mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-11-28 22:58:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a84724665e | ||
|
|
e1bdfba0fb | ||
|
|
4f927ca12e | ||
|
|
8a029da50b | ||
|
|
ec664a511f | ||
|
|
d701d1c0e3 | ||
|
|
2cfff83e85 | ||
|
|
3f2b0ba631 | ||
|
|
4d83fb861c | ||
|
|
4814c727f5 | ||
|
|
03253614c5 | ||
|
|
7e83399a3f | ||
|
|
df6a5d3fe3 | ||
|
|
c39b680c52 | ||
|
|
ebc41ea8fd | ||
|
|
dfc888d060 | ||
|
|
2337d70d86 | ||
|
|
0e0265fdd6 | ||
|
|
3d6add33d5 | ||
|
|
2247c0ebb4 | ||
|
|
f425c81a85 | ||
|
|
e4099f0fa1 | ||
|
|
37942ce9d8 | ||
|
|
49858024ef | ||
|
|
7ab4eed838 | ||
|
|
d4c4b2851f | ||
|
|
b0b28ef002 | ||
|
|
e38aa82a23 | ||
|
|
e0a42d4e07 | ||
|
|
83ac220f54 | ||
|
|
6c407f0f93 | ||
|
|
a450080ed1 | ||
|
|
700e25fd2f | ||
|
|
ad91303f99 | ||
|
|
cac48917f1 | ||
|
|
db25932646 | ||
|
|
7abf290477 | ||
|
|
f0ad835df1 | ||
|
|
4ee2251c37 | ||
|
|
fe7f3d61db | ||
|
|
5b013f25cf | ||
|
|
fcbcd10bb0 | ||
|
|
d4b3d236da | ||
|
|
299fd33795 | ||
|
|
b00c985728 | ||
|
|
4387c674ca | ||
|
|
20cb280c9d | ||
|
|
9613f02a05 | ||
|
|
6fb9d9e433 | ||
|
|
0495d295e0 | ||
|
|
1bee5901de | ||
|
|
2fbed16d9a | ||
|
|
80072ebb6f | ||
|
|
d8cb32b856 | ||
|
|
fdafea36ce | ||
|
|
808c0d6251 | ||
|
|
6b076839c6 | ||
|
|
1b2ea14596 | ||
|
|
7b73775591 | ||
|
|
96a6962b3f | ||
|
|
299a63f8f6 | ||
|
|
acc4f626ad | ||
|
|
db63ffbbf6 | ||
|
|
b0ea75bd21 | ||
|
|
fa081fb16c | ||
|
|
0f71808cbe | ||
|
|
885244a9a0 | ||
|
|
ab3746a1d8 | ||
|
|
d9c447a816 | ||
|
|
6791df12e0 | ||
|
|
f5183da5a9 | ||
|
|
61dc7b1038 | ||
|
|
cacd01a3b3 | ||
|
|
d801e6b67b | ||
|
|
8c1b1a3ee2 | ||
|
|
f109b8b095 |
No files matched your search
@@ -381,7 +381,7 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Upload Prerelease
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
@@ -443,7 +443,7 @@ jobs:
|
||||
working-directory: bin
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag_name: ${{ github.event.inputs.version }}
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
- 'macos-latest' # arm64 macos
|
||||
- 'ubuntu-24.04-arm' # arm64 linux
|
||||
- 'windows-11-arm' # arm64 windows
|
||||
- 'macos-15-intel' # amd64 macos
|
||||
- 'macos-26-intel' # amd64 macos
|
||||
go-version:
|
||||
- '1.26'
|
||||
- '1.25'
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
- uses: actions/create-github-app-token@v3
|
||||
id: generate-token
|
||||
with:
|
||||
app-id: ${{ secrets.MAINTAINER_APPID }}
|
||||
client-id: ${{ secrets.MAINTAINER_APPID }}
|
||||
private-key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
|
||||
+12
-12
@@ -86,18 +86,18 @@ func (t *AnyTLS) Close() error {
|
||||
func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &AnyTLS{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.AnyTLS,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.AnyTLS,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
+35
-34
@@ -16,6 +16,8 @@ import (
|
||||
"github.com/metacubex/mihomo/component/resolver"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
type ProxyAdapter interface {
|
||||
@@ -37,7 +39,38 @@ type Base struct {
|
||||
rmark int
|
||||
prefer C.DNSPrefer
|
||||
dialer C.Dialer
|
||||
id string
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
type BaseOption struct {
|
||||
Name string
|
||||
Addr string
|
||||
Type C.AdapterType
|
||||
ProviderName string
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
MPTCP bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
Prefer C.DNSPrefer
|
||||
}
|
||||
|
||||
func NewBase(opt BaseOption) *Base {
|
||||
return &Base{
|
||||
name: opt.Name,
|
||||
addr: opt.Addr,
|
||||
tp: opt.Type,
|
||||
pdName: opt.ProviderName,
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
mpTcp: opt.MPTCP,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
prefer: opt.Prefer,
|
||||
id: utils.NewUUIDV6(),
|
||||
}
|
||||
}
|
||||
|
||||
// Name implements C.ProxyAdapter
|
||||
@@ -47,11 +80,7 @@ func (b *Base) Name() string {
|
||||
|
||||
// Id implements C.ProxyAdapter
|
||||
func (b *Base) Id() string {
|
||||
if b.id == "" {
|
||||
b.id = utils.NewUUIDV6().String()
|
||||
}
|
||||
|
||||
return b.id
|
||||
return b.id.String()
|
||||
}
|
||||
|
||||
// Type implements C.ProxyAdapter
|
||||
@@ -188,34 +217,6 @@ func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
|
||||
return cDialer
|
||||
}
|
||||
|
||||
type BaseOption struct {
|
||||
Name string
|
||||
Addr string
|
||||
Type C.AdapterType
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
MPTCP bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
Prefer C.DNSPrefer
|
||||
}
|
||||
|
||||
func NewBase(opt BaseOption) *Base {
|
||||
return &Base{
|
||||
name: opt.Name,
|
||||
addr: opt.Addr,
|
||||
tp: opt.Type,
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
mpTcp: opt.MPTCP,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
prefer: opt.Prefer,
|
||||
}
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
N.ExtendedConn
|
||||
chain C.Chain
|
||||
|
||||
+23
-23
@@ -66,41 +66,41 @@ func (d *Direct) IsL3Protocol(metadata *C.Metadata) bool {
|
||||
|
||||
func NewDirectWithOption(option DirectOption) *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Direct,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Direct,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewDirect() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "DIRECT",
|
||||
tp: C.Direct,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "DIRECT",
|
||||
Type: C.Direct,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewCompatible() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "COMPATIBLE",
|
||||
tp: C.Compatible,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "COMPATIBLE",
|
||||
Type: C.Compatible,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
loopBack: loopback.NewDetector(),
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -155,16 +155,16 @@ func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
|
||||
func NewDnsWithOption(option DnsOption) *Dns {
|
||||
return &Dns{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Dns,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Dns,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -167,17 +167,17 @@ func NewHttp(option HttpOption) (*Http, error) {
|
||||
}
|
||||
|
||||
outbound := &Http{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Http,
|
||||
pdName: option.ProviderName,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Http,
|
||||
ProviderName: option.ProviderName,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
user: option.UserName,
|
||||
pass: option.Password,
|
||||
tlsConfig: tlsConfig,
|
||||
|
||||
@@ -239,17 +239,17 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||
}
|
||||
outbound := &Hysteria{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Hysteria,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.FastOpen,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Hysteria,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.FastOpen,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
client: client,
|
||||
tlsConfig: tlsClientConfig,
|
||||
|
||||
@@ -11,21 +11,17 @@ import (
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/component/ca"
|
||||
"github.com/metacubex/mihomo/component/proxydialer"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
qtls "github.com/metacubex/sing-quic"
|
||||
"github.com/metacubex/sing-quic/hysteria2"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
func init() {
|
||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||
}
|
||||
|
||||
const minHopInterval = 5
|
||||
const defaultHopInterval = 30
|
||||
|
||||
@@ -42,7 +38,7 @@ type Hysteria2Option struct {
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port,omitempty"`
|
||||
Ports string `proxy:"ports,omitempty"`
|
||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||
HopInterval string `proxy:"hop-interval,omitempty"`
|
||||
Up string `proxy:"up,omitempty"`
|
||||
Down string `proxy:"down,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
@@ -56,6 +52,7 @@ type Hysteria2Option struct {
|
||||
PrivateKey string `proxy:"private-key,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||
|
||||
// quic-go special config
|
||||
@@ -105,20 +102,19 @@ func (h *Hysteria2) ProxyInfo() C.ProxyInfo {
|
||||
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &Hysteria2{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Hysteria2,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Hysteria2,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
singDialer := proxydialer.NewSingDialer(outbound.dialer)
|
||||
|
||||
var salamanderPassword string
|
||||
if len(option.Obfs) > 0 {
|
||||
@@ -177,7 +173,6 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
|
||||
clientOptions := hysteria2.ClientOptions{
|
||||
Context: context.TODO(),
|
||||
Dialer: singDialer,
|
||||
Logger: log.SingLogger,
|
||||
SendBPS: StringToBps(option.Up),
|
||||
ReceiveBPS: StringToBps(option.Down),
|
||||
@@ -186,25 +181,24 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
TLSConfig: tlsClientConfig,
|
||||
QUICConfig: quicConfig,
|
||||
UDPDisabled: false,
|
||||
CWND: option.CWND,
|
||||
UdpMTU: option.UdpMTU,
|
||||
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", addr, option.IPVersion)
|
||||
ServerAddress: M.ParseSocksaddr(addr),
|
||||
PacketListener: outbound.dialer,
|
||||
QuicDialer: qtls.QuicDialerFunc(func(ctx context.Context, addr string, dialer qtls.PacketDialer, tlsCfg *tls.Config, cfg *quic.Config, early bool) (net.PacketConn, *quic.Conn, error) {
|
||||
err := echConfig.ClientHandle(ctx, tlsCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
err = echConfig.ClientHandle(ctx, tlsClientConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return udpAddr, nil
|
||||
return common.DialQuic(ctx, addr, outbound.DialOptions(), dialer, tlsCfg, cfg, early)
|
||||
}),
|
||||
SetBBRCongestion: func(quicConn *quic.Conn) {
|
||||
common.SetCongestionController(quicConn, "bbr", option.CWND, option.BBRProfile)
|
||||
},
|
||||
}
|
||||
|
||||
var ranges utils.IntRanges[uint16]
|
||||
var serverPorts []uint16
|
||||
if option.Ports != "" {
|
||||
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
||||
ranges, err := utils.NewUnsignedRanges[uint16](option.Ports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -213,12 +207,21 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||
return true
|
||||
})
|
||||
if len(serverPorts) > 0 {
|
||||
if option.HopInterval == 0 {
|
||||
option.HopInterval = defaultHopInterval
|
||||
} else if option.HopInterval < minHopInterval {
|
||||
option.HopInterval = minHopInterval
|
||||
hopRange, err := utils.NewUnsignedRange[uint64](option.HopInterval)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
||||
start, end := hopRange.Start(), hopRange.End()
|
||||
if start == 0 {
|
||||
start = defaultHopInterval
|
||||
} else if start < minHopInterval {
|
||||
start = minHopInterval
|
||||
}
|
||||
if end < start {
|
||||
end = start
|
||||
}
|
||||
clientOptions.HopInterval = time.Duration(start) * time.Second
|
||||
clientOptions.HopIntervalMax = time.Duration(end) * time.Second
|
||||
clientOptions.ServerPorts = serverPorts
|
||||
}
|
||||
}
|
||||
|
||||
+76
-56
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
@@ -25,7 +26,7 @@ import (
|
||||
"github.com/metacubex/mihomo/transport/masque"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
connectip "github.com/metacubex/connect-ip-go"
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go"
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
@@ -34,11 +35,12 @@ import (
|
||||
|
||||
type Masque struct {
|
||||
*Base
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
tlsConfig *tls.Config
|
||||
quicConfig *quic.Config
|
||||
tunDevice wireguard.Device
|
||||
resolver resolver.Resolver
|
||||
uri string
|
||||
h2Transport *http.Http2Transport
|
||||
|
||||
runCtx context.Context
|
||||
runCancel context.CancelFunc
|
||||
@@ -51,20 +53,23 @@ 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"`
|
||||
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"`
|
||||
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
|
||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||
Dns []string `proxy:"dns,omitempty"`
|
||||
@@ -100,16 +105,16 @@ func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
|
||||
|
||||
func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
outbound := &Masque{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Masque,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Masque,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
@@ -150,12 +155,26 @@ func NewMasque(option MasqueOption) (*Masque, error) {
|
||||
sni = masque.ConnectSNI
|
||||
}
|
||||
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni)
|
||||
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni, option.SkipCertVerify)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare TLS config: %v\n", err)
|
||||
}
|
||||
outbound.tlsConfig = tlsConfig
|
||||
|
||||
if option.Network == "h2" {
|
||||
tlsConfig.NextProtos = []string{"h2"}
|
||||
outbound.h2Transport = &http.Http2Transport{
|
||||
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||
c, err := outbound.dialer.DialContext(ctx, "tcp", outbound.addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tls.Client(c, tlsConfig), nil
|
||||
},
|
||||
ReadIdleTimeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
outbound.quicConfig = &quic.Config{
|
||||
EnableDatagrams: true,
|
||||
InitialPacketSize: 1242,
|
||||
@@ -229,27 +248,28 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
w.runDevice.Store(true)
|
||||
}
|
||||
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", w.addr, w.prefer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var pc net.PacketConn
|
||||
var closer io.Closer
|
||||
var ipConn masque.IpConn
|
||||
var err error
|
||||
if w.h2Transport != nil {
|
||||
closer, ipConn, err = masque.ConnectTunnelH2(ctx, w.h2Transport, w.uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
var quicConn *quic.Conn
|
||||
pc, quicConn, err = common.DialQuic(ctx, w.addr, w.DialOptions(), w.dialer, w.tlsConfig, w.quicConfig, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND, w.option.BBRProfile)
|
||||
|
||||
pc, err := w.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
quicConn, err := quic.Dial(ctx, pc, udpAddr, w.tlsConfig, w.quicConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND)
|
||||
|
||||
tr, ipConn, err := masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
_ = pc.Close()
|
||||
return err
|
||||
closer, ipConn, err = masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||
if err != nil {
|
||||
_ = pc.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
w.running.Store(true)
|
||||
@@ -258,8 +278,10 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
contextutils.AfterFunc(runCtx, func() {
|
||||
w.running.Store(false)
|
||||
_ = ipConn.Close()
|
||||
_ = tr.Close()
|
||||
_ = pc.Close()
|
||||
_ = closer.Close()
|
||||
if pc != nil {
|
||||
_ = pc.Close()
|
||||
}
|
||||
})
|
||||
|
||||
go func() {
|
||||
@@ -276,7 +298,7 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
}
|
||||
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
@@ -294,19 +316,17 @@ func (w *Masque) run(ctx context.Context) error {
|
||||
|
||||
go func() {
|
||||
defer runCancel()
|
||||
buf := pool.Get(pool.UDPBufferSize)
|
||||
defer pool.Put(buf)
|
||||
for runCtx.Err() == nil {
|
||||
n, err := ipConn.ReadPacket(buf)
|
||||
buf, err := ipConn.ReadPacket()
|
||||
if err != nil {
|
||||
if errors.As(err, new(*connectip.CloseError)) {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
log.Warnln("[Masque](%s) error reading from IP connection: %v, continuing...", w.name, err)
|
||||
continue
|
||||
}
|
||||
if _, err := w.tunDevice.Write([][]byte{buf[:n]}, 0); err != nil {
|
||||
if _, err := w.tunDevice.Write([][]byte{buf}, 0); err != nil {
|
||||
log.Errorln("[Masque](%s) error writing to TUN device: %v", w.name, err)
|
||||
return
|
||||
}
|
||||
|
||||
+12
-11
@@ -166,17 +166,18 @@ func NewMieru(option MieruOption) (*Mieru, error) {
|
||||
addr = net.JoinHostPort(option.Server, strconv.Itoa(beginPort))
|
||||
}
|
||||
outbound := &Mieru{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Mieru,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: false,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Mieru,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
client: c,
|
||||
}
|
||||
|
||||
+17
-17
@@ -46,33 +46,33 @@ func (r *Reject) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||
|
||||
func NewRejectWithOption(option RejectOption) *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Reject,
|
||||
udp: true,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Reject,
|
||||
UDP: true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func NewReject() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "REJECT",
|
||||
tp: C.Reject,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "REJECT",
|
||||
Type: C.Reject,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func NewRejectDrop() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "REJECT-DROP",
|
||||
tp: C.RejectDrop,
|
||||
udp: true,
|
||||
prefer: C.DualStack,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: "REJECT-DROP",
|
||||
Type: C.RejectDrop,
|
||||
UDP: true,
|
||||
Prefer: C.DualStack,
|
||||
}),
|
||||
drop: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,18 +446,18 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
}
|
||||
|
||||
outbound := &ShadowSocks{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Shadowsocks,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Shadowsocks,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
method: method,
|
||||
|
||||
option: &option,
|
||||
|
||||
@@ -158,18 +158,18 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||
}
|
||||
|
||||
outbound := &ShadowSocksR{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.ShadowsocksR,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.ShadowsocksR,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
cipher: coreCiph,
|
||||
obfs: obfs,
|
||||
|
||||
@@ -103,6 +103,7 @@ func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error)
|
||||
MinStreams: option.MinStreams,
|
||||
MaxStreams: option.MaxStreams,
|
||||
Padding: option.Padding,
|
||||
TCPTimeout: C.DefaultTCPTimeout,
|
||||
Brutal: mux.BrutalOptions{
|
||||
Enabled: option.BrutalOpts.Enabled,
|
||||
SendBPS: StringToBps(option.BrutalOpts.Up),
|
||||
|
||||
+12
-12
@@ -161,18 +161,18 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
}
|
||||
|
||||
s := &Snell{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Snell,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Snell,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
psk: psk,
|
||||
obfsOption: obfsOption,
|
||||
|
||||
+12
-14
@@ -98,8 +98,6 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
|
||||
if ss.tls {
|
||||
cc := tls.Client(c, ss.tlsConfig)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
err = cc.HandshakeContext(ctx)
|
||||
c = cc
|
||||
}
|
||||
@@ -187,18 +185,18 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||
}
|
||||
|
||||
outbound := &Socks5{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Socks5,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Socks5,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
user: option.UserName,
|
||||
pass: option.Password,
|
||||
|
||||
+12
-10
@@ -182,16 +182,18 @@ func NewSsh(option SshOption) (*Ssh, error) {
|
||||
config.ClientVersion = version
|
||||
|
||||
outbound := &Ssh{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Ssh,
|
||||
pdName: option.ProviderName,
|
||||
udp: false,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Ssh,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: false,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
config: &config,
|
||||
}
|
||||
|
||||
+12
-12
@@ -223,18 +223,18 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
}
|
||||
|
||||
outbound := &Sudoku{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: baseConf.ServerAddress,
|
||||
tp: C.Sudoku,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: baseConf.ServerAddress,
|
||||
Type: C.Sudoku,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
baseConf: baseConf,
|
||||
}
|
||||
|
||||
+12
-12
@@ -253,18 +253,18 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
}
|
||||
|
||||
t := &Trojan{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Trojan,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Trojan,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
hexPassword: trojan.Key(option.Password),
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package outbound
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
@@ -39,6 +38,7 @@ type TrustTunnelOption struct {
|
||||
Quic bool `proxy:"quic,omitempty"`
|
||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
// reuse options
|
||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||
MinStreams int `proxy:"min-streams,omitempty"`
|
||||
@@ -86,37 +86,32 @@ func (t *TrustTunnel) Close() error {
|
||||
func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
outbound := &TrustTunnel{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.TrustTunnel,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.TrustTunnel,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
|
||||
tOption := trusttunnel.ClientOptions{
|
||||
Dialer: outbound.dialer,
|
||||
ResolvUDP: func(ctx context.Context, server string) (netip.AddrPort, error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", server, option.IPVersion)
|
||||
if err != nil {
|
||||
return netip.AddrPort{}, err
|
||||
}
|
||||
return udpAddr.AddrPort(), nil
|
||||
},
|
||||
Dialer: outbound.dialer,
|
||||
DialOptions: outbound.DialOptions,
|
||||
Server: addr,
|
||||
Username: option.UserName,
|
||||
Password: option.Password,
|
||||
QUIC: option.Quic,
|
||||
QUICCongestionControl: option.CongestionController,
|
||||
QUICCwnd: option.CWND,
|
||||
QUICBBRProfile: option.BBRProfile,
|
||||
HealthCheck: option.HealthCheck,
|
||||
MaxConnections: option.MaxConnections,
|
||||
MinStreams: option.MinStreams,
|
||||
|
||||
+25
-44
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/tuic"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/metacubex/quic-go"
|
||||
@@ -25,8 +26,9 @@ type Tuic struct {
|
||||
option *TuicOption
|
||||
client *tuic.PoolClient
|
||||
|
||||
tlsConfig *tls.Config
|
||||
echConfig *ech.Config
|
||||
quicConfig *quic.Config
|
||||
tlsConfig *tls.Config
|
||||
echConfig *ech.Config
|
||||
}
|
||||
|
||||
type TuicOption struct {
|
||||
@@ -50,6 +52,7 @@ type TuicOption struct {
|
||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
BBRProfile string `proxy:"bbr-profile,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
Certificate string `proxy:"certificate,omitempty"`
|
||||
@@ -106,25 +109,13 @@ func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_
|
||||
return newPacketConn(pc, t), nil
|
||||
}
|
||||
|
||||
func (t *Tuic) dial(ctx context.Context) (transport *quic.Transport, addr net.Addr, err error) {
|
||||
udpAddr, err := resolveUDPAddr(ctx, "udp", t.addr, t.prefer)
|
||||
func (t *Tuic) dial(ctx context.Context) (quicConn *quic.Conn, err error) {
|
||||
_, quicConn, err = common.DialQuic(ctx, t.addr, t.DialOptions(), t.dialer, t.tlsConfig, t.quicConfig, t.option.ReduceRtt)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
err = t.echConfig.ClientHandle(ctx, t.tlsConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
addr = udpAddr
|
||||
var pc net.PacketConn
|
||||
pc, err = t.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
transport = &quic.Transport{Conn: pc}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
return
|
||||
common.SetCongestionController(quicConn, t.option.CongestionController, t.option.CWND, t.option.BBRProfile)
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// ProxyInfo implements C.ProxyAdapter
|
||||
@@ -232,7 +223,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
tlsConfig.InsecureSkipVerify = true // tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
|
||||
}
|
||||
|
||||
tlsClientConfig := tlsConfig
|
||||
echConfig, err := option.ECHOpts.Parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -247,20 +237,21 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
}
|
||||
|
||||
t := &Tuic{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Tuic,
|
||||
pdName: option.ProviderName,
|
||||
udp: true,
|
||||
tfo: option.FastOpen,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
option: &option,
|
||||
tlsConfig: tlsClientConfig,
|
||||
echConfig: echConfig,
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: addr,
|
||||
Type: C.Tuic,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: true,
|
||||
TFO: option.FastOpen,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
option: &option,
|
||||
quicConfig: quicConfig,
|
||||
tlsConfig: tlsConfig,
|
||||
echConfig: echConfig,
|
||||
}
|
||||
t.dialer = option.NewDialer(t.DialOptions())
|
||||
|
||||
@@ -278,17 +269,12 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
if len(option.Token) > 0 {
|
||||
tkn := tuic.GenTKN(option.Token)
|
||||
clientOption := &tuic.ClientOptionV4{
|
||||
TlsConfig: tlsClientConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Token: tkn,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||
FastOpen: option.FastOpen,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV4(clientOption, t.dial)
|
||||
@@ -298,16 +284,11 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
maxUdpRelayPacketSize = tuic.MaxFragSizeV5
|
||||
}
|
||||
clientOption := &tuic.ClientOptionV5{
|
||||
TlsConfig: tlsClientConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Uuid: uuid.FromStringOrNil(option.UUID),
|
||||
Password: option.Password,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
MaxUdpRelayPacketSize: maxUdpRelayPacketSize,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV5(clientOption, t.dial)
|
||||
|
||||
+184
-48
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/convert"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
@@ -15,12 +16,14 @@ 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/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/vless"
|
||||
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
"github.com/metacubex/mihomo/transport/xhttp"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go"
|
||||
vmessSing "github.com/metacubex/sing-vmess"
|
||||
"github.com/metacubex/sing-vmess/packetaddr"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
@@ -76,34 +79,63 @@ type VlessOption struct {
|
||||
}
|
||||
|
||||
type XHTTPOptions struct {
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
Mode string `proxy:"mode,omitempty"`
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"`
|
||||
XPaddingBytes string `proxy:"x-padding-bytes,omitempty"`
|
||||
ScMaxEachPostBytes int `proxy:"sc-max-each-post-bytes,omitempty"`
|
||||
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
|
||||
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"`
|
||||
Path string `proxy:"path,omitempty"`
|
||||
Host string `proxy:"host,omitempty"`
|
||||
Mode string `proxy:"mode,omitempty"`
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"`
|
||||
XPaddingBytes string `proxy:"x-padding-bytes,omitempty"`
|
||||
XPaddingObfsMode bool `proxy:"x-padding-obfs-mode,omitempty"`
|
||||
XPaddingKey string `proxy:"x-padding-key,omitempty"`
|
||||
XPaddingHeader string `proxy:"x-padding-header,omitempty"`
|
||||
XPaddingPlacement string `proxy:"x-padding-placement,omitempty"`
|
||||
XPaddingMethod string `proxy:"x-padding-method,omitempty"`
|
||||
UplinkHTTPMethod string `proxy:"uplink-http-method,omitempty"`
|
||||
SessionPlacement string `proxy:"session-placement,omitempty"`
|
||||
SessionKey string `proxy:"session-key,omitempty"`
|
||||
SeqPlacement string `proxy:"seq-placement,omitempty"`
|
||||
SeqKey string `proxy:"seq-key,omitempty"`
|
||||
UplinkDataPlacement string `proxy:"uplink-data-placement,omitempty"`
|
||||
UplinkDataKey string `proxy:"uplink-data-key,omitempty"`
|
||||
UplinkChunkSize string `proxy:"uplink-chunk-size,omitempty"`
|
||||
ScMaxEachPostBytes string `proxy:"sc-max-each-post-bytes,omitempty"`
|
||||
ScMinPostsIntervalMs string `proxy:"sc-min-posts-interval-ms,omitempty"`
|
||||
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
|
||||
DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"`
|
||||
}
|
||||
|
||||
type XHTTPReuseSettings struct {
|
||||
MaxConnections string `proxy:"max-connections,omitempty"`
|
||||
MaxConcurrency string `proxy:"max-concurrency,omitempty"`
|
||||
MaxConnections string `proxy:"max-connections,omitempty"`
|
||||
CMaxReuseTimes string `proxy:"c-max-reuse-times,omitempty"`
|
||||
HMaxRequestTimes string `proxy:"h-max-request-times,omitempty"`
|
||||
HMaxReusableSecs string `proxy:"h-max-reusable-secs,omitempty"`
|
||||
HKeepAlivePeriod int `proxy:"h-keep-alive-period,omitempty"`
|
||||
}
|
||||
|
||||
type XHTTPDownloadSettings struct {
|
||||
// xhttp part
|
||||
Path *string `proxy:"path,omitempty"`
|
||||
Host *string `proxy:"host,omitempty"`
|
||||
Headers *map[string]string `proxy:"headers,omitempty"`
|
||||
NoGRPCHeader *bool `proxy:"no-grpc-header,omitempty"`
|
||||
XPaddingBytes *string `proxy:"x-padding-bytes,omitempty"`
|
||||
ScMaxEachPostBytes *int `proxy:"sc-max-each-post-bytes,omitempty"`
|
||||
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
|
||||
Path *string `proxy:"path,omitempty"`
|
||||
Host *string `proxy:"host,omitempty"`
|
||||
Headers *map[string]string `proxy:"headers,omitempty"`
|
||||
NoGRPCHeader *bool `proxy:"no-grpc-header,omitempty"`
|
||||
XPaddingBytes *string `proxy:"x-padding-bytes,omitempty"`
|
||||
XPaddingObfsMode *bool `proxy:"x-padding-obfs-mode,omitempty"`
|
||||
XPaddingKey *string `proxy:"x-padding-key,omitempty"`
|
||||
XPaddingHeader *string `proxy:"x-padding-header,omitempty"`
|
||||
XPaddingPlacement *string `proxy:"x-padding-placement,omitempty"`
|
||||
XPaddingMethod *string `proxy:"x-padding-method,omitempty"`
|
||||
UplinkHTTPMethod *string `proxy:"uplink-http-method,omitempty"`
|
||||
SessionPlacement *string `proxy:"session-placement,omitempty"`
|
||||
SessionKey *string `proxy:"session-key,omitempty"`
|
||||
SeqPlacement *string `proxy:"seq-placement,omitempty"`
|
||||
SeqKey *string `proxy:"seq-key,omitempty"`
|
||||
UplinkDataPlacement *string `proxy:"uplink-data-placement,omitempty"`
|
||||
UplinkDataKey *string `proxy:"uplink-data-key,omitempty"`
|
||||
UplinkChunkSize *string `proxy:"uplink-chunk-size,omitempty"`
|
||||
ScMaxEachPostBytes *string `proxy:"sc-max-each-post-bytes,omitempty"`
|
||||
ScMinPostsIntervalMs *string `proxy:"sc-min-posts-interval-ms,omitempty"`
|
||||
ReuseSettings *XHTTPReuseSettings `proxy:"reuse-settings,omitempty"` // aka XMUX
|
||||
// proxy part
|
||||
Server *string `proxy:"server,omitempty"`
|
||||
Port *int `proxy:"port,omitempty"`
|
||||
@@ -432,19 +464,19 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
|
||||
v := &Vless{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vless,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Vless,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
XUDP: option.XUDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
client: client,
|
||||
option: &option,
|
||||
}
|
||||
@@ -525,26 +557,43 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
var hKeepAlivePeriod time.Duration
|
||||
|
||||
var reuseCfg *xhttp.ReuseConfig
|
||||
if option.XHTTPOpts.ReuseSettings != nil {
|
||||
reuseCfg = &xhttp.ReuseConfig{
|
||||
MaxConnections: option.XHTTPOpts.ReuseSettings.MaxConnections,
|
||||
MaxConcurrency: option.XHTTPOpts.ReuseSettings.MaxConcurrency,
|
||||
MaxConnections: option.XHTTPOpts.ReuseSettings.MaxConnections,
|
||||
CMaxReuseTimes: option.XHTTPOpts.ReuseSettings.CMaxReuseTimes,
|
||||
HMaxRequestTimes: option.XHTTPOpts.ReuseSettings.HMaxRequestTimes,
|
||||
HMaxReusableSecs: option.XHTTPOpts.ReuseSettings.HMaxReusableSecs,
|
||||
}
|
||||
hKeepAlivePeriod = time.Duration(option.XHTTPOpts.ReuseSettings.HKeepAlivePeriod) * time.Second
|
||||
}
|
||||
|
||||
cfg := &xhttp.Config{
|
||||
Host: requestHost,
|
||||
Path: v.option.XHTTPOpts.Path,
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: v.option.XHTTPOpts.Headers,
|
||||
NoGRPCHeader: v.option.XHTTPOpts.NoGRPCHeader,
|
||||
XPaddingBytes: v.option.XHTTPOpts.XPaddingBytes,
|
||||
ScMaxEachPostBytes: v.option.XHTTPOpts.ScMaxEachPostBytes,
|
||||
ReuseConfig: reuseCfg,
|
||||
Host: requestHost,
|
||||
Path: v.option.XHTTPOpts.Path,
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: v.option.XHTTPOpts.Headers,
|
||||
NoGRPCHeader: v.option.XHTTPOpts.NoGRPCHeader,
|
||||
XPaddingBytes: v.option.XHTTPOpts.XPaddingBytes,
|
||||
XPaddingObfsMode: v.option.XHTTPOpts.XPaddingObfsMode,
|
||||
XPaddingKey: v.option.XHTTPOpts.XPaddingKey,
|
||||
XPaddingHeader: v.option.XHTTPOpts.XPaddingHeader,
|
||||
XPaddingPlacement: v.option.XHTTPOpts.XPaddingPlacement,
|
||||
XPaddingMethod: v.option.XHTTPOpts.XPaddingMethod,
|
||||
UplinkHTTPMethod: v.option.XHTTPOpts.UplinkHTTPMethod,
|
||||
SessionPlacement: v.option.XHTTPOpts.SessionPlacement,
|
||||
SessionKey: v.option.XHTTPOpts.SessionKey,
|
||||
SeqPlacement: v.option.XHTTPOpts.SeqPlacement,
|
||||
SeqKey: v.option.XHTTPOpts.SeqKey,
|
||||
UplinkDataPlacement: v.option.XHTTPOpts.UplinkDataPlacement,
|
||||
UplinkDataKey: v.option.XHTTPOpts.UplinkDataKey,
|
||||
UplinkChunkSize: v.option.XHTTPOpts.UplinkChunkSize,
|
||||
ScMaxEachPostBytes: v.option.XHTTPOpts.ScMaxEachPostBytes,
|
||||
ScMinPostsIntervalMs: v.option.XHTTPOpts.ScMinPostsIntervalMs,
|
||||
ReuseConfig: reuseCfg,
|
||||
}
|
||||
|
||||
makeTransport := func() http.RoundTripper {
|
||||
@@ -555,7 +604,42 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
func(ctx context.Context, raw net.Conn, isH2 bool) (net.Conn, error) {
|
||||
return v.streamTLSConn(ctx, raw, isH2)
|
||||
},
|
||||
func(ctx context.Context, cfg *quic.Config) (*quic.Conn, error) {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Certificate: v.option.Certificate,
|
||||
PrivateKey: v.option.PrivateKey,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
ECH: v.echConfig,
|
||||
Reality: v.realityConfig,
|
||||
NextProtos: []string{"h3"},
|
||||
}
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
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")
|
||||
}
|
||||
tlsConfig, err := tlsOpts.ToStdConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = v.echConfig.ClientHandle(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, quicConn, err := common.DialQuic(ctx, v.addr, v.DialOptions(), v.dialer, tlsConfig, cfg, true)
|
||||
return quicConn, nil
|
||||
},
|
||||
v.option.ALPN,
|
||||
hKeepAlivePeriod,
|
||||
)
|
||||
}
|
||||
var makeDownloadTransport func() http.RoundTripper
|
||||
@@ -601,26 +685,43 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
downloadHKeepAlivePeriod := hKeepAlivePeriod
|
||||
|
||||
downloadReuseCfg := reuseCfg
|
||||
if ds.ReuseSettings != nil {
|
||||
downloadReuseCfg = &xhttp.ReuseConfig{
|
||||
MaxConnections: ds.ReuseSettings.MaxConnections,
|
||||
MaxConcurrency: ds.ReuseSettings.MaxConcurrency,
|
||||
MaxConnections: ds.ReuseSettings.MaxConnections,
|
||||
CMaxReuseTimes: ds.ReuseSettings.CMaxReuseTimes,
|
||||
HMaxRequestTimes: ds.ReuseSettings.HMaxRequestTimes,
|
||||
HMaxReusableSecs: ds.ReuseSettings.HMaxReusableSecs,
|
||||
}
|
||||
downloadHKeepAlivePeriod = time.Duration(ds.ReuseSettings.HKeepAlivePeriod) * time.Second
|
||||
}
|
||||
|
||||
cfg.DownloadConfig = &xhttp.Config{
|
||||
Host: downloadHost,
|
||||
Path: lo.FromPtrOr(ds.Path, v.option.XHTTPOpts.Path),
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: lo.FromPtrOr(ds.Headers, v.option.XHTTPOpts.Headers),
|
||||
NoGRPCHeader: lo.FromPtrOr(ds.NoGRPCHeader, v.option.XHTTPOpts.NoGRPCHeader),
|
||||
XPaddingBytes: lo.FromPtrOr(ds.XPaddingBytes, v.option.XHTTPOpts.XPaddingBytes),
|
||||
ScMaxEachPostBytes: lo.FromPtrOr(ds.ScMaxEachPostBytes, v.option.XHTTPOpts.ScMaxEachPostBytes),
|
||||
ReuseConfig: downloadReuseCfg,
|
||||
Host: downloadHost,
|
||||
Path: lo.FromPtrOr(ds.Path, v.option.XHTTPOpts.Path),
|
||||
Mode: v.option.XHTTPOpts.Mode,
|
||||
Headers: lo.FromPtrOr(ds.Headers, v.option.XHTTPOpts.Headers),
|
||||
NoGRPCHeader: lo.FromPtrOr(ds.NoGRPCHeader, v.option.XHTTPOpts.NoGRPCHeader),
|
||||
XPaddingBytes: lo.FromPtrOr(ds.XPaddingBytes, v.option.XHTTPOpts.XPaddingBytes),
|
||||
XPaddingObfsMode: lo.FromPtrOr(ds.XPaddingObfsMode, v.option.XHTTPOpts.XPaddingObfsMode),
|
||||
XPaddingKey: lo.FromPtrOr(ds.XPaddingKey, v.option.XHTTPOpts.XPaddingKey),
|
||||
XPaddingHeader: lo.FromPtrOr(ds.XPaddingHeader, v.option.XHTTPOpts.XPaddingHeader),
|
||||
XPaddingPlacement: lo.FromPtrOr(ds.XPaddingPlacement, v.option.XHTTPOpts.XPaddingPlacement),
|
||||
XPaddingMethod: lo.FromPtrOr(ds.XPaddingMethod, v.option.XHTTPOpts.XPaddingMethod),
|
||||
UplinkHTTPMethod: lo.FromPtrOr(ds.UplinkHTTPMethod, v.option.XHTTPOpts.UplinkHTTPMethod),
|
||||
SessionPlacement: lo.FromPtrOr(ds.SessionPlacement, v.option.XHTTPOpts.SessionPlacement),
|
||||
SessionKey: lo.FromPtrOr(ds.SessionKey, v.option.XHTTPOpts.SessionKey),
|
||||
SeqPlacement: lo.FromPtrOr(ds.SeqPlacement, v.option.XHTTPOpts.SeqPlacement),
|
||||
SeqKey: lo.FromPtrOr(ds.SeqKey, v.option.XHTTPOpts.SeqKey),
|
||||
UplinkDataPlacement: lo.FromPtrOr(ds.UplinkDataPlacement, v.option.XHTTPOpts.UplinkDataPlacement),
|
||||
UplinkDataKey: lo.FromPtrOr(ds.UplinkDataKey, v.option.XHTTPOpts.UplinkDataKey),
|
||||
UplinkChunkSize: lo.FromPtrOr(ds.UplinkChunkSize, v.option.XHTTPOpts.UplinkChunkSize),
|
||||
ScMaxEachPostBytes: lo.FromPtrOr(ds.ScMaxEachPostBytes, v.option.XHTTPOpts.ScMaxEachPostBytes),
|
||||
ScMinPostsIntervalMs: lo.FromPtrOr(ds.ScMinPostsIntervalMs, v.option.XHTTPOpts.ScMinPostsIntervalMs),
|
||||
ReuseConfig: downloadReuseCfg,
|
||||
}
|
||||
|
||||
makeDownloadTransport = func() http.RoundTripper {
|
||||
@@ -657,7 +758,42 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
|
||||
return conn, nil
|
||||
},
|
||||
func(ctx context.Context, cfg *quic.Config) (*quic.Conn, error) {
|
||||
host, _, _ := net.SplitHostPort(downloadAddr)
|
||||
tlsOpts := &vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: downloadSkipCertVerify,
|
||||
FingerPrint: downloadFingerprint,
|
||||
Certificate: downloadCertificate,
|
||||
PrivateKey: downloadPrivateKey,
|
||||
ClientFingerprint: downloadClientFingerprint,
|
||||
ECH: downloadEchConfig,
|
||||
Reality: downloadRealityCfg,
|
||||
NextProtos: []string{"h3"},
|
||||
}
|
||||
if downloadServerName != "" {
|
||||
tlsOpts.Host = downloadServerName
|
||||
}
|
||||
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")
|
||||
}
|
||||
tlsConfig, err := tlsOpts.ToStdConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = downloadEchConfig.ClientHandle(ctx, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, quicConn, err := common.DialQuic(ctx, downloadAddr, v.DialOptions(), v.dialer, tlsConfig, cfg, true)
|
||||
return quicConn, nil
|
||||
},
|
||||
downloadALPN,
|
||||
downloadHKeepAlivePeriod,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -374,19 +374,19 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
}
|
||||
|
||||
v := &Vmess{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vmess,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.Vmess,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
XUDP: option.XUDP,
|
||||
TFO: option.TFO,
|
||||
MPTCP: option.MPTCP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
client: client,
|
||||
option: &option,
|
||||
}
|
||||
|
||||
@@ -166,16 +166,16 @@ func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
||||
|
||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||
outbound := &WireGuard{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.WireGuard,
|
||||
pdName: option.ProviderName,
|
||||
udp: option.UDP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
Base: NewBase(BaseOption{
|
||||
Name: option.Name,
|
||||
Addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Type: C.WireGuard,
|
||||
ProviderName: option.ProviderName,
|
||||
UDP: option.UDP,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
Prefer: option.IPVersion,
|
||||
}),
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
singDialer := proxydialer.NewSingDialer(proxydialer.NewSlowDownDialer(outbound.dialer, slowdown.New()))
|
||||
|
||||
@@ -3,6 +3,7 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -34,3 +35,19 @@ func splitArgs(cmd string) []string {
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func ExecShell(shellStr string) (string, error) {
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.Command("cmd.exe", "/C", shellStr)
|
||||
} else {
|
||||
cmd = exec.Command("sh", "-c", shellStr)
|
||||
}
|
||||
|
||||
prepareBackgroundCommand(cmd)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
@@ -453,10 +453,18 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
"host": pluginInfo.Get("obfs-host"),
|
||||
}
|
||||
} else if strings.Contains(pluginName, "v2ray-plugin") {
|
||||
mode := pluginInfo.Get("mode")
|
||||
if mode == "" {
|
||||
mode = pluginInfo.Get("obfs")
|
||||
}
|
||||
host := pluginInfo.Get("host")
|
||||
if host == "" {
|
||||
host = pluginInfo.Get("obfs-host")
|
||||
}
|
||||
ss["plugin"] = "v2ray-plugin"
|
||||
ss["plugin-opts"] = map[string]any{
|
||||
"mode": pluginInfo.Get("mode"),
|
||||
"host": pluginInfo.Get("host"),
|
||||
"mode": mode,
|
||||
"host": host,
|
||||
"path": pluginInfo.Get("path"),
|
||||
"tls": strings.Contains(plugin, "tls"),
|
||||
}
|
||||
|
||||
@@ -129,3 +129,52 @@ func TestConvertsV2RayMieruFragment(t *testing.T) {
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "myproxy:443/TCP", proxies[0]["name"])
|
||||
}
|
||||
|
||||
func TestConvertsV2RayVlessRealityVisionTCPWithoutHeaderType(t *testing.T) {
|
||||
vlessTest := "vless://a1b2c3d4-eacc-4433-981b-7e5f9a8b@142.98.76.54:34888?encryption=none&security=reality&type=tcp&sni=github.io&fp=chrome&pbk=TifX9kL2mPqRsTuVwXyZ_JdUWw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "tcp", proxies[0]["network"])
|
||||
assert.Equal(t, "xtls-rprx-vision", proxies[0]["flow"])
|
||||
assert.Equal(t, "none", proxies[0]["encryption"])
|
||||
assert.Equal(t, "github.io", proxies[0]["servername"])
|
||||
assert.NotContains(t, proxies[0], "http-opts")
|
||||
assert.NotContains(t, proxies[0], "h2-opts")
|
||||
}
|
||||
|
||||
func TestConvertsV2RayVlessTCPHTTPHeaderType(t *testing.T) {
|
||||
vlessTest := "vless://uuid@example.com:443?security=tls&type=tcp&headerType=http&host=cdn.example.com&path=%2Fedge&method=POST#vless-http"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "http", proxies[0]["network"])
|
||||
assert.Equal(t, map[string]any{
|
||||
"method": "POST",
|
||||
"path": []string{"/edge"},
|
||||
"headers": map[string]any{
|
||||
"Host": []string{"cdn.example.com"},
|
||||
},
|
||||
}, proxies[0]["http-opts"])
|
||||
assert.NotContains(t, proxies[0], "h2-opts")
|
||||
}
|
||||
|
||||
func TestConvertsV2RayVlessHTTPTransportUsesH2Opts(t *testing.T) {
|
||||
vlessTest := "vless://uuid@example.com:443?security=tls&type=http&host=cdn.example.com&path=%2Fgrpc#vless-h2"
|
||||
|
||||
proxies, err := ConvertsV2Ray([]byte(vlessTest))
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Len(t, proxies, 1)
|
||||
assert.Equal(t, "h2", proxies[0]["network"])
|
||||
assert.Equal(t, map[string]any{
|
||||
"host": []string{"cdn.example.com"},
|
||||
"path": []string{"/grpc"},
|
||||
"headers": map[string]any{},
|
||||
}, proxies[0]["h2-opts"])
|
||||
assert.NotContains(t, proxies[0], "http-opts")
|
||||
}
|
||||
+170
-37
@@ -63,7 +63,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
network = "tcp"
|
||||
}
|
||||
fakeType := strings.ToLower(query.Get("headerType"))
|
||||
if fakeType == "http" {
|
||||
if network == "tcp" && fakeType == "http" {
|
||||
network = "http"
|
||||
} else if network == "http" {
|
||||
network = "h2"
|
||||
@@ -71,27 +71,26 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
proxy["network"] = network
|
||||
switch network {
|
||||
case "tcp":
|
||||
if fakeType != "none" {
|
||||
headers := make(map[string]any)
|
||||
httpOpts := make(map[string]any)
|
||||
httpOpts["path"] = []string{"/"}
|
||||
case "http":
|
||||
headers := make(map[string]any)
|
||||
httpOpts := make(map[string]any)
|
||||
httpOpts["path"] = []string{"/"}
|
||||
|
||||
if host := query.Get("host"); host != "" {
|
||||
headers["Host"] = []string{host}
|
||||
}
|
||||
|
||||
if method := query.Get("method"); method != "" {
|
||||
httpOpts["method"] = method
|
||||
}
|
||||
|
||||
if path := query.Get("path"); path != "" {
|
||||
httpOpts["path"] = []string{path}
|
||||
}
|
||||
httpOpts["headers"] = headers
|
||||
proxy["http-opts"] = httpOpts
|
||||
if host := query.Get("host"); host != "" {
|
||||
headers["Host"] = []string{host}
|
||||
}
|
||||
|
||||
case "http":
|
||||
if method := query.Get("method"); method != "" {
|
||||
httpOpts["method"] = method
|
||||
}
|
||||
|
||||
if path := query.Get("path"); path != "" {
|
||||
httpOpts["path"] = []string{path}
|
||||
}
|
||||
httpOpts["headers"] = headers
|
||||
proxy["http-opts"] = httpOpts
|
||||
|
||||
case "h2":
|
||||
headers := make(map[string]any)
|
||||
h2Opts := make(map[string]any)
|
||||
h2Opts["path"] = []string{"/"}
|
||||
@@ -187,6 +186,9 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
set("cMaxReuseTimes", "c-max-reuse-times")
|
||||
set("hMaxRequestTimes", "h-max-request-times")
|
||||
set("hMaxReusableSecs", "h-max-reusable-secs")
|
||||
if v, ok := xmux["hKeepAlivePeriod"].(float64); ok {
|
||||
reuse["h-keep-alive-period"] = int(v)
|
||||
}
|
||||
return reuse
|
||||
}
|
||||
|
||||
@@ -197,14 +199,74 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
if v, ok := extra["xPaddingBytes"].(string); ok && v != "" {
|
||||
opts["x-padding-bytes"] = v
|
||||
}
|
||||
|
||||
|
||||
if v, ok := extra["xPaddingObfsMode"].(bool); ok {
|
||||
opts["x-padding-obfs-mode"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["xPaddingKey"].(string); ok && v != "" {
|
||||
opts["x-padding-key"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["xPaddingHeader"].(string); ok && v != "" {
|
||||
opts["x-padding-header"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["xPaddingPlacement"].(string); ok && v != "" {
|
||||
opts["x-padding-placement"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["xPaddingMethod"].(string); ok && v != "" {
|
||||
opts["x-padding-method"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["uplinkHttpMethod"].(string); ok && v != "" {
|
||||
opts["uplink-http-method"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionPlacement"].(string); ok && v != "" {
|
||||
opts["session-placement"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["sessionKey"].(string); ok && v != "" {
|
||||
opts["session-key"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["seqPlacement"].(string); ok && v != "" {
|
||||
opts["seq-placement"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["seqKey"].(string); ok && v != "" {
|
||||
opts["seq-key"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["uplinkDataPlacement"].(string); ok && v != "" {
|
||||
opts["uplink-data-placement"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["uplinkDataKey"].(string); ok && v != "" {
|
||||
opts["uplink-data-key"] = v
|
||||
}
|
||||
|
||||
if v, ok := extra["uplinkChunkSize"].(float64); ok {
|
||||
opts["uplink-chunk-size"] = int(v)
|
||||
}
|
||||
|
||||
if v, ok := extra["scMaxEachPostBytes"].(float64); ok {
|
||||
opts["sc-max-each-post-bytes"] = int(v)
|
||||
}
|
||||
|
||||
if v, ok := extra["scMinPostsIntervalMs"].(float64); ok {
|
||||
opts["sc-min-posts-interval-ms"] = int(v)
|
||||
}
|
||||
|
||||
// xmux in root extra → reuse-settings
|
||||
if xmuxAny, ok := extra["xmux"].(map[string]any); ok && len(xmuxAny) > 0 {
|
||||
if reuse := xmuxToReuse(xmuxAny); len(reuse) > 0 {
|
||||
opts["reuse-settings"] = reuse
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if dsAny, ok := extra["downloadSettings"].(map[string]any); ok {
|
||||
ds := make(map[string]any)
|
||||
|
||||
@@ -216,26 +278,49 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
ds["port"] = int(port)
|
||||
}
|
||||
|
||||
if sec, ok := dsAny["security"].(string); ok && strings.ToLower(sec) == "tls" {
|
||||
ds["tls"] = true
|
||||
sec := ""
|
||||
if s, ok := dsAny["security"].(string); ok {
|
||||
sec = strings.ToLower(s)
|
||||
}
|
||||
|
||||
if tlsAny, ok := dsAny["tlsSettings"].(map[string]any); ok {
|
||||
if sn, ok := tlsAny["serverName"].(string); ok && sn != "" {
|
||||
ds["servername"] = sn
|
||||
}
|
||||
if fp, ok := tlsAny["fingerprint"].(string); ok && fp != "" {
|
||||
ds["client-fingerprint"] = fp
|
||||
}
|
||||
if alpnAny, ok := tlsAny["alpn"].([]any); ok && len(alpnAny) > 0 {
|
||||
alpnList := make([]string, 0, len(alpnAny))
|
||||
for _, a := range alpnAny {
|
||||
if s, ok := a.(string); ok {
|
||||
alpnList = append(alpnList, s)
|
||||
if sec == "tls" || sec == "reality" {
|
||||
ds["tls"] = true
|
||||
|
||||
if tlsAny, ok := dsAny["tlsSettings"].(map[string]any); ok {
|
||||
if sn, ok := tlsAny["serverName"].(string); ok && sn != "" {
|
||||
ds["servername"] = sn
|
||||
}
|
||||
if fp, ok := tlsAny["fingerprint"].(string); ok && fp != "" {
|
||||
ds["client-fingerprint"] = fp
|
||||
}
|
||||
if alpnAny, ok := tlsAny["alpn"].([]any); ok && len(alpnAny) > 0 {
|
||||
alpnList := make([]string, 0, len(alpnAny))
|
||||
for _, a := range alpnAny {
|
||||
if s, ok := a.(string); ok {
|
||||
alpnList = append(alpnList, s)
|
||||
}
|
||||
}
|
||||
if len(alpnList) > 0 {
|
||||
ds["alpn"] = alpnList
|
||||
}
|
||||
}
|
||||
if len(alpnList) > 0 {
|
||||
ds["alpn"] = alpnList
|
||||
if v, ok := tlsAny["allowInsecure"].(bool); ok && v {
|
||||
ds["skip-cert-verify"] = true
|
||||
}
|
||||
}
|
||||
|
||||
if sec == "reality" {
|
||||
if realityAny, ok := dsAny["realitySettings"].(map[string]any); ok {
|
||||
realityOpts := make(map[string]any)
|
||||
if pk, ok := realityAny["publicKey"].(string); ok && pk != "" {
|
||||
realityOpts["public-key"] = pk
|
||||
}
|
||||
if sid, ok := realityAny["shortId"].(string); ok && sid != "" {
|
||||
realityOpts["short-id"] = sid
|
||||
}
|
||||
if len(realityOpts) > 0 {
|
||||
ds["reality-opts"] = realityOpts
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,12 +332,60 @@ func parseXHTTPExtra(extra map[string]any, opts map[string]any) {
|
||||
if host, ok := xhttpAny["host"].(string); ok && host != "" {
|
||||
ds["host"] = host
|
||||
}
|
||||
if headers, ok := xhttpAny["headers"].(map[string]any); ok && len(headers) > 0 {
|
||||
ds["headers"] = headers
|
||||
}
|
||||
if v, ok := xhttpAny["noGRPCHeader"].(bool); ok && v {
|
||||
ds["no-grpc-header"] = true
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingBytes"].(string); ok && v != "" {
|
||||
ds["x-padding-bytes"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingObfsMode"].(bool); ok {
|
||||
ds["x-padding-obfs-mode"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingKey"].(string); ok && v != "" {
|
||||
ds["x-padding-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingHeader"].(string); ok && v != "" {
|
||||
ds["x-padding-header"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingPlacement"].(string); ok && v != "" {
|
||||
ds["x-padding-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["xPaddingMethod"].(string); ok && v != "" {
|
||||
ds["x-padding-method"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkHttpMethod"].(string); ok && v != "" {
|
||||
ds["uplink-http-method"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["sessionPlacement"].(string); ok && v != "" {
|
||||
ds["session-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["sessionKey"].(string); ok && v != "" {
|
||||
ds["session-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["seqPlacement"].(string); ok && v != "" {
|
||||
ds["seq-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["seqKey"].(string); ok && v != "" {
|
||||
ds["seq-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkDataPlacement"].(string); ok && v != "" {
|
||||
ds["uplink-data-placement"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkDataKey"].(string); ok && v != "" {
|
||||
ds["uplink-data-key"] = v
|
||||
}
|
||||
if v, ok := xhttpAny["uplinkChunkSize"].(float64); ok {
|
||||
ds["uplink-chunk-size"] = int(v)
|
||||
}
|
||||
if v, ok := xhttpAny["scMaxEachPostBytes"].(float64); ok {
|
||||
ds["sc-max-each-post-bytes"] = int(v)
|
||||
}
|
||||
if v, ok := xhttpAny["scMinPostsIntervalMs"].(float64); ok {
|
||||
ds["sc-min-posts-interval-ms"] = int(v)
|
||||
}
|
||||
|
||||
// xmux inside downloadSettings.xhttpSettings.extra → download-settings.reuse-settings
|
||||
if dsExtraAny, ok := xhttpAny["extra"].(map[string]any); ok {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
@@ -42,3 +46,58 @@ func (r Range[T]) Start() T {
|
||||
func (r Range[T]) End() T {
|
||||
return r.end
|
||||
}
|
||||
|
||||
func (r Range[T]) String() string {
|
||||
if r.start == r.end {
|
||||
return fmt.Sprintf("%v", r.start)
|
||||
}
|
||||
return fmt.Sprintf("%v-%v", r.start, r.end)
|
||||
}
|
||||
|
||||
func NewUnsignedRange[T constraints.Unsigned](expected string) (Range[T], error) {
|
||||
return newIntRange(expected, parseUnsigned[T])
|
||||
}
|
||||
|
||||
func NewSignedRange[T constraints.Signed](expected string) (Range[T], error) {
|
||||
return newIntRange(expected, parseSigned[T])
|
||||
}
|
||||
|
||||
func newIntRange[T constraints.Integer](s string, parseFn func(string) (T, error)) (Range[T], error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) == 0 {
|
||||
return NewRange[T](0, 0), nil
|
||||
}
|
||||
status := strings.Split(s, "-")
|
||||
start, err := parseFn(strings.Trim(status[0], "[ ]"))
|
||||
if err != nil {
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
switch len(status) {
|
||||
case 1: // Port range
|
||||
return NewRange(start, start), nil
|
||||
case 2: // Single port
|
||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
||||
if err != nil {
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
return NewRange(start, end), nil
|
||||
default:
|
||||
return Range[T]{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func parseUnsigned[T constraints.Unsigned](s string) (T, error) {
|
||||
if val, err := strconv.ParseUint(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func parseSigned[T constraints.Signed](s string) (T, error) {
|
||||
if val, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
+4
-48
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
@@ -38,41 +37,16 @@ func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(str
|
||||
continue
|
||||
}
|
||||
|
||||
status := strings.Split(s, "-")
|
||||
statusLen := len(status)
|
||||
if statusLen > 2 {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
start, err := parseFn(strings.Trim(status[0], "[ ]"))
|
||||
r, err := newIntRange[T](s, parseFn)
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
switch statusLen {
|
||||
case 1: // Port range
|
||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
||||
case 2: // Single port
|
||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
ranges = append(ranges, NewRange(T(start), T(end)))
|
||||
return nil, err
|
||||
}
|
||||
ranges = append(ranges, r)
|
||||
}
|
||||
|
||||
return ranges, nil
|
||||
}
|
||||
|
||||
func parseUnsigned[T constraints.Unsigned](s string) (T, error) {
|
||||
if val, err := strconv.ParseUint(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func NewUnsignedRanges[T constraints.Unsigned](expected string) (IntRanges[T], error) {
|
||||
return newIntRanges(expected, parseUnsigned[T])
|
||||
}
|
||||
@@ -81,14 +55,6 @@ func NewUnsignedRangesFromList[T constraints.Unsigned](list []string) (IntRanges
|
||||
return newIntRangesFromList(list, parseUnsigned[T])
|
||||
}
|
||||
|
||||
func parseSigned[T constraints.Signed](s string) (T, error) {
|
||||
if val, err := strconv.ParseInt(s, 10, 64); err == nil {
|
||||
return T(val), nil
|
||||
} else {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
func NewSignedRanges[T constraints.Signed](expected string) (IntRanges[T], error) {
|
||||
return newIntRanges(expected, parseSigned[T])
|
||||
}
|
||||
@@ -118,17 +84,7 @@ func (ranges IntRanges[T]) String() string {
|
||||
|
||||
terms := make([]string, len(ranges))
|
||||
for i, r := range ranges {
|
||||
start := r.Start()
|
||||
end := r.End()
|
||||
|
||||
var term string
|
||||
if start == end {
|
||||
term = strconv.Itoa(int(start))
|
||||
} else {
|
||||
term = strconv.Itoa(int(start)) + "-" + strconv.Itoa(int(end))
|
||||
}
|
||||
|
||||
terms[i] = term
|
||||
terms[i] = r.String()
|
||||
}
|
||||
|
||||
return strings.Join(terms, "/")
|
||||
|
||||
@@ -209,6 +209,12 @@ func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string,
|
||||
if len(ipv4s) == 0 && len(ipv6s) == 0 {
|
||||
return nil, ErrorNoIpAddress
|
||||
}
|
||||
if len(ipv4s) == 0 && len(ipv6s) != 0 {
|
||||
return dialFn(ctx, network, ipv6s, port, opt)
|
||||
}
|
||||
if len(ipv4s) != 0 && len(ipv6s) == 0 {
|
||||
return dialFn(ctx, network, ipv4s, port, opt)
|
||||
}
|
||||
|
||||
preferIPVersion := opt.prefer
|
||||
fallbackTicker := time.NewTicker(dualStackFallbackTimeout)
|
||||
@@ -289,6 +295,9 @@ func parallelDialContext(ctx context.Context, network string, ips []netip.Addr,
|
||||
if len(ips) == 0 {
|
||||
return nil, ErrorNoIpAddress
|
||||
}
|
||||
if len(ips) == 1 {
|
||||
return dialContext(ctx, network, ips[0], port, opt)
|
||||
}
|
||||
results := make(chan dialResult)
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
|
||||
@@ -24,6 +24,12 @@ type NetDialer interface {
|
||||
DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
||||
}
|
||||
|
||||
type NetDialerFunc func(ctx context.Context, network, address string) (net.Conn, error)
|
||||
|
||||
func (f NetDialerFunc) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return f(ctx, network, address)
|
||||
}
|
||||
|
||||
type option struct {
|
||||
interfaceName string
|
||||
fallbackBind bool
|
||||
@@ -115,6 +121,14 @@ func WithOption(o option) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithOptions(options ...Option) Option {
|
||||
return func(opt *option) {
|
||||
for _, o := range options {
|
||||
o(opt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func IsZeroOptions(opts []Option) bool {
|
||||
return applyOptions(opts...) == option{}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ var (
|
||||
bucketFakeip6 = []byte("fakeip6")
|
||||
bucketETag = []byte("etag")
|
||||
bucketSubscriptionInfo = []byte("subscriptioninfo")
|
||||
bucketStorage = []byte("storage")
|
||||
)
|
||||
|
||||
// CacheFile store and update the cache file
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package cachefile
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/bbolt"
|
||||
"github.com/vmihailenco/msgpack/v5"
|
||||
)
|
||||
|
||||
const storageSizeLimit = 1024 * 1024
|
||||
const storageKeySizeLimit = 64
|
||||
const maxStorageEntries = storageSizeLimit / storageKeySizeLimit
|
||||
|
||||
type StorageData struct {
|
||||
Data []byte
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
func decodeStorageData(v []byte) (StorageData, error) {
|
||||
var storage StorageData
|
||||
if err := msgpack.Unmarshal(v, &storage); err != nil {
|
||||
return StorageData{}, err
|
||||
}
|
||||
return storage, nil
|
||||
}
|
||||
|
||||
func (c *CacheFile) GetStorage(key string) []byte {
|
||||
if c.DB == nil {
|
||||
return nil
|
||||
}
|
||||
var data []byte
|
||||
decodeFailed := false
|
||||
err := c.DB.View(func(t *bbolt.Tx) error {
|
||||
if bucket := t.Bucket(bucketStorage); bucket != nil {
|
||||
if v := bucket.Get([]byte(key)); v != nil {
|
||||
storage, err := decodeStorageData(v)
|
||||
if err != nil {
|
||||
decodeFailed = true
|
||||
return err
|
||||
}
|
||||
data = storage.Data
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] read cache for key %s failed: %s", key, err.Error())
|
||||
if decodeFailed {
|
||||
c.DeleteStorage(key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func (c *CacheFile) SetStorage(key string, data []byte) {
|
||||
if c.DB == nil {
|
||||
return
|
||||
}
|
||||
if len(key) > storageKeySizeLimit {
|
||||
log.Warnln("[CacheFile] skip storage for key %s: key exceeds %d bytes", key, storageKeySizeLimit)
|
||||
return
|
||||
}
|
||||
if len(data) > storageSizeLimit {
|
||||
log.Warnln("[CacheFile] skip storage for key %s: payload exceeds %d bytes", key, storageSizeLimit)
|
||||
return
|
||||
}
|
||||
keyBytes := []byte(key)
|
||||
payload, err := msgpack.Marshal(StorageData{
|
||||
Data: data,
|
||||
Time: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.DB.Batch(func(t *bbolt.Tx) error {
|
||||
bucket, err := t.CreateBucketIfNotExists(bucketStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type storageEntry struct {
|
||||
Key string
|
||||
Data StorageData
|
||||
}
|
||||
|
||||
entries := make(map[string]StorageData)
|
||||
usedSize := 0
|
||||
entryCount := 0
|
||||
corruptedKeys := make([][]byte, 0)
|
||||
c := bucket.Cursor()
|
||||
for k, v := c.First(); k != nil; k, v = c.Next() {
|
||||
storage, err := decodeStorageData(v)
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] drop corrupted storage entry %s: %s", string(k), err.Error())
|
||||
corruptedKeys = append(corruptedKeys, append([]byte(nil), k...))
|
||||
continue
|
||||
}
|
||||
entryKey := string(k)
|
||||
entries[entryKey] = storage
|
||||
if entryKey != key {
|
||||
usedSize += len(storage.Data)
|
||||
entryCount++
|
||||
}
|
||||
}
|
||||
for _, k := range corruptedKeys {
|
||||
if err := bucket.Delete(k); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
evictionQueue := make([]storageEntry, 0, len(entries))
|
||||
for entryKey, storage := range entries {
|
||||
if entryKey == key {
|
||||
continue
|
||||
}
|
||||
evictionQueue = append(evictionQueue, storageEntry{
|
||||
Key: entryKey,
|
||||
Data: storage,
|
||||
})
|
||||
}
|
||||
sort.Slice(evictionQueue, func(i, j int) bool {
|
||||
left := evictionQueue[i]
|
||||
right := evictionQueue[j]
|
||||
if left.Data.Time.Equal(right.Data.Time) {
|
||||
return left.Key < right.Key
|
||||
}
|
||||
return left.Data.Time.Before(right.Data.Time)
|
||||
})
|
||||
|
||||
for _, entry := range evictionQueue {
|
||||
if usedSize+len(data) <= storageSizeLimit && entryCount < maxStorageEntries {
|
||||
break
|
||||
}
|
||||
if err := bucket.Delete([]byte(entry.Key)); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infoln("[CacheFile] evict storage entry %s to make room for %s", entry.Key, key)
|
||||
usedSize -= len(entry.Data.Data)
|
||||
entryCount--
|
||||
}
|
||||
return bucket.Put(keyBytes, payload)
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] write cache to %s failed: %s", c.DB.Path(), err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CacheFile) DeleteStorage(key string) {
|
||||
if c.DB == nil {
|
||||
return
|
||||
}
|
||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
||||
bucket := t.Bucket(bucketStorage)
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
return bucket.Delete([]byte(key))
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnln("[CacheFile] delete cache from %s failed: %s", c.DB.Path(), err.Error())
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -554,11 +554,11 @@ func (doh *dnsOverHTTPS) dialQuic(ctx context.Context, addr string, tlsCfg *tls.
|
||||
IP: net.ParseIP(ip),
|
||||
Port: portInt,
|
||||
}
|
||||
conn, err := doh.dialer.ListenPacket(ctx, "udp", addr)
|
||||
packetConn, err := doh.dialer.ListenPacket(ctx, "udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := quic.Transport{Conn: conn}
|
||||
transport := quic.Transport{Conn: packetConn}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
tlsCfg = tlsCfg.Clone()
|
||||
@@ -568,7 +568,12 @@ func (doh *dnsOverHTTPS) dialQuic(ctx context.Context, addr string, tlsCfg *tls.
|
||||
// It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
|
||||
tlsCfg.ServerName = doh.url.Host
|
||||
}
|
||||
return transport.DialEarly(ctx, &udpAddr, tlsCfg, cfg)
|
||||
quicConn, err := transport.DialEarly(ctx, &udpAddr, tlsCfg, cfg)
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// probeH3 runs a test to check whether QUIC is faster than TLS for this
|
||||
|
||||
+6
-5
@@ -279,7 +279,7 @@ func (doq *dnsOverQUIC) openStream(ctx context.Context, conn *quic.Conn) (*quic.
|
||||
}
|
||||
|
||||
// openConnection opens a new QUIC connection.
|
||||
func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, err error) {
|
||||
func (doq *dnsOverQUIC) openConnection(ctx context.Context) (quicConn *quic.Conn, err error) {
|
||||
// we're using bootstrapped address instead of what's passed to the function
|
||||
// it does not create an actual connection, but it helps us determine
|
||||
// what IP is actually reachable (when there're v4/v6 addresses).
|
||||
@@ -298,7 +298,7 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, er
|
||||
|
||||
p, err := strconv.Atoi(port)
|
||||
udpAddr := net.UDPAddr{IP: net.ParseIP(ip), Port: p}
|
||||
udp, err := doq.dialer.ListenPacket(ctx, "udp", addr)
|
||||
packetConn, err := doq.dialer.ListenPacket(ctx, "udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -322,15 +322,16 @@ func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn *quic.Conn, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
transport := quic.Transport{Conn: udp}
|
||||
transport := quic.Transport{Conn: packetConn}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
conn, err = transport.Dial(ctx, &udpAddr, tlsConfig, doq.getQUICConfig())
|
||||
quicConn, err = transport.Dial(ctx, &udpAddr, tlsConfig, doq.getQUICConfig())
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, fmt.Errorf("opening quic connection to %s: %w", doq.addr, err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
return quicConn, nil
|
||||
}
|
||||
|
||||
// closeConnWithError closes the active connection with error to make sure that
|
||||
|
||||
+79
-11
@@ -807,8 +807,7 @@ proxies: # socks5
|
||||
udp: true
|
||||
tls: true
|
||||
network: xhttp
|
||||
alpn:
|
||||
- h2
|
||||
alpn: [h2] # 默认仅支持h2,如果开启h3模式需要设置alpn: [h3],如果开启http1.1模式需要设置alpn: [http/1.1]
|
||||
# ech-opts: ...
|
||||
# reality-opts: ...
|
||||
# skip-cert-verify: false
|
||||
@@ -826,13 +825,28 @@ proxies: # socks5
|
||||
# X-Forwarded-For: ""
|
||||
# no-grpc-header: false
|
||||
# x-padding-bytes: "100-1000"
|
||||
# x-padding-obfs-mode: false
|
||||
# x-padding-key: x_padding
|
||||
# x-padding-header: Referer
|
||||
# x-padding-placement: queryInHeader # Available: queryInHeader, cookie, header, query
|
||||
# x-padding-method: repeat-x # Available: repeat-x, tokenish
|
||||
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
|
||||
# session-placement: path # Available: path, query, cookie, header
|
||||
# session-key: ""
|
||||
# seq-placement: path # Available: path, query, cookie, header
|
||||
# seq-key: ""
|
||||
# uplink-data-placement: body # Available: body, cookie, header
|
||||
# uplink-data-key: ""
|
||||
# uplink-chunk-size: 0 # only applicable when uplink-data-placement is not body
|
||||
# sc-max-each-post-bytes: 1000000
|
||||
# sc-min-posts-interval-ms: 30
|
||||
# reuse-settings: # aka XMUX
|
||||
# max-connections: "16-32"
|
||||
# max-concurrency: "0"
|
||||
# max-concurrency: "16-32"
|
||||
# max-connections: "0"
|
||||
# c-max-reuse-times: "0"
|
||||
# h-max-request-times: "600-900"
|
||||
# h-max-reusable-secs: "1800-3000"
|
||||
# h-keep-alive-period: 0
|
||||
# download-settings:
|
||||
# ## xhttp part
|
||||
# path: "/"
|
||||
@@ -841,19 +855,33 @@ proxies: # socks5
|
||||
# X-Forwarded-For: ""
|
||||
# no-grpc-header: false
|
||||
# x-padding-bytes: "100-1000"
|
||||
# x-padding-obfs-mode: false
|
||||
# x-padding-key: x_padding
|
||||
# x-padding-header: Referer
|
||||
# x-padding-placement: queryInHeader # Available: queryInHeader, cookie, header, query
|
||||
# x-padding-method: repeat-x # Available: repeat-x, tokenish
|
||||
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
|
||||
# session-placement: path # Available: path, query, cookie, header
|
||||
# session-key: ""
|
||||
# seq-placement: path # Available: path, query, cookie, header
|
||||
# seq-key: ""
|
||||
# uplink-data-placement: body # Available: body, cookie, header
|
||||
# uplink-data-key: ""
|
||||
# uplink-chunk-size: 0 # only applicable when uplink-data-placement is not body
|
||||
# sc-max-each-post-bytes: 1000000
|
||||
# sc-min-posts-interval-ms: 30
|
||||
# reuse-settings: # aka XMUX
|
||||
# max-connections: "16-32"
|
||||
# max-concurrency: "0"
|
||||
# max-concurrency: "16-32"
|
||||
# max-connections: "0"
|
||||
# c-max-reuse-times: "0"
|
||||
# h-max-request-times: "600-900"
|
||||
# h-max-reusable-secs: "1800-3000"
|
||||
# h-keep-alive-period: 0
|
||||
# ## proxy part
|
||||
# server: server
|
||||
# port: 443
|
||||
# tls: true
|
||||
# alpn:
|
||||
# - h2
|
||||
# alpn: ...
|
||||
# ech-opts: ...
|
||||
# reality-opts: ...
|
||||
# skip-cert-verify: false
|
||||
@@ -982,10 +1010,11 @@ proxies: # socks5
|
||||
server: server.com
|
||||
port: 443
|
||||
# ports: 1000,2000-3000,5000 # port 不可省略
|
||||
# hop-interval: 15
|
||||
# hop-interval: 15 # 支持填写"15-30"会每次随机选取其中一个值作为切换间隔,仅支持写一个范围(即不允许出现逗号)
|
||||
# up 和 down 均不写或为 0 则使用 BBR 流控
|
||||
# up: "30 Mbps" # 若不写单位,默认为 Mbps
|
||||
# down: "200 Mbps" # 若不写单位,默认为 Mbps
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
password: yourpassword
|
||||
# obfs: salamander # 默认为空,如果填写则开启 obfs,目前仅支持 salamander
|
||||
# obfs-password: yourpassword
|
||||
@@ -1080,6 +1109,23 @@ proxies: # socks5
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
# congestion-controller: bbr # 默认不开启
|
||||
|
||||
# masque-h2
|
||||
- name: "masque-h2"
|
||||
type: masque
|
||||
server: 162.159.198.2
|
||||
port: 443
|
||||
private-key: MHcCAQEEILI1eOtnbEIh89Fj4yNDuFR6UjayCKI3NdLl3DhetimWoAoGCCqGSM49AwEHoUQDQgAEgyXrE8v+hHsHy3ewSb3WcRjYgCrM9T9hiE0Uv6k2DZ1+4kefrDT9v1Q/8wdRigTf6t6gGNUV8W+IUMdrfUt+9g==
|
||||
public-key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIaU7MToJm9NKp8YfGxR6r+/h4mcG7SxI8tsW8OR1A5tv/zCzVbCRRh2t87/kxnP6lAy0lkr7qYwu+ox+k3dr6w==
|
||||
ip: 172.16.0.2
|
||||
ipv6: 2606:4700:110:84c0:163a:4914:a0ad:3342
|
||||
mtu: 1280
|
||||
udp: true
|
||||
network: h2
|
||||
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
|
||||
# dialer-proxy: "ss1"
|
||||
# remote-dns-resolve: true # 强制 dns 远程解析,默认值为 false
|
||||
# dns: [ 1.1.1.1, 8.8.8.8 ] # 仅在 remote-dns-resolve 为 true 时生效
|
||||
|
||||
# tuic
|
||||
- name: tuic
|
||||
server: www.example.com
|
||||
@@ -1099,6 +1145,7 @@ proxies: # socks5
|
||||
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
||||
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
||||
# cwnd: 10 # default: 32
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-udp-relay-packet-size: 1500
|
||||
# fast-open: true
|
||||
# skip-cert-verify: true
|
||||
@@ -1217,9 +1264,10 @@ proxies: # socks5
|
||||
### quic options
|
||||
# quic: true # 默认为false
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
### reuse options
|
||||
# max-connections: 1 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 0 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-connections: 8 # Maximum connections. Conflict with max-streams.
|
||||
# min-streams: 5 # Minimum multiplexed streams in a connection before opening a new connection. Conflict with max-streams.
|
||||
# max-streams: 0 # Maximum multiplexed streams in a connection before opening a new connection. Conflict with max-connections and min-streams.
|
||||
|
||||
# dns 出站会将请求劫持到内部 dns 模块,所有请求均在内部处理
|
||||
@@ -1632,6 +1680,7 @@ listeners:
|
||||
# dC5jb20AAA==
|
||||
# -----END ECH KEYS-----
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# authentication-timeout: 1000
|
||||
# alpn:
|
||||
@@ -1664,6 +1713,21 @@ listeners:
|
||||
# host: ""
|
||||
# mode: auto # Available: "stream-one", "stream-up" or "packet-up"
|
||||
# no-sse-header: false
|
||||
# x-padding-bytes: "100-1000"
|
||||
# x-padding-obfs-mode: false
|
||||
# x-padding-key: x_padding
|
||||
# x-padding-header: Referer
|
||||
# x-padding-placement: queryInHeader # Available: queryInHeader, cookie, header, query
|
||||
# x-padding-method: repeat-x # Available: repeat-x, tokenish
|
||||
# uplink-http-method: POST # Available: POST, PUT, PATCH, DELETE
|
||||
# session-placement: path # Available: path, query, cookie, header
|
||||
# session-key: ""
|
||||
# seq-placement: path # Available: path, query, cookie, header
|
||||
# seq-key: ""
|
||||
# uplink-data-placement: body # Available: body, cookie, header
|
||||
# uplink-data-key: ""
|
||||
# uplink-chunk-size: 0 # only applicable when uplink-data-placement is not body
|
||||
# sc-max-buffered-posts: 30
|
||||
# sc-stream-up-server-secs: "20-80"
|
||||
# sc-max-each-post-bytes: 1000000
|
||||
# -------------------------
|
||||
@@ -1744,6 +1808,8 @@ listeners:
|
||||
username2: password2
|
||||
# 一个 base64 字符串用于微调网络行为
|
||||
# traffic-pattern: ""
|
||||
# 如果开启,且客户端不发送用户提示,代理服务器将拒绝连接
|
||||
# user-hint-is-mandatory: false
|
||||
|
||||
- name: sudoku-in-1
|
||||
type: sudoku
|
||||
@@ -1864,6 +1930,7 @@ listeners:
|
||||
private-key: ./server.key # 证书对应的私钥 PEM 格式,或者私钥路径
|
||||
network: ["tcp", "udp"] # http2+http3
|
||||
congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# 下面两项为mTLS配置项,如果client-auth-type设置为 "verify-if-given" 或 "require-and-verify" 则client-auth-cert必须不为空
|
||||
# client-auth-type: "" # 可选值:""、"request"、"require-any"、"verify-if-given"、"require-and-verify"
|
||||
# client-auth-cert: string # 证书 PEM 格式,或者 证书的路径
|
||||
@@ -1939,6 +2006,7 @@ listeners:
|
||||
# certificate: ./server.crt
|
||||
# private-key: ./server.key
|
||||
# congestion-controller: bbr
|
||||
# bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard"
|
||||
# max-idle-time: 15000
|
||||
# authentication-timeout: 1000
|
||||
# alpn:
|
||||
|
||||
@@ -5,8 +5,8 @@ go 1.20
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0
|
||||
github.com/coreos/go-iptables v0.8.0
|
||||
github.com/dlclark/regexp2 v1.11.5
|
||||
github.com/enfein/mieru/v3 v3.30.0
|
||||
github.com/dlclark/regexp2 v1.12.0
|
||||
github.com/enfein/mieru/v3 v3.31.0
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
@@ -16,21 +16,21 @@ require (
|
||||
github.com/metacubex/blake3 v0.1.0
|
||||
github.com/metacubex/chacha v0.1.5
|
||||
github.com/metacubex/chi v0.1.0
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727
|
||||
github.com/metacubex/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.1
|
||||
github.com/metacubex/http v0.1.2
|
||||
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.20260213014310-4df8f0de5b56
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306
|
||||
github.com/metacubex/randv2 v0.2.0
|
||||
github.com/metacubex/restls-client-go v0.1.7
|
||||
github.com/metacubex/sing v0.5.7
|
||||
github.com/metacubex/sing-mux v0.3.5
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e
|
||||
github.com/metacubex/sing-mux v0.3.9
|
||||
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a
|
||||
github.com/metacubex/sing-shadowsocks v0.2.12
|
||||
github.com/metacubex/sing-shadowsocks2 v0.2.7
|
||||
github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2
|
||||
|
||||
@@ -16,12 +16,12 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
||||
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
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.30.0 h1:g7v0TuK7y0ZMn6TOdjOs8WEUQk8bvs6WYPBJ16SKdBU=
|
||||
github.com/enfein/mieru/v3 v3.30.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/enfein/mieru/v3 v3.31.0 h1:Fl2ocRCRXJzMygzdRjBHgqI996ZuIDHUmyQyovSf9sA=
|
||||
github.com/enfein/mieru/v3 v3.31.0/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM=
|
||||
github.com/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=
|
||||
@@ -87,8 +87,8 @@ github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2
|
||||
github.com/metacubex/chacha v0.1.5/go.mod h1:Djn9bPZxLTXbJFSeyo0/qzEzQI+gUSSzttuzZM75GH8=
|
||||
github.com/metacubex/chi v0.1.0 h1:rjNDyDj50nRpicG43CNkIw4ssiCbmDL8d7wJXKlUCsg=
|
||||
github.com/metacubex/chi v0.1.0/go.mod h1:zM5u5oMQt8b2DjvDHvzadKrP6B2ztmasL1YHRMbVV+g=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727 h1:qbZQ0sO0bDBKPvTd/qNQK6513300WJ5GRsHnw3PO4Ho=
|
||||
github.com/metacubex/connect-ip-go v0.0.0-20260128031117-1cad62060727/go.mod h1:xYC8Ik7/rN6no+vTRuWMEziGwm3brA0wNM/zZP9qhOQ=
|
||||
github.com/metacubex/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=
|
||||
github.com/metacubex/cpu v0.1.1/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU=
|
||||
github.com/metacubex/edwards25519 v1.2.0 h1:pIQZLBsjQgg3Nl/c86YYFEUAbL5qQRnPq4LrgIw0KK4=
|
||||
@@ -103,8 +103,8 @@ github.com/metacubex/hkdf v0.1.0 h1:fPA6VzXK8cU1foc/TOmGCDmSa7pZbxlnqhl3RNsthaA=
|
||||
github.com/metacubex/hkdf v0.1.0/go.mod h1:3seEfds3smgTAXqUGn+tgEJH3uXdsUjOiduG/2EtvZ4=
|
||||
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.1 h1:zVea0zOoaZvxe51EvJMRWGNQv6MvWqJhkZSuoAjOjVw=
|
||||
github.com/metacubex/http v0.1.1/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
|
||||
github.com/metacubex/http v0.1.2 h1:XxW+pMaGAvVveRqREbyWJJDDl9dRZQGJoyKBiPPPKs8=
|
||||
github.com/metacubex/http v0.1.2/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg=
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI=
|
||||
github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604/go.mod h1:lpmN3m269b3V5jFCWtffqBLS4U3QQoIid9ugtO+OhVc=
|
||||
github.com/metacubex/mhurl v0.1.0 h1:ZdW4Zxe3j3uJ89gNytOazHu6kbHn5owutN/VfXOI8GE=
|
||||
@@ -117,18 +117,18 @@ github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686 h1:PIXmYT2an
|
||||
github.com/metacubex/protobuf-go v0.0.0-20260306035419-7ceee0674686/go.mod h1:eQV7juxFZIdRgjMxtVqP+6BssKoTZQ1RM0fc58BsCZY=
|
||||
github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw=
|
||||
github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260213014310-4df8f0de5b56 h1:7yfF31COW2hiCovb5+3uSxRl3UKWOXjpS0j4N5U0qZ8=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260213014310-4df8f0de5b56/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306 h1:HlGLmLsWJMLSu0CMI9z/BmEnithB4oXM5Rom6/0Qxtg=
|
||||
github.com/metacubex/quic-go v0.59.1-0.20260413153657-53bb22f2c306/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk=
|
||||
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
|
||||
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
|
||||
github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k=
|
||||
github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g=
|
||||
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
|
||||
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
|
||||
github.com/metacubex/sing-mux v0.3.5 h1:UqVN+o62SR8kJaC9/3VfOc5UiVqgVY/ef9WwfGYYkk0=
|
||||
github.com/metacubex/sing-mux v0.3.5/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e h1:MLxp42z9Jd6LtY2suyawnl24oNzIsFxWc15bNeDIGxA=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e/go.mod h1:+lgKTd52xAarGtqugALISShyw4KxnoEpYe2u0zJh26w=
|
||||
github.com/metacubex/sing-mux v0.3.9 h1:/aoBD2+sK2qsXDlNDe3hkR0GZuFDtwIZhOeGUx9W0Yk=
|
||||
github.com/metacubex/sing-mux v0.3.9/go.mod h1:8bT7ZKT3clRrJjYc/x5CRYibC1TX/bK73a3r3+2E+Fc=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a h1:977o0ZYYbiQAGuOxql7Q6UN3rEy59OyAE0tELq4gZfI=
|
||||
github.com/metacubex/sing-quic v0.0.0-20260414034501-3ea3410d197a/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=
|
||||
|
||||
@@ -122,6 +122,7 @@ type tuicServerSchema struct {
|
||||
ALPN *[]string `yaml:"alpn" json:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize *int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
CWND *int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile *string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -305,6 +306,9 @@ func pointerOrDefaultTuicServer(p *tuicServerSchema, def LC.TuicServer) LC.TuicS
|
||||
if p.CWND != nil {
|
||||
def.CWND = *p.CWND
|
||||
}
|
||||
if p.BBRProfile != nil {
|
||||
def.BBRProfile = *p.BBRProfile
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ func router(isDebug bool, secret string, dohServer string, cors Cors) *chi.Mux {
|
||||
r.Mount("/providers/rules", ruleProviderRouter())
|
||||
r.Mount("/cache", cacheRouter())
|
||||
r.Mount("/dns", dnsRouter())
|
||||
r.Mount("/storage", storageRouter())
|
||||
if !embedMode { // disallow restart in embed mode
|
||||
r.Mount("/restart", restartRouter())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||
|
||||
"github.com/metacubex/chi"
|
||||
"github.com/metacubex/chi/render"
|
||||
"github.com/metacubex/http"
|
||||
)
|
||||
|
||||
func storageRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Get("/{key}", getStorage)
|
||||
r.Put("/{key}", setStorage)
|
||||
r.Delete("/{key}", deleteStorage)
|
||||
return r
|
||||
}
|
||||
|
||||
func getStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
data := cachefile.Cache().GetStorage(key)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if len(data) == 0 {
|
||||
w.Write([]byte("null"))
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
|
||||
func setStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, newError(err.Error()))
|
||||
return
|
||||
}
|
||||
if !json.Valid(data) {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, ErrBadRequest)
|
||||
return
|
||||
}
|
||||
if len(data) > 1024*1024 {
|
||||
render.Status(r, http.StatusRequestEntityTooLarge)
|
||||
render.JSON(w, r, newError("payload exceeds 1MB limit"))
|
||||
return
|
||||
}
|
||||
cachefile.Cache().SetStorage(key, data)
|
||||
render.NoContent(w, r)
|
||||
}
|
||||
|
||||
func deleteStorage(w http.ResponseWriter, r *http.Request) {
|
||||
key := getEscapeParam(r, "key")
|
||||
cachefile.Cache().DeleteStorage(key)
|
||||
render.NoContent(w, r)
|
||||
}
|
||||
@@ -24,6 +24,7 @@ type Hysteria2Server struct {
|
||||
IgnoreClientBandwidth bool `yaml:"ignore-client-bandwidth" json:"ignore-client-bandwidth,omitempty"`
|
||||
Masquerade string `yaml:"masquerade" json:"masquerade,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
UdpMTU int `yaml:"udp-mtu" json:"udp-mtu,omitempty"`
|
||||
MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"`
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ type TrustTunnelServer struct {
|
||||
Network []string `yaml:"network" json:"network,omitempty"`
|
||||
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func (t TrustTunnelServer) String() string {
|
||||
|
||||
@@ -23,6 +23,7 @@ type TuicServer struct {
|
||||
MaxUdpRelayPacketSize int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,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"`
|
||||
}
|
||||
|
||||
|
||||
@@ -34,9 +34,24 @@ type XHTTPConfig struct {
|
||||
Path string
|
||||
Host string
|
||||
Mode string
|
||||
XPaddingBytes string
|
||||
XPaddingObfsMode bool
|
||||
XPaddingKey string
|
||||
XPaddingHeader string
|
||||
XPaddingPlacement string
|
||||
XPaddingMethod string
|
||||
UplinkHTTPMethod string
|
||||
SessionPlacement string
|
||||
SessionKey string
|
||||
SeqPlacement string
|
||||
SeqKey string
|
||||
UplinkDataPlacement string
|
||||
UplinkDataKey string
|
||||
UplinkChunkSize string
|
||||
NoSSEHeader bool
|
||||
ScStreamUpServerSecs string
|
||||
ScMaxEachPostBytes int
|
||||
ScMaxBufferedPosts string
|
||||
ScMaxEachPostBytes string
|
||||
}
|
||||
|
||||
func (t VlessServer) String() string {
|
||||
|
||||
@@ -41,6 +41,7 @@ func testInboundAnyTLS(t *testing.T, inboundOptions inbound.AnyTLSOption, outbou
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewAnyTLS(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -57,6 +58,30 @@ func init() {
|
||||
realityPublickey = base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes())
|
||||
}
|
||||
|
||||
type TestDialer struct {
|
||||
dialer C.Dialer
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (t *TestDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
start:
|
||||
conn, err := t.dialer.DialContext(ctx, network, address)
|
||||
if err != nil && ctx.Err() == nil && t.ctx.Err() == nil {
|
||||
// We are conducting tests locally, and they shouldn't fail.
|
||||
// However, a large number of requests in a short period during concurrent testing can exhaust system ports.
|
||||
// This can lead to various errors such as WSAECONNREFUSED and WSAENOBUFS.
|
||||
// So we just retry if the context is not canceled.
|
||||
goto start
|
||||
}
|
||||
return conn, err
|
||||
}
|
||||
|
||||
func (t *TestDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||
return t.dialer.ListenPacket(ctx, network, address, rAddrPort)
|
||||
}
|
||||
|
||||
var _ C.Dialer = (*TestDialer)(nil)
|
||||
|
||||
type TestTunnel struct {
|
||||
HandleTCPConnFn func(conn net.Conn, metadata *C.Metadata)
|
||||
HandleUDPPacketFn func(packet C.UDPPacket, metadata *C.Metadata)
|
||||
@@ -64,6 +89,7 @@ type TestTunnel struct {
|
||||
CloseFn func() error
|
||||
DoSequentialTestFn func(t *testing.T, proxy C.ProxyAdapter)
|
||||
DoConcurrentTestFn func(t *testing.T, proxy C.ProxyAdapter)
|
||||
NewDialerFn func() C.Dialer
|
||||
}
|
||||
|
||||
func (tt *TestTunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {
|
||||
@@ -95,6 +121,10 @@ func (tt *TestTunnel) DoConcurrentTest(t *testing.T, proxy C.ProxyAdapter) {
|
||||
tt.DoConcurrentTestFn(t, proxy)
|
||||
}
|
||||
|
||||
func (tt *TestTunnel) NewDialer() C.Dialer {
|
||||
return tt.NewDialerFn()
|
||||
}
|
||||
|
||||
type TestTunnelListener struct {
|
||||
ch chan net.Conn
|
||||
ctx context.Context
|
||||
@@ -182,15 +212,39 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
}
|
||||
defer instance.Close()
|
||||
|
||||
var dialNum atomic.Int32
|
||||
var extraConns []net.Conn
|
||||
var extraConnsMu sync.Mutex
|
||||
defer func() {
|
||||
extraConnsMu.Lock()
|
||||
extraConns := append([]net.Conn{}, extraConns...) // clone conn list avoid race condition
|
||||
extraConnsMu.Unlock()
|
||||
for _, conn := range extraConns {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
transport := &http.Transport{
|
||||
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
return instance, nil
|
||||
DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
|
||||
dianNum := dialNum.Add(1)
|
||||
if dianNum == 1 { // first dial, return instance
|
||||
return instance, nil
|
||||
}
|
||||
t.Logf("transport dial time %d more than once in: %s", dianNum, t.Name())
|
||||
conn, err := proxy.DialContext(ctx, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extraConnsMu.Lock()
|
||||
extraConns = append(extraConns, conn)
|
||||
extraConnsMu.Unlock()
|
||||
return conn, nil
|
||||
},
|
||||
// from http.DefaultTransport
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
//// from http.DefaultTransport
|
||||
//MaxIdleConns: 100,
|
||||
//IdleConnTimeout: 90 * time.Second,
|
||||
//TLSHandshakeTimeout: 10 * time.Second,
|
||||
//ExpectContinueTimeout: 1 * time.Second,
|
||||
// for our self-signed cert
|
||||
TLSClientConfig: tlsClientConfig.Clone(),
|
||||
// open http2
|
||||
@@ -198,7 +252,7 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
}
|
||||
|
||||
client := http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Timeout: 60 * time.Second,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
@@ -284,8 +338,8 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
//ctx, cancel := context.WithTimeout(ctx, C.DefaultTLSTimeout)
|
||||
//defer cancel()
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -303,6 +357,7 @@ func NewHttpTestTunnel() *TestTunnel {
|
||||
CloseFn: ln.Close,
|
||||
DoSequentialTestFn: sequentialTestFn,
|
||||
DoConcurrentTestFn: concurrentTestFn,
|
||||
NewDialerFn: func() C.Dialer { return &TestDialer{dialer: dialer.NewDialer(), ctx: ctx} },
|
||||
}
|
||||
return tunnel
|
||||
}
|
||||
@@ -26,6 +26,7 @@ type Hysteria2Option struct {
|
||||
IgnoreClientBandwidth bool `inbound:"ignore-client-bandwidth,omitempty"`
|
||||
Masquerade string `inbound:"masquerade,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
UdpMTU int `inbound:"udp-mtu,omitempty"`
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
|
||||
@@ -73,6 +74,7 @@ func NewHysteria2(options *Hysteria2Option) (*Hysteria2, error) {
|
||||
IgnoreClientBandwidth: options.IgnoreClientBandwidth,
|
||||
Masquerade: options.Masquerade,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
UdpMTU: options.UdpMTU,
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
// quic-go special config
|
||||
|
||||
@@ -41,6 +41,7 @@ func testInboundHysteria2(t *testing.T, inboundOptions inbound.Hysteria2Option,
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewHysteria2(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -27,9 +27,10 @@ type Mieru struct {
|
||||
|
||||
type MieruOption struct {
|
||||
BaseOption
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
|
||||
Transport string `inbound:"transport"`
|
||||
Users map[string]string `inbound:"users"`
|
||||
TrafficPattern string `inbound:"traffic-pattern,omitempty"`
|
||||
UserHintIsMandatory bool `inbound:"user-hint-is-mandatory,omitempty"`
|
||||
}
|
||||
|
||||
type mieruListenerFactory struct{}
|
||||
@@ -158,11 +159,18 @@ func buildMieruServerConfig(option *MieruOption, ports utils.IntRanges[uint16])
|
||||
}
|
||||
var trafficPattern *mierupb.TrafficPattern
|
||||
trafficPattern, _ = mierutp.Decode(option.TrafficPattern)
|
||||
var advancedSettings *mierupb.ServerAdvancedSettings
|
||||
if option.UserHintIsMandatory {
|
||||
advancedSettings = &mierupb.ServerAdvancedSettings{
|
||||
UserHintIsMandatory: proto.Bool(true),
|
||||
}
|
||||
}
|
||||
return &mieruserver.ServerConfig{
|
||||
Config: &mierupb.ServerConfig{
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
TrafficPattern: trafficPattern,
|
||||
PortBindings: portBindings,
|
||||
Users: users,
|
||||
TrafficPattern: trafficPattern,
|
||||
AdvancedSettings: advancedSettings,
|
||||
},
|
||||
StreamListenerFactory: mieruListenerFactory{},
|
||||
PacketListenerFactory: mieruListenerFactory{},
|
||||
|
||||
@@ -206,8 +206,9 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
|
||||
Listen: "127.0.0.1",
|
||||
Port: strconv.Itoa(port),
|
||||
},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
Transport: "TCP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
UserHintIsMandatory: true,
|
||||
}
|
||||
in, err := inbound.NewMieru(&inboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -236,6 +237,7 @@ func testInboundMieruTCP(t *testing.T, handshakeMode string) {
|
||||
Password: "password",
|
||||
HandshakeMode: handshakeMode,
|
||||
}
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
out, err := outbound.NewMieru(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
@@ -260,8 +262,9 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
|
||||
Listen: "127.0.0.1",
|
||||
Port: strconv.Itoa(port),
|
||||
},
|
||||
Transport: "UDP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
Transport: "UDP",
|
||||
Users: map[string]string{"test": "password"},
|
||||
UserHintIsMandatory: true,
|
||||
}
|
||||
in, err := inbound.NewMieru(&inboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -290,6 +293,7 @@ func testInboundMieruUDP(t *testing.T, handshakeMode string) {
|
||||
Password: "password",
|
||||
HandshakeMode: handshakeMode,
|
||||
}
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
out, err := outbound.NewMieru(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
|
||||
@@ -28,7 +28,6 @@ func testSingMux(t *testing.T, tunnel *TestTunnel, out outbound.ProxyAdapter) {
|
||||
for _, protocol := range singMuxProtocolList {
|
||||
protocol := protocol
|
||||
t.Run(protocol, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
singMuxOption := outbound.SingMuxOption{
|
||||
Enabled: true,
|
||||
Protocol: protocol,
|
||||
|
||||
@@ -85,6 +85,7 @@ func testInboundShadowSocks0(t *testing.T, inboundOptions inbound.ShadowSocksOpt
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = password
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewShadowSocks(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package inbound_test
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
@@ -42,6 +43,7 @@ func testInboundSudoku(t *testing.T, inboundOptions inbound.SudokuOption, outbou
|
||||
outboundOptions.Name = "sudoku_outbound"
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewSudoku(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -166,6 +168,10 @@ func TestInboundSudoku_CustomTable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInboundSudoku_HTTPMaskMode(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("temporarily skipped on windows due to intermittent failures; tracked in PR")
|
||||
}
|
||||
|
||||
key := "test_key_http_mask_mode"
|
||||
|
||||
for _, mode := range []string{"ws", "stream", "poll", "auto"} {
|
||||
|
||||
@@ -43,6 +43,7 @@ func testInboundTrojan(t *testing.T, inboundOptions inbound.TrojanOption, outbou
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTrojan(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -20,6 +20,7 @@ type TrustTunnelOption struct {
|
||||
Network []string `inbound:"network,omitempty"`
|
||||
CongestionController string `inbound:"congestion-controller,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
}
|
||||
|
||||
func (o TrustTunnelOption) Equal(config C.InboundConfig) bool {
|
||||
@@ -57,6 +58,7 @@ func NewTrustTunnel(options *TrustTunnelOption) (*TrustTunnel, error) {
|
||||
Network: options.Network,
|
||||
CongestionController: options.CongestionController,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ func testInboundTrustTunnel(t *testing.T, inboundOptions inbound.TrustTunnelOpti
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.UserName = "test"
|
||||
outboundOptions.Password = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTrustTunnel(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -24,6 +24,7 @@ type TuicOption struct {
|
||||
ALPN []string `inbound:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize int `inbound:"max-udp-relay-packet-size,omitempty"`
|
||||
CWND int `inbound:"cwnd,omitempty"`
|
||||
BBRProfile string `inbound:"bbr-profile,omitempty"`
|
||||
MuxOption MuxOption `inbound:"mux-option,omitempty"`
|
||||
}
|
||||
|
||||
@@ -62,6 +63,7 @@ func NewTuic(options *TuicOption) (*Tuic, error) {
|
||||
ALPN: options.ALPN,
|
||||
MaxUdpRelayPacketSize: options.MaxUdpRelayPacketSize,
|
||||
CWND: options.CWND,
|
||||
BBRProfile: options.BBRProfile,
|
||||
MuxOption: options.MuxOption.Build(),
|
||||
},
|
||||
}, nil
|
||||
|
||||
@@ -69,6 +69,7 @@ func testInboundTuic0(t *testing.T, inboundOptions inbound.TuicOption, outboundO
|
||||
outboundOptions.Name = "tuic_outbound"
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewTuic(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -35,9 +35,24 @@ type XHTTPConfig struct {
|
||||
Path string `inbound:"path,omitempty"`
|
||||
Host string `inbound:"host,omitempty"`
|
||||
Mode string `inbound:"mode,omitempty"`
|
||||
XPaddingBytes string `inbound:"x-padding-bytes,omitempty"`
|
||||
XPaddingObfsMode bool `inbound:"x-padding-obfs-mode,omitempty"`
|
||||
XPaddingKey string `inbound:"x-padding-key,omitempty"`
|
||||
XPaddingHeader string `inbound:"x-padding-header,omitempty"`
|
||||
XPaddingPlacement string `inbound:"x-padding-placement,omitempty"`
|
||||
XPaddingMethod string `inbound:"x-padding-method,omitempty"`
|
||||
UplinkHTTPMethod string `inbound:"uplink-http-method,omitempty"`
|
||||
SessionPlacement string `inbound:"session-placement,omitempty"`
|
||||
SessionKey string `inbound:"session-key,omitempty"`
|
||||
SeqPlacement string `inbound:"seq-placement,omitempty"`
|
||||
SeqKey string `inbound:"seq-key,omitempty"`
|
||||
UplinkDataPlacement string `inbound:"uplink-data-placement,omitempty"`
|
||||
UplinkDataKey string `inbound:"uplink-data-key,omitempty"`
|
||||
UplinkChunkSize string `inbound:"uplink-chunk-size,omitempty"`
|
||||
NoSSEHeader bool `inbound:"no-sse-header,omitempty"`
|
||||
ScStreamUpServerSecs string `inbound:"sc-stream-up-server-secs,omitempty"`
|
||||
ScMaxEachPostBytes int `inbound:"sc-max-each-post-bytes,omitempty"`
|
||||
ScMaxBufferedPosts string `inbound:"sc-max-buffered-posts,omitempty"`
|
||||
ScMaxEachPostBytes string `inbound:"sc-max-each-post-bytes,omitempty"`
|
||||
}
|
||||
|
||||
func (o XHTTPConfig) Build() LC.XHTTPConfig {
|
||||
@@ -46,7 +61,21 @@ func (o XHTTPConfig) Build() LC.XHTTPConfig {
|
||||
Host: o.Host,
|
||||
Mode: o.Mode,
|
||||
NoSSEHeader: o.NoSSEHeader,
|
||||
XPaddingBytes: o.XPaddingBytes,
|
||||
XPaddingObfsMode: o.XPaddingObfsMode,
|
||||
XPaddingKey: o.XPaddingKey,
|
||||
XPaddingHeader: o.XPaddingHeader,
|
||||
XPaddingPlacement: o.XPaddingPlacement,
|
||||
UplinkHTTPMethod: o.UplinkHTTPMethod,
|
||||
SessionPlacement: o.SessionPlacement,
|
||||
SessionKey: o.SessionKey,
|
||||
SeqPlacement: o.SeqPlacement,
|
||||
SeqKey: o.SeqKey,
|
||||
UplinkDataPlacement: o.UplinkDataPlacement,
|
||||
UplinkDataKey: o.UplinkDataKey,
|
||||
UplinkChunkSize: o.UplinkChunkSize,
|
||||
ScStreamUpServerSecs: o.ScStreamUpServerSecs,
|
||||
ScMaxBufferedPosts: o.ScMaxBufferedPosts,
|
||||
ScMaxEachPostBytes: o.ScMaxEachPostBytes,
|
||||
}
|
||||
}
|
||||
|
||||
+218
-54
@@ -44,6 +44,7 @@ func testInboundVless(t *testing.T, inboundOptions inbound.VlessOption, outbound
|
||||
outboundOptions.Server = addrPort.Addr().String()
|
||||
outboundOptions.Port = int(addrPort.Port())
|
||||
outboundOptions.UUID = userUUID
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewVless(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
@@ -377,40 +378,43 @@ func TestInboundVless_XHTTP(t *testing.T) {
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if testCase.mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
testInboundVless_XHTTP(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testInboundVless_XHTTP(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, outboundOptions, false)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVlessTLS(t, inboundOptions, withXHTTPReuse(outboundOptions), false)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_Reality(t *testing.T) {
|
||||
testCases := []struct {
|
||||
mode string
|
||||
@@ -454,36 +458,196 @@ func TestInboundVless_XHTTP_Reality(t *testing.T) {
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Reality(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
func testInboundVless_XHTTP_Reality(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if testCase.mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_Encryption(t *testing.T) {
|
||||
privateKeyBase64, passwordBase64, _, err := encryption.GenX25519("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Decryption: "mlkem768x25519plus.native.600s." + privateKeyBase64,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
Encryption: "mlkem768x25519plus.native.0rtt." + passwordBase64,
|
||||
Network: "xhttp",
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Encryption(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
func testInboundVless_XHTTP_Encryption(t *testing.T, getConfig func() (inbound.VlessOption, outbound.VlessOption), mode string) {
|
||||
t.Run("nosplit", func(t *testing.T) {
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("split", func(t *testing.T) {
|
||||
if mode == "stream-one" { // stream-one not supported download settings
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("single", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
inboundOptions, outboundOptions := getConfig()
|
||||
outboundOptions.XHTTPOpts.DownloadSettings = &outbound.XHTTPDownloadSettings{}
|
||||
testInboundVless(t, inboundOptions, withXHTTPReuse(outboundOptions))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_H1(t *testing.T) {
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Certificate: tlsCertificate,
|
||||
PrivateKey: tlsPrivateKey,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
TLS: true,
|
||||
Fingerprint: tlsFingerprint,
|
||||
Network: "xhttp",
|
||||
ALPN: []string{"http/1.1"},
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundVless_XHTTP_H1_Encryption(t *testing.T) {
|
||||
privateKeyBase64, passwordBase64, _, err := encryption.GenX25519("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
testCases := []struct {
|
||||
mode string
|
||||
}{
|
||||
{mode: "auto"},
|
||||
{mode: "stream-one"},
|
||||
{mode: "stream-up"},
|
||||
{mode: "packet-up"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run(testCase.mode, func(t *testing.T) {
|
||||
getConfig := func() (inbound.VlessOption, outbound.VlessOption) {
|
||||
inboundOptions := inbound.VlessOption{
|
||||
Decryption: "mlkem768x25519plus.native.600s." + privateKeyBase64,
|
||||
XHTTPConfig: inbound.XHTTPConfig{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
outboundOptions := outbound.VlessOption{
|
||||
Encryption: "mlkem768x25519plus.native.0rtt." + passwordBase64,
|
||||
Network: "xhttp",
|
||||
ALPN: []string{"http/1.1"},
|
||||
XHTTPOpts: outbound.XHTTPOptions{
|
||||
Path: "/vless-xhttp",
|
||||
Host: "example.com",
|
||||
Mode: testCase.mode,
|
||||
},
|
||||
}
|
||||
return inboundOptions, outboundOptions
|
||||
}
|
||||
testInboundVless_XHTTP_Encryption(t, getConfig, testCase.mode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ func testInboundVMess(t *testing.T, inboundOptions inbound.VmessOption, outbound
|
||||
outboundOptions.UUID = userUUID
|
||||
outboundOptions.AlterID = 0
|
||||
outboundOptions.Cipher = "auto"
|
||||
outboundOptions.DialerForAPI = tunnel.NewDialer()
|
||||
|
||||
out, err := outbound.NewVmess(outboundOptions)
|
||||
if !assert.NoError(t, err) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/metacubex/mihomo/listener/sing"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/ntp"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/httputil"
|
||||
@@ -171,8 +172,10 @@ func New(config LC.Hysteria2Server, tunnel C.Tunnel, additions ...inbound.Additi
|
||||
UDPTimeout: sing.UDPTimeout,
|
||||
Handler: h,
|
||||
MasqueradeHandler: masqueradeHandler,
|
||||
CWND: config.CWND,
|
||||
UdpMTU: config.UdpMTU,
|
||||
SetBBRCongestion: func(quicConn *quic.Conn) {
|
||||
common.SetCongestionController(quicConn, "bbr", config.CWND, config.BBRProfile)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -157,7 +157,7 @@ func New(options LC.Tun, tunnel C.Tunnel, additions ...inbound.Addition) (l *Lis
|
||||
if options.FileDescriptor > 0 {
|
||||
if tunnelName, err := getTunnelName(int32(options.FileDescriptor)); err == nil {
|
||||
tunName = tunnelName // sing-tun must have the truth tun interface name even it from a fd
|
||||
forwarderBindInterface = true
|
||||
//forwarderBindInterface = true
|
||||
log.Debugln("[TUN] use tun name %s for fd %d", tunnelName, options.FileDescriptor)
|
||||
} else {
|
||||
log.Warnln("[TUN] get tun name failed for fd %d, fallback to use tun interface name %s", options.FileDescriptor, tunName)
|
||||
|
||||
@@ -154,13 +154,28 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
}
|
||||
}
|
||||
if config.XHTTPConfig.Path != "" || config.XHTTPConfig.Host != "" || config.XHTTPConfig.Mode != "" {
|
||||
httpServer.Handler = xhttp.NewServerHandler(xhttp.ServerOption{
|
||||
httpServer.Handler, err = xhttp.NewServerHandler(xhttp.ServerOption{
|
||||
Config: xhttp.Config{
|
||||
Host: config.XHTTPConfig.Host,
|
||||
Path: config.XHTTPConfig.Path,
|
||||
Mode: config.XHTTPConfig.Mode,
|
||||
XPaddingBytes: config.XHTTPConfig.XPaddingBytes,
|
||||
XPaddingObfsMode: config.XHTTPConfig.XPaddingObfsMode,
|
||||
XPaddingKey: config.XHTTPConfig.XPaddingKey,
|
||||
XPaddingHeader: config.XHTTPConfig.XPaddingHeader,
|
||||
XPaddingPlacement: config.XHTTPConfig.XPaddingPlacement,
|
||||
XPaddingMethod: config.XHTTPConfig.XPaddingMethod,
|
||||
UplinkHTTPMethod: config.XHTTPConfig.UplinkHTTPMethod,
|
||||
SessionPlacement: config.XHTTPConfig.SessionPlacement,
|
||||
SessionKey: config.XHTTPConfig.SessionKey,
|
||||
SeqPlacement: config.XHTTPConfig.SeqPlacement,
|
||||
SeqKey: config.XHTTPConfig.SeqKey,
|
||||
UplinkDataPlacement: config.XHTTPConfig.UplinkDataPlacement,
|
||||
UplinkDataKey: config.XHTTPConfig.UplinkDataKey,
|
||||
UplinkChunkSize: config.XHTTPConfig.UplinkChunkSize,
|
||||
NoSSEHeader: config.XHTTPConfig.NoSSEHeader,
|
||||
ScStreamUpServerSecs: config.XHTTPConfig.ScStreamUpServerSecs,
|
||||
ScMaxBufferedPosts: config.XHTTPConfig.ScMaxBufferedPosts,
|
||||
ScMaxEachPostBytes: config.XHTTPConfig.ScMaxEachPostBytes,
|
||||
},
|
||||
ConnHandler: func(conn net.Conn) {
|
||||
@@ -168,6 +183,9 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
},
|
||||
HttpHandler: httpServer.Handler,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(tlsConfig.NextProtos, "http/1.1") {
|
||||
tlsConfig.NextProtos = append([]string{"http/1.1"}, tlsConfig.NextProtos...)
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ func New(config LC.TrustTunnelServer, tunnel C.Tunnel, additions ...inbound.Addi
|
||||
ICMPHandler: nil,
|
||||
QUICCongestionControl: config.CongestionController,
|
||||
QUICCwnd: config.CWND,
|
||||
QUICBBRProfile: config.BBRProfile,
|
||||
})
|
||||
service.UpdateUsers(config.Users)
|
||||
err = service.Start(tcpListener, udpConn, tlsConfig)
|
||||
|
||||
@@ -155,6 +155,7 @@ func New(config LC.TuicServer, tunnel C.Tunnel, additions ...inbound.Addition) (
|
||||
AuthenticationTimeout: time.Duration(config.AuthenticationTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: config.MaxUdpRelayPacketSize,
|
||||
CWND: config.CWND,
|
||||
BBRProfile: config.BBRProfile,
|
||||
}
|
||||
if len(config.Token) > 0 {
|
||||
tokens := make([][32]byte, len(config.Token))
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/cmd"
|
||||
"github.com/metacubex/mihomo/component/generator"
|
||||
"github.com/metacubex/mihomo/component/geodata"
|
||||
"github.com/metacubex/mihomo/component/updater"
|
||||
@@ -41,6 +42,8 @@ var (
|
||||
externalControllerUnix string
|
||||
externalControllerPipe string
|
||||
secret string
|
||||
postUp string
|
||||
postDown string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -52,6 +55,8 @@ func init() {
|
||||
flag.StringVar(&externalControllerUnix, "ext-ctl-unix", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_UNIX"), "override external controller unix address")
|
||||
flag.StringVar(&externalControllerPipe, "ext-ctl-pipe", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_PIPE"), "override external controller pipe address")
|
||||
flag.StringVar(&secret, "secret", os.Getenv("CLASH_OVERRIDE_SECRET"), "override secret for RESTful API")
|
||||
flag.StringVar(&postUp, "post-up", os.Getenv("CLASH_POST_UP"), "set post-up script")
|
||||
flag.StringVar(&postDown, "post-down", os.Getenv("CLASH_POST_DOWN"), "set post-down script")
|
||||
flag.BoolVar(&geodataMode, "m", false, "set geodata mode")
|
||||
flag.BoolVar(&version, "v", false, "show current version of mihomo")
|
||||
flag.BoolVar(&testConfig, "t", false, "test configuration and exit")
|
||||
@@ -184,6 +189,19 @@ func main() {
|
||||
updater.RegisterGeoUpdater()
|
||||
}
|
||||
|
||||
if postDown != "" {
|
||||
defer func() {
|
||||
if _, err := cmd.ExecShell(postDown); err != nil {
|
||||
log.Errorln("post-down script error: %s", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
if postUp != "" {
|
||||
if _, err := cmd.ExecShell(postUp); err != nil {
|
||||
log.Fatalln("post-up script error: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
defer executor.Shutdown()
|
||||
|
||||
termSign := make(chan os.Signal, 1)
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
package masque
|
||||
|
||||
// copy and modify from: https://github.com/Diniboy1123/connect-ip-go/blob/8d7bb0a858a2674046a7cb5538749e4c826c3538/client_h2.go
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/metacubex/mihomo/common/contextutils"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/quic-go/quicvarint"
|
||||
"github.com/yosida95/uritemplate/v3"
|
||||
)
|
||||
|
||||
const h2DatagramCapsuleType uint64 = 0
|
||||
|
||||
const (
|
||||
ipv4HeaderLen = 20
|
||||
ipv6HeaderLen = 40
|
||||
)
|
||||
|
||||
func ConnectTunnelH2(ctx context.Context, h2Transport *http.Http2Transport, connectUri string) (*http.Http2ClientConn, IpConn, error) {
|
||||
additionalHeaders := http.Header{
|
||||
"User-Agent": []string{""},
|
||||
}
|
||||
template := uritemplate.MustNew(connectUri)
|
||||
|
||||
h2Headers := additionalHeaders.Clone()
|
||||
h2Headers.Set("cf-connect-proto", "cf-connect-ip")
|
||||
// TODO: support PQC
|
||||
h2Headers.Set("pq-enabled", "false")
|
||||
|
||||
conn, err := h2Transport.DialTLSContext(ctx, "tcp", ":0", nil)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to dial: %w", err)
|
||||
}
|
||||
|
||||
cc, err := h2Transport.NewClientConn(conn)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to create client connection: %w", err)
|
||||
}
|
||||
|
||||
if !cc.ReserveNewRequest() {
|
||||
_ = cc.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to reserve client connection: %w", err)
|
||||
}
|
||||
|
||||
ipConn, rsp, err := dialH2(ctx, cc, template, h2Headers)
|
||||
if err != nil {
|
||||
_ = cc.Close()
|
||||
if strings.Contains(err.Error(), "tls: access denied") {
|
||||
return nil, nil, errors.New("login failed! Please double-check if your tls key and cert is enrolled in the Cloudflare Access service")
|
||||
}
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip over HTTP/2: %w", err)
|
||||
}
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
_ = ipConn.Close()
|
||||
_ = cc.Close()
|
||||
return nil, nil, fmt.Errorf("failed to dial connect-ip: %v", rsp.Status)
|
||||
}
|
||||
|
||||
return cc, ipConn, nil
|
||||
}
|
||||
|
||||
// dialH2 dials a proxied connection over HTTP/2 CONNECT-IP.
|
||||
//
|
||||
// This transport carries proxied packets inside HTTP capsule DATAGRAM frames.
|
||||
func dialH2(ctx context.Context, rt http.RoundTripper, template *uritemplate.Template, additionalHeaders http.Header) (*h2IpConn, *http.Response, error) {
|
||||
if len(template.Varnames()) > 0 {
|
||||
return nil, nil, errors.New("connect-ip: IP flow forwarding not supported")
|
||||
}
|
||||
|
||||
u, err := url.Parse(template.Raw())
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to parse URI: %w", err)
|
||||
}
|
||||
|
||||
reqCtx, cancel := context.WithCancel(context.Background()) // reqCtx must disconnect from ctx, otherwise ctx would close the entire HTTP/2 connection.
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodConnect, u.String(), pr)
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to create request: %w", err)
|
||||
}
|
||||
req.Host = authorityFromURL(u)
|
||||
req.ContentLength = -1
|
||||
req.Header = make(http.Header)
|
||||
for k, v := range additionalHeaders {
|
||||
req.Header[k] = v
|
||||
}
|
||||
|
||||
stop := contextutils.AfterFunc(ctx, cancel) // temporarily connect ctx with reqCtx when client.Do
|
||||
rsp, err := rt.RoundTrip(req)
|
||||
stop() // disconnect ctx with reqCtx after client.Do
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
return nil, nil, fmt.Errorf("connect-ip: failed to send request: %w", err)
|
||||
}
|
||||
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
|
||||
cancel()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
_ = rsp.Body.Close()
|
||||
return nil, rsp, fmt.Errorf("connect-ip: server responded with %d", rsp.StatusCode)
|
||||
}
|
||||
|
||||
stream := &h2DatagramStream{
|
||||
requestBody: pw,
|
||||
responseBody: rsp.Body,
|
||||
cancel: cancel,
|
||||
}
|
||||
return &h2IpConn{
|
||||
str: stream,
|
||||
closeChan: make(chan struct{}),
|
||||
}, rsp, nil
|
||||
}
|
||||
|
||||
func authorityFromURL(u *url.URL) string {
|
||||
if u.Port() != "" {
|
||||
return u.Host
|
||||
}
|
||||
host := u.Hostname()
|
||||
if host == "" {
|
||||
return u.Host
|
||||
}
|
||||
return host + ":443"
|
||||
}
|
||||
|
||||
type h2IpConn struct {
|
||||
str *h2DatagramStream
|
||||
|
||||
mu sync.Mutex
|
||||
|
||||
closeChan chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (c *h2IpConn) ReadPacket() (b []byte, err error) {
|
||||
start:
|
||||
data, err := c.str.ReceiveDatagram(context.Background())
|
||||
if err != nil {
|
||||
defer func() {
|
||||
// There are no errors that can be recovered in h2 mode,
|
||||
// so calling Close allows the outer read loop to exit in the next iteration by returning net.ErrClosed.
|
||||
_ = c.Close()
|
||||
}()
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := c.handleIncomingProxiedPacket(data); err != nil {
|
||||
log.Debugln("dropping proxied packet: %s", err)
|
||||
goto start
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) handleIncomingProxiedPacket(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return errors.New("connect-ip: empty packet")
|
||||
}
|
||||
switch v := ipVersion(data); v {
|
||||
default:
|
||||
return fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(data) < ipv4HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
case 6:
|
||||
if len(data) < ipv6HeaderLen {
|
||||
return fmt.Errorf("connect-ip: malformed datagram: too short")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WritePacket writes an IP packet to the stream.
|
||||
// If sending the packet fails, it might return an ICMP packet.
|
||||
// It is the caller's responsibility to send the ICMP packet to the sender.
|
||||
func (c *h2IpConn) WritePacket(b []byte) (icmp []byte, err error) {
|
||||
data, err := c.composeDatagram(b)
|
||||
if err != nil {
|
||||
log.Debugln("dropping proxied packet (%d bytes) that can't be proxied: %s", len(b), err)
|
||||
return nil, nil
|
||||
}
|
||||
if err := c.str.SendDatagram(data); err != nil {
|
||||
select {
|
||||
case <-c.closeChan:
|
||||
return nil, c.closeErr
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) composeDatagram(b []byte) ([]byte, error) {
|
||||
// TODO: implement src, dst and ipproto checks
|
||||
if len(b) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
switch v := ipVersion(b); v {
|
||||
default:
|
||||
return nil, fmt.Errorf("connect-ip: unknown IP versions: %d", v)
|
||||
case 4:
|
||||
if len(b) < ipv4HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv4 packet too short")
|
||||
}
|
||||
ttl := b[8]
|
||||
if ttl <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram TTL too small: %d", ttl)
|
||||
}
|
||||
b[8]-- // decrement TTL
|
||||
// recalculate the checksum
|
||||
binary.BigEndian.PutUint16(b[10:12], calculateIPv4Checksum(([ipv4HeaderLen]byte)(b[:ipv4HeaderLen])))
|
||||
case 6:
|
||||
if len(b) < ipv6HeaderLen {
|
||||
return nil, fmt.Errorf("connect-ip: IPv6 packet too short")
|
||||
}
|
||||
hopLimit := b[7]
|
||||
if hopLimit <= 1 {
|
||||
return nil, fmt.Errorf("connect-ip: datagram Hop Limit too small: %d", hopLimit)
|
||||
}
|
||||
b[7]-- // Decrement Hop Limit
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (c *h2IpConn) Close() error {
|
||||
c.mu.Lock()
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = net.ErrClosed
|
||||
close(c.closeChan)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
err := c.str.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
func ipVersion(b []byte) uint8 { return b[0] >> 4 }
|
||||
|
||||
func calculateIPv4Checksum(header [ipv4HeaderLen]byte) uint16 {
|
||||
// add every 16-bit word in the header, skipping the checksum field (bytes 10 and 11)
|
||||
var sum uint32
|
||||
for i := 0; i < len(header); i += 2 {
|
||||
if i == 10 {
|
||||
continue // skip checksum field
|
||||
}
|
||||
sum += uint32(binary.BigEndian.Uint16(header[i : i+2]))
|
||||
}
|
||||
for (sum >> 16) > 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
return ^uint16(sum)
|
||||
}
|
||||
|
||||
type h2DatagramStream struct {
|
||||
requestBody *io.PipeWriter
|
||||
responseBody io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
|
||||
readMu sync.Mutex
|
||||
writeMu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) ReceiveDatagram(_ context.Context) ([]byte, error) {
|
||||
s.readMu.Lock()
|
||||
defer s.readMu.Unlock()
|
||||
|
||||
reader := quicvarint.NewReader(s.responseBody)
|
||||
for {
|
||||
capsuleType, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payloadLen, err := quicvarint.Read(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := make([]byte, payloadLen)
|
||||
_, err = io.ReadFull(reader, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capsuleType != h2DatagramCapsuleType {
|
||||
continue
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) SendDatagram(data []byte) error {
|
||||
frame := make([]byte, 0, quicvarint.Len(h2DatagramCapsuleType)+quicvarint.Len(uint64(len(data)))+len(data))
|
||||
frame = quicvarint.Append(frame, h2DatagramCapsuleType)
|
||||
frame = quicvarint.Append(frame, uint64(len(data)))
|
||||
frame = append(frame, data...)
|
||||
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
_, err := s.requestBody.Write(frame)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect-ip: failed to send datagram capsule: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *h2DatagramStream) Close() error {
|
||||
_ = s.requestBody.Close()
|
||||
err := s.responseBody.Close()
|
||||
s.cancel()
|
||||
return err
|
||||
}
|
||||
@@ -27,9 +27,15 @@ const (
|
||||
ConnectURI = "https://cloudflareaccess.com"
|
||||
)
|
||||
|
||||
type IpConn interface {
|
||||
ReadPacket() (b []byte, err error)
|
||||
WritePacket(b []byte) (icmp []byte, err error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// PrepareTlsConfig creates a TLS configuration using the provided certificate and SNI (Server Name Indication).
|
||||
// It also verifies the peer's public key against the provided public key.
|
||||
func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string) (*tls.Config, error) {
|
||||
func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sni string, insecure bool) (*tls.Config, error) {
|
||||
verfiyCert := func(cert *x509.Certificate) error {
|
||||
if _, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
|
||||
// we only support ECDSA
|
||||
@@ -77,6 +83,9 @@ func PrepareTlsConfig(privKey *ecdsa.PrivateKey, peerPubKey *ecdsa.PublicKey, sn
|
||||
return err
|
||||
},
|
||||
}
|
||||
if insecure {
|
||||
tlsConfig.VerifyConnection = nil
|
||||
}
|
||||
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
"github.com/metacubex/mihomo/common/once"
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/vmess"
|
||||
|
||||
@@ -22,11 +22,11 @@ import (
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
type ResolvUDPFunc func(ctx context.Context, server string) (netip.AddrPort, error)
|
||||
type DialOptionsFunc func() []dialer.Option
|
||||
|
||||
type ClientOptions struct {
|
||||
Dialer C.Dialer
|
||||
ResolvUDP ResolvUDPFunc
|
||||
DialOptions DialOptionsFunc // for quic
|
||||
Server string
|
||||
Username string
|
||||
Password string
|
||||
@@ -34,6 +34,7 @@ type ClientOptions struct {
|
||||
QUIC bool
|
||||
QUICCongestionControl string
|
||||
QUICCwnd int
|
||||
QUICBBRProfile string
|
||||
HealthCheck bool
|
||||
MaxConnections int
|
||||
MinStreams int
|
||||
@@ -43,7 +44,7 @@ type ClientOptions struct {
|
||||
type Client struct {
|
||||
ctx context.Context
|
||||
dialer C.Dialer
|
||||
resolv ResolvUDPFunc
|
||||
dialOptions DialOptionsFunc
|
||||
server string
|
||||
auth string
|
||||
roundTripper http.RoundTripper
|
||||
@@ -55,11 +56,11 @@ type Client struct {
|
||||
|
||||
func NewClient(ctx context.Context, options ClientOptions) (client *Client, err error) {
|
||||
client = &Client{
|
||||
ctx: ctx,
|
||||
dialer: options.Dialer,
|
||||
resolv: options.ResolvUDP,
|
||||
server: options.Server,
|
||||
auth: buildAuth(options.Username, options.Password),
|
||||
ctx: ctx,
|
||||
dialer: options.Dialer,
|
||||
dialOptions: options.DialOptions,
|
||||
server: options.Server,
|
||||
auth: buildAuth(options.Username, options.Password),
|
||||
}
|
||||
if options.QUIC {
|
||||
if len(options.TLSConfig.NextProtos) == 0 {
|
||||
@@ -67,7 +68,7 @@ func NewClient(ctx context.Context, options ClientOptions) (client *Client, err
|
||||
} else if !slices.Contains(options.TLSConfig.NextProtos, "h3") {
|
||||
return nil, errors.New("require alpn h3")
|
||||
}
|
||||
err = client.quicRoundTripper(options.TLSConfig, options.QUICCongestionControl, options.QUICCwnd)
|
||||
err = client.quicRoundTripper(options.TLSConfig, options.QUICCongestionControl, options.QUICCwnd, options.QUICBBRProfile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -154,66 +155,51 @@ func (c *Client) roundTrip(request *http.Request, conn *httpConn) {
|
||||
if err != nil {
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
conn.setUp(nil, err)
|
||||
conn.setup(nil, err)
|
||||
} else if response.StatusCode != http.StatusOK {
|
||||
_ = response.Body.Close()
|
||||
err = fmt.Errorf("unexpected status code: %d", response.StatusCode)
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
conn.setUp(nil, err)
|
||||
conn.setup(nil, err)
|
||||
} else {
|
||||
c.resetHealthCheckTimer()
|
||||
conn.setUp(response.Body, nil)
|
||||
conn.setup(response.Body, nil)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *Client) Dial(ctx context.Context, host string) (net.Conn, error) {
|
||||
func (c *Client) newConnectRequest(host, userAgent string) *http.Request {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: host,
|
||||
Host: c.server, // Use the proxy server authority so the pool keys reuse against the actual proxy endpoint.
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: host,
|
||||
Host: host, // Send the actual CONNECT target as the Host header (:authority).
|
||||
}
|
||||
request.Header.Add("User-Agent", TCPUserAgent)
|
||||
request.Header.Add("User-Agent", userAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
return request
|
||||
}
|
||||
|
||||
func (c *Client) Dial(ctx context.Context, host string) (net.Conn, error) {
|
||||
request := c.newConnectRequest(host, TCPUserAgent)
|
||||
conn := &tcpConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenPacket(ctx context.Context) (net.PacketConn, error) {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: UDPMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: UDPMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", UDPUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(UDPMagicAddress, UDPUserAgent)
|
||||
conn := &clientPacketConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenICMP(ctx context.Context) (*IcmpConn, error) {
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: ICMPMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: ICMPMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", ICMPUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(ICMPMagicAddress, ICMPUserAgent)
|
||||
conn := &IcmpConn{}
|
||||
c.roundTrip(request, &conn.httpConn)
|
||||
return conn, nil
|
||||
@@ -234,17 +220,7 @@ func (c *Client) ResetConnections() {
|
||||
|
||||
func (c *Client) HealthCheck(ctx context.Context) error {
|
||||
defer c.resetHealthCheckTimer()
|
||||
request := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: HealthCheckMagicAddress,
|
||||
},
|
||||
Header: make(http.Header),
|
||||
Host: HealthCheckMagicAddress,
|
||||
}
|
||||
request.Header.Add("User-Agent", HealthCheckUserAgent)
|
||||
request.Header.Add("Proxy-Authorization", c.auth)
|
||||
request := c.newConnectRequest(HealthCheckMagicAddress, HealthCheckUserAgent)
|
||||
response, err := c.roundTripper.RoundTrip(request.WithContext(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -271,7 +247,8 @@ func NewPoolClient(ctx context.Context, options ClientOptions) (*PoolClient, err
|
||||
minStreams := options.MinStreams
|
||||
maxStreams := options.MaxStreams
|
||||
if maxConnections == 0 && minStreams == 0 && maxStreams == 0 {
|
||||
maxConnections = 1
|
||||
maxConnections = 8
|
||||
minStreams = 5
|
||||
}
|
||||
client, err := NewClient(ctx, options) // reserve one client and verify the configuration
|
||||
if err != nil {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
@@ -95,6 +96,7 @@ type httpConn struct {
|
||||
writer io.Writer
|
||||
flusher http.Flusher
|
||||
body io.ReadCloser
|
||||
setupOnce sync.Once
|
||||
created chan struct{}
|
||||
createErr error
|
||||
cancelFn func()
|
||||
@@ -105,22 +107,28 @@ type httpConn struct {
|
||||
deadline *time.Timer
|
||||
}
|
||||
|
||||
func (h *httpConn) setUp(body io.ReadCloser, err error) {
|
||||
h.body = body
|
||||
h.createErr = err
|
||||
close(h.created)
|
||||
func (h *httpConn) setup(body io.ReadCloser, err error) {
|
||||
h.setupOnce.Do(func() {
|
||||
h.body = body
|
||||
h.createErr = err
|
||||
close(h.created)
|
||||
})
|
||||
if h.createErr != nil && body != nil { // conn already closed before setup
|
||||
_ = body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *httpConn) waitCreated() error {
|
||||
if h.body != nil || h.createErr != nil {
|
||||
return h.createErr
|
||||
}
|
||||
<-h.created
|
||||
if h.body != nil {
|
||||
return nil
|
||||
}
|
||||
return h.createErr
|
||||
}
|
||||
|
||||
func (h *httpConn) Close() error {
|
||||
var errorArr []error
|
||||
h.setup(nil, net.ErrClosed)
|
||||
if closer, ok := h.writer.(io.Closer); ok {
|
||||
errorArr = append(errorArr, closer.Close())
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlName string, cwnd int) error {
|
||||
func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlName string, cwnd int, bbrProfile string) error {
|
||||
stdConfig, err := tlsConfig.ToStdConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -30,24 +30,15 @@ func (c *Client) quicRoundTripper(tlsConfig *vmess.TLSConfig, congestionControlN
|
||||
Allow0RTT: false,
|
||||
},
|
||||
Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (*quic.Conn, error) {
|
||||
addrPort, err := c.resolv(ctx, c.server)
|
||||
err := tlsConfig.ECH.ClientHandle(ctx, tlsCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tlsConfig.ECH.ClientHandle(ctx, tlsCfg)
|
||||
_, quicConn, err := common.DialQuic(ctx, addr, c.dialOptions(), c.dialer, tlsCfg, cfg, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packetConn, err := c.dialer.ListenPacket(ctx, "udp", "", addrPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quicConn, err := quic.DialEarly(ctx, packetConn, net.UDPAddrFromAddrPort(addrPort), tlsCfg, cfg)
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
common.SetCongestionController(quicConn, congestionControlName, cwnd)
|
||||
common.SetCongestionController(quicConn, congestionControlName, cwnd, bbrProfile)
|
||||
return quicConn, nil
|
||||
},
|
||||
}
|
||||
@@ -69,7 +60,7 @@ func (s *Service) configHTTP3Server(tlsConfig *tls.Config, udpConn net.PacketCon
|
||||
Handler: s,
|
||||
IdleTimeout: DefaultSessionTimeout,
|
||||
ConnContext: func(ctx context.Context, conn *quic.Conn) context.Context {
|
||||
common.SetCongestionController(conn, s.quicCongestionControl, s.quicCwnd)
|
||||
common.SetCongestionController(conn, s.quicCongestionControl, s.quicCwnd, s.quicBBRProfile)
|
||||
return ctx
|
||||
},
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/h2c"
|
||||
@@ -18,13 +19,13 @@ import (
|
||||
E "github.com/metacubex/sing/common/exceptions"
|
||||
"github.com/metacubex/sing/common/logger"
|
||||
M "github.com/metacubex/sing/common/metadata"
|
||||
N "github.com/metacubex/sing/common/network"
|
||||
"github.com/metacubex/sing/common/network"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
N.TCPConnectionHandler
|
||||
N.UDPConnectionHandler
|
||||
network.TCPConnectionHandler
|
||||
network.UDPConnectionHandler
|
||||
}
|
||||
|
||||
type ICMPHandler interface {
|
||||
@@ -38,6 +39,7 @@ type ServiceOptions struct {
|
||||
ICMPHandler ICMPHandler
|
||||
QUICCongestionControl string
|
||||
QUICCwnd int
|
||||
QUICBBRProfile string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
@@ -48,6 +50,7 @@ type Service struct {
|
||||
icmpHandler ICMPHandler
|
||||
quicCongestionControl string
|
||||
quicCwnd int
|
||||
quicBBRProfile string
|
||||
httpServer *http.Server
|
||||
h2Server *http.Http2Server
|
||||
h3Server *http3.Server
|
||||
@@ -64,6 +67,7 @@ func NewService(options ServiceOptions) *Service {
|
||||
icmpHandler: options.ICMPHandler,
|
||||
quicCongestionControl: options.QUICCongestionControl,
|
||||
quicCwnd: options.QUICCwnd,
|
||||
quicBBRProfile: options.QUICBBRProfile,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +167,7 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
conn.setup(request.Body, nil)
|
||||
firstPacket := buf.NewPacket()
|
||||
destination, err := conn.ReadPacket(firstPacket)
|
||||
if err != nil {
|
||||
@@ -200,7 +204,7 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
conn.setup(request.Body, nil)
|
||||
s.icmpHandler.NewICMPConnection(ctx, conn)
|
||||
}
|
||||
case HealthCheckMagicAddress:
|
||||
@@ -223,8 +227,8 @@ func (s *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
},
|
||||
}
|
||||
httputils.SetAddrFromRequest(&conn.NetAddr, request)
|
||||
conn.setUp(request.Body, nil)
|
||||
_ = s.handler.NewConnection(ctx, conn, M.Metadata{
|
||||
conn.setup(request.Body, nil)
|
||||
_ = s.handler.NewConnection(ctx, N.NewDeadlineConn(conn), M.Metadata{
|
||||
Protocol: "trusttunnel",
|
||||
Source: M.ParseSocksaddr(request.RemoteAddr),
|
||||
Destination: M.ParseSocksaddr(request.Host).Unwrap(),
|
||||
|
||||
@@ -13,7 +13,7 @@ const (
|
||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||
)
|
||||
|
||||
func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
|
||||
func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int, profile string) {
|
||||
if cwnd == 0 {
|
||||
cwnd = 32
|
||||
}
|
||||
@@ -47,6 +47,7 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int) {
|
||||
congestionv2.NewBbrSender(
|
||||
congestionv2.GetInitialPacketSize(quicConn),
|
||||
c.ByteCount(cwnd),
|
||||
congestionv2.Profile(profile),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/component/dialer"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type PacketDialer interface {
|
||||
ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error)
|
||||
}
|
||||
|
||||
func DialQuic(ctx context.Context, address string, opts []dialer.Option, pDialer PacketDialer, tlsConf *tls.Config, conf *quic.Config, early bool) (net.PacketConn, *quic.Conn, error) {
|
||||
d := dialer.NewDialer(
|
||||
dialer.WithOptions(opts...),
|
||||
dialer.WithNetDialer(dialer.NetDialerFunc(func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
addrPort, err := netip.ParseAddrPort(address) // the dialer will resolve the domain to ip
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpAddr := net.UDPAddrFromAddrPort(addrPort)
|
||||
packetConn, err := pDialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := quic.Transport{Conn: packetConn}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
|
||||
var quicConn *quic.Conn
|
||||
if early {
|
||||
quicConn, err = transport.DialEarly(ctx, udpAddr, tlsConf, conf)
|
||||
} else {
|
||||
quicConn, err = transport.Dial(ctx, udpAddr, tlsConf, conf)
|
||||
}
|
||||
if err != nil {
|
||||
_ = packetConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return quicNetConn{Conn: quicConn, pc: packetConn}, nil
|
||||
})),
|
||||
)
|
||||
c, err := d.DialContext(ctx, "udp", address)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
nc := c.(quicNetConn)
|
||||
return nc.pc, nc.Conn, nil
|
||||
}
|
||||
|
||||
type quicNetConn struct {
|
||||
*quic.Conn
|
||||
pc net.PacketConn
|
||||
}
|
||||
|
||||
func (q quicNetConn) Close() error {
|
||||
err := q.Conn.CloseWithError(0, "")
|
||||
_ = q.pc.Close() // always close the packetConn
|
||||
return err
|
||||
}
|
||||
|
||||
func (q quicNetConn) Read(b []byte) (n int, err error) {
|
||||
panic("should not call Read on quicNetConn")
|
||||
}
|
||||
|
||||
func (q quicNetConn) Write(b []byte) (n int, err error) {
|
||||
panic("should not call Write on quicNetConn")
|
||||
}
|
||||
|
||||
func (q quicNetConn) SetDeadline(t time.Time) error {
|
||||
panic("should not call SetDeadline on quicNetConn")
|
||||
}
|
||||
|
||||
func (q quicNetConn) SetReadDeadline(t time.Time) error {
|
||||
panic("should not call SetReadDeadline on quicNetConn")
|
||||
}
|
||||
|
||||
func (q quicNetConn) SetWriteDeadline(t time.Time) error {
|
||||
panic("should not call SetWriteDeadline on quicNetConn")
|
||||
}
|
||||
|
||||
var _ net.Conn = quicNetConn{}
|
||||
@@ -27,16 +27,13 @@ const (
|
||||
|
||||
invalidPacketNumber = -1
|
||||
initialCongestionWindowPackets = 32
|
||||
minCongestionWindowPackets = 4
|
||||
|
||||
// Constants based on TCP defaults.
|
||||
// The minimum CWND to ensure delayed acks don't reduce bandwidth measurements.
|
||||
// Does not inflate the pacing rate.
|
||||
defaultMinimumCongestionWindow = 4 * congestion.ByteCount(congestion.InitialPacketSize)
|
||||
|
||||
// The gain used for the STARTUP, equal to 2/ln(2).
|
||||
defaultHighGain = 2.885
|
||||
// The newly derived gain for STARTUP, equal to 4 * ln(2)
|
||||
derivedHighGain = 2.773
|
||||
// The newly derived CWND gain for STARTUP, 2.
|
||||
derivedHighCWNDGain = 2.0
|
||||
)
|
||||
@@ -63,7 +60,6 @@ const (
|
||||
// Flag.
|
||||
defaultStartupFullLossCount = 8
|
||||
quicBbr2DefaultLossThreshold = 0.02
|
||||
maxBbrBurstPackets = 10
|
||||
)
|
||||
|
||||
type bbrMode int
|
||||
@@ -94,6 +90,63 @@ const (
|
||||
bbrRecoveryStateGrowth
|
||||
)
|
||||
|
||||
type Profile string
|
||||
|
||||
const (
|
||||
ProfileConservative Profile = "conservative"
|
||||
ProfileStandard Profile = "standard"
|
||||
ProfileAggressive Profile = "aggressive"
|
||||
)
|
||||
|
||||
type profileConfig struct {
|
||||
highGain float64
|
||||
highCwndGain float64
|
||||
congestionWindowGainConstant float64
|
||||
numStartupRtts int64
|
||||
drainToTarget bool
|
||||
detectOvershooting bool
|
||||
bytesLostMultiplier uint8
|
||||
enableAckAggregationStartup bool
|
||||
expireAckAggregationStartup bool
|
||||
enableOverestimateAvoidance bool
|
||||
reduceExtraAckedOnBandwidthIncrease bool
|
||||
}
|
||||
|
||||
func configForProfile(profile Profile) profileConfig {
|
||||
switch profile {
|
||||
case ProfileConservative:
|
||||
return profileConfig{
|
||||
highGain: 2.25,
|
||||
highCwndGain: 1.75,
|
||||
congestionWindowGainConstant: 1.75,
|
||||
numStartupRtts: 2,
|
||||
drainToTarget: true,
|
||||
detectOvershooting: true,
|
||||
bytesLostMultiplier: 1,
|
||||
enableOverestimateAvoidance: true,
|
||||
reduceExtraAckedOnBandwidthIncrease: true,
|
||||
}
|
||||
case ProfileAggressive:
|
||||
return profileConfig{
|
||||
highGain: 3.0,
|
||||
highCwndGain: 2.25,
|
||||
congestionWindowGainConstant: 2.5,
|
||||
numStartupRtts: 4,
|
||||
bytesLostMultiplier: 2,
|
||||
enableAckAggregationStartup: true,
|
||||
expireAckAggregationStartup: true,
|
||||
}
|
||||
default:
|
||||
return profileConfig{
|
||||
highGain: defaultHighGain,
|
||||
highCwndGain: derivedHighCWNDGain,
|
||||
congestionWindowGainConstant: 2.0,
|
||||
numStartupRtts: roundTripsWithoutGrowthBeforeExitingStartup,
|
||||
bytesLostMultiplier: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type bbrSender struct {
|
||||
rttStats congestion.RTTStatsProvider
|
||||
pacer *Pacer
|
||||
@@ -141,6 +194,9 @@ type bbrSender struct {
|
||||
// The smallest value the |congestion_window_| can achieve.
|
||||
minCongestionWindow congestion.ByteCount
|
||||
|
||||
// The BBR profile used by the sender.
|
||||
profile Profile
|
||||
|
||||
// The pacing gain applied during the STARTUP phase.
|
||||
highGain float64
|
||||
|
||||
@@ -245,11 +301,13 @@ var _ congestion.CongestionControl = &bbrSender{}
|
||||
func NewBbrSender(
|
||||
initialMaxDatagramSize congestion.ByteCount,
|
||||
initialCongestionWindowPackets congestion.ByteCount,
|
||||
profile Profile,
|
||||
) *bbrSender {
|
||||
return newBbrSender(
|
||||
initialMaxDatagramSize,
|
||||
initialCongestionWindowPackets*initialMaxDatagramSize,
|
||||
congestion.MaxCongestionWindowPackets*initialMaxDatagramSize,
|
||||
profile,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -257,6 +315,7 @@ func newBbrSender(
|
||||
initialMaxDatagramSize,
|
||||
initialCongestionWindow,
|
||||
initialMaxCongestionWindow congestion.ByteCount,
|
||||
profile Profile,
|
||||
) *bbrSender {
|
||||
b := &bbrSender{
|
||||
mode: bbrModeStartup,
|
||||
@@ -267,9 +326,10 @@ func newBbrSender(
|
||||
congestionWindow: initialCongestionWindow,
|
||||
initialCongestionWindow: initialCongestionWindow,
|
||||
maxCongestionWindow: initialMaxCongestionWindow,
|
||||
minCongestionWindow: defaultMinimumCongestionWindow,
|
||||
minCongestionWindow: minCongestionWindowForMaxDatagramSize(initialMaxDatagramSize),
|
||||
profile: ProfileStandard,
|
||||
highGain: defaultHighGain,
|
||||
highCwndGain: defaultHighGain,
|
||||
highCwndGain: derivedHighCWNDGain,
|
||||
drainGain: 1.0 / defaultHighGain,
|
||||
pacingGain: 1.0,
|
||||
congestionWindowGain: 1.0,
|
||||
@@ -284,20 +344,57 @@ func newBbrSender(
|
||||
maxDatagramSize: initialMaxDatagramSize,
|
||||
}
|
||||
b.pacer = NewPacer(b.bandwidthForPacer)
|
||||
|
||||
/*
|
||||
if b.tracer != nil {
|
||||
b.lastState = logging.CongestionStateStartup
|
||||
b.tracer.UpdatedCongestionState(logging.CongestionStateStartup)
|
||||
}
|
||||
*/
|
||||
b.applyProfile(profile)
|
||||
|
||||
b.enterStartupMode()
|
||||
b.setHighCwndGain(derivedHighCWNDGain)
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *bbrSender) applyProfile(profile Profile) {
|
||||
cfg := configForProfile(profile)
|
||||
b.profile = profile
|
||||
b.highGain = cfg.highGain
|
||||
b.highCwndGain = cfg.highCwndGain
|
||||
b.drainGain = 1.0 / cfg.highGain
|
||||
b.congestionWindowGainConstant = cfg.congestionWindowGainConstant
|
||||
b.numStartupRtts = cfg.numStartupRtts
|
||||
b.drainToTarget = cfg.drainToTarget
|
||||
b.detectOvershooting = cfg.detectOvershooting
|
||||
b.bytesLostMultiplierWhileDetectingOvershooting = cfg.bytesLostMultiplier
|
||||
b.enableAckAggregationDuringStartup = cfg.enableAckAggregationStartup
|
||||
b.expireAckAggregationInStartup = cfg.expireAckAggregationStartup
|
||||
if cfg.enableOverestimateAvoidance {
|
||||
b.sampler.EnableOverestimateAvoidance()
|
||||
}
|
||||
b.sampler.SetReduceExtraAckedOnBandwidthIncrease(cfg.reduceExtraAckedOnBandwidthIncrease)
|
||||
}
|
||||
|
||||
func minCongestionWindowForMaxDatagramSize(maxDatagramSize congestion.ByteCount) congestion.ByteCount {
|
||||
return minCongestionWindowPackets * maxDatagramSize
|
||||
}
|
||||
|
||||
func scaleByteWindowForDatagramSize(window, oldMaxDatagramSize, newMaxDatagramSize congestion.ByteCount) congestion.ByteCount {
|
||||
if oldMaxDatagramSize == newMaxDatagramSize {
|
||||
return window
|
||||
}
|
||||
return congestion.ByteCount(uint64(window) * uint64(newMaxDatagramSize) / uint64(oldMaxDatagramSize))
|
||||
}
|
||||
|
||||
func (b *bbrSender) rescalePacketSizedWindows(maxDatagramSize congestion.ByteCount) {
|
||||
oldMaxDatagramSize := b.maxDatagramSize
|
||||
b.maxDatagramSize = maxDatagramSize
|
||||
b.initialCongestionWindow = scaleByteWindowForDatagramSize(b.initialCongestionWindow, oldMaxDatagramSize, maxDatagramSize)
|
||||
b.maxCongestionWindow = scaleByteWindowForDatagramSize(b.maxCongestionWindow, oldMaxDatagramSize, maxDatagramSize)
|
||||
b.minCongestionWindow = minCongestionWindowForMaxDatagramSize(maxDatagramSize)
|
||||
b.cwndToCalculateMinPacingRate = scaleByteWindowForDatagramSize(b.cwndToCalculateMinPacingRate, oldMaxDatagramSize, maxDatagramSize)
|
||||
b.maxCongestionWindowWithNetworkParametersAdjusted = scaleByteWindowForDatagramSize(
|
||||
b.maxCongestionWindowWithNetworkParametersAdjusted,
|
||||
oldMaxDatagramSize,
|
||||
maxDatagramSize,
|
||||
)
|
||||
}
|
||||
|
||||
func (b *bbrSender) SetRTTStatsProvider(provider congestion.RTTStatsProvider) {
|
||||
b.rttStats = provider
|
||||
}
|
||||
@@ -330,8 +427,6 @@ func (b *bbrSender) OnPacketSent(
|
||||
}
|
||||
|
||||
b.sampler.OnPacketSent(sentTime, packetNumber, bytes, bytesInFlight, isRetransmittable)
|
||||
|
||||
b.maybeAppLimited(bytesInFlight)
|
||||
}
|
||||
|
||||
// CanSend implements the SendAlgorithm interface.
|
||||
@@ -364,11 +459,18 @@ func (b *bbrSender) SetMaxDatagramSize(s congestion.ByteCount) {
|
||||
if s < b.maxDatagramSize {
|
||||
panic(fmt.Sprintf("congestion BUG: decreased max datagram size from %d to %d", b.maxDatagramSize, s))
|
||||
}
|
||||
cwndIsMinCwnd := b.congestionWindow == b.minCongestionWindow
|
||||
b.maxDatagramSize = s
|
||||
if cwndIsMinCwnd {
|
||||
oldMinCongestionWindow := b.minCongestionWindow
|
||||
oldInitialCongestionWindow := b.initialCongestionWindow
|
||||
b.rescalePacketSizedWindows(s)
|
||||
switch b.congestionWindow {
|
||||
case oldMinCongestionWindow:
|
||||
b.congestionWindow = b.minCongestionWindow
|
||||
case oldInitialCongestionWindow:
|
||||
b.congestionWindow = b.initialCongestionWindow
|
||||
default:
|
||||
b.congestionWindow = Min(b.maxCongestionWindow, Max(b.congestionWindow, b.minCongestionWindow))
|
||||
}
|
||||
b.recoveryWindow = Min(b.maxCongestionWindow, Max(b.recoveryWindow, b.minCongestionWindow))
|
||||
b.pacer.SetMaxDatagramSize(s)
|
||||
}
|
||||
|
||||
@@ -411,6 +513,8 @@ func (b *bbrSender) OnCongestionEventEx(priorInFlight congestion.ByteCount, even
|
||||
// packet in lost_packets.
|
||||
var lastPacketSendState sendTimeState
|
||||
|
||||
b.maybeAppLimited(priorInFlight)
|
||||
|
||||
// Update bytesInFlight
|
||||
b.bytesInFlight = priorInFlight
|
||||
for _, p := range ackedPackets {
|
||||
@@ -508,22 +612,6 @@ func (b *bbrSender) PacingRate() Bandwidth {
|
||||
return b.pacingRate
|
||||
}
|
||||
|
||||
func (b *bbrSender) hasGoodBandwidthEstimateForResumption() bool {
|
||||
return b.hasNonAppLimitedSample()
|
||||
}
|
||||
|
||||
func (b *bbrSender) hasNonAppLimitedSample() bool {
|
||||
return b.hasNoAppLimitedSample
|
||||
}
|
||||
|
||||
// Sets the pacing gain used in STARTUP. Must be greater than 1.
|
||||
func (b *bbrSender) setHighGain(highGain float64) {
|
||||
b.highGain = highGain
|
||||
if b.mode == bbrModeStartup {
|
||||
b.pacingGain = highGain
|
||||
}
|
||||
}
|
||||
|
||||
// Sets the CWND gain used in STARTUP. Must be greater than 1.
|
||||
func (b *bbrSender) setHighCwndGain(highCwndGain float64) {
|
||||
b.highCwndGain = highCwndGain
|
||||
@@ -532,11 +620,6 @@ func (b *bbrSender) setHighCwndGain(highCwndGain float64) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sets the gain used in DRAIN. Must be less than 1.
|
||||
func (b *bbrSender) setDrainGain(drainGain float64) {
|
||||
b.drainGain = drainGain
|
||||
}
|
||||
|
||||
// Get the current bandwidth estimate. Note that Bandwidth is in bits per second.
|
||||
func (b *bbrSender) bandwidthEstimate() Bandwidth {
|
||||
return b.maxBandwidth.GetBest()
|
||||
@@ -697,12 +780,7 @@ func (b *bbrSender) checkIfFullBandwidthReached(lastPacketSendState *sendTimeSta
|
||||
}
|
||||
|
||||
func (b *bbrSender) maybeAppLimited(bytesInFlight congestion.ByteCount) {
|
||||
congestionWindow := b.GetCongestionWindow()
|
||||
if bytesInFlight >= congestionWindow {
|
||||
return
|
||||
}
|
||||
availableBytes := congestionWindow - bytesInFlight
|
||||
if availableBytes > maxBbrBurstPackets*b.maxDatagramSize {
|
||||
if bytesInFlight < b.getTargetCongestionWindow(1) {
|
||||
b.sampler.OnAppLimited()
|
||||
}
|
||||
}
|
||||
@@ -729,7 +807,7 @@ func (b *bbrSender) maybeEnterOrExitProbeRtt(now monotime.Time, isRoundStart, mi
|
||||
b.pacingGain = 1.0
|
||||
// Do not decide on the time to exit PROBE_RTT until the |bytes_in_flight|
|
||||
// is at the target small value.
|
||||
b.exitProbeRttAt = monotime.Time(0)
|
||||
b.exitProbeRttAt = 0
|
||||
}
|
||||
|
||||
if b.mode == bbrModeProbeRtt {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package congestion
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/quic-go/congestion"
|
||||
@@ -9,7 +8,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
maxBurstPackets = 10
|
||||
maxBurstPackets = 10
|
||||
maxBurstPacingDelayMultiplier = 4
|
||||
)
|
||||
|
||||
// Pacer implements a token bucket pacing algorithm.
|
||||
@@ -52,22 +52,27 @@ func (p *Pacer) Budget(now monotime.Time) congestion.ByteCount {
|
||||
|
||||
func (p *Pacer) maxBurstSize() congestion.ByteCount {
|
||||
return Max(
|
||||
congestion.ByteCount((congestion.MinPacingDelay+time.Millisecond).Nanoseconds())*p.getBandwidth()/1e9,
|
||||
congestion.ByteCount((maxBurstPacingDelayMultiplier*congestion.MinPacingDelay).Nanoseconds())*p.getBandwidth()/1e9,
|
||||
maxBurstPackets*p.maxDatagramSize,
|
||||
)
|
||||
}
|
||||
|
||||
// TimeUntilSend returns when the next packet should be sent.
|
||||
// It returns the zero value of monotime.Time if a packet can be sent immediately.
|
||||
// It returns the zero value if a packet can be sent immediately.
|
||||
func (p *Pacer) TimeUntilSend() monotime.Time {
|
||||
if p.budgetAtLastSent >= p.maxDatagramSize {
|
||||
return monotime.Time(0)
|
||||
return 0
|
||||
}
|
||||
return p.lastSentTime.Add(Max(
|
||||
congestion.MinPacingDelay,
|
||||
time.Duration(math.Ceil(float64(p.maxDatagramSize-p.budgetAtLastSent)*1e9/
|
||||
float64(p.getBandwidth())))*time.Nanosecond,
|
||||
))
|
||||
diff := 1e9 * uint64(p.maxDatagramSize-p.budgetAtLastSent)
|
||||
bw := uint64(p.getBandwidth())
|
||||
// We might need to round up this value.
|
||||
// Otherwise, we might have a budget (slightly) smaller than the datagram size when the timer expires.
|
||||
d := diff / bw
|
||||
// this is effectively a math.Ceil, but using only integer math
|
||||
if diff%bw > 0 {
|
||||
d++
|
||||
}
|
||||
return p.lastSentTime.Add(Max(congestion.MinPacingDelay, time.Duration(d)*time.Nanosecond))
|
||||
}
|
||||
|
||||
func (p *Pacer) SetMaxDatagramSize(s congestion.ByteCount) {
|
||||
|
||||
@@ -152,7 +152,7 @@ func (p *packetNumberIndexedQueue[T]) EntrySlotsUsed() int {
|
||||
return p.entries.Len()
|
||||
}
|
||||
|
||||
// LastPacket returns packet number of the first entry in the queue.
|
||||
// FirstPacket returns packet number of the first entry in the queue.
|
||||
func (p *packetNumberIndexedQueue[T]) FirstPacket() (packetNumber congestion.PacketNumber) {
|
||||
return p.firstPacket
|
||||
}
|
||||
|
||||
@@ -4,16 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
|
||||
list "github.com/bahlo/generic-list-go"
|
||||
)
|
||||
@@ -22,7 +17,7 @@ type PoolClient struct {
|
||||
newClientOptionV4 *ClientOptionV4
|
||||
newClientOptionV5 *ClientOptionV5
|
||||
|
||||
dialHelper *poolDialHelper
|
||||
dialFn DialFunc
|
||||
tcpClients list.List[Client]
|
||||
tcpClientsMutex sync.Mutex
|
||||
udpClients list.List[Client]
|
||||
@@ -51,47 +46,6 @@ func (t *PoolClient) ListenPacket(ctx context.Context, metadata *C.Metadata) (ne
|
||||
return N.NewRefPacketConn(pc, t), nil
|
||||
}
|
||||
|
||||
// poolDialHelper is a helper for dialFn
|
||||
// using a standalone struct to let finalizer working
|
||||
type poolDialHelper struct {
|
||||
dialFn DialFunc
|
||||
dialResult atomic.Pointer[dialResult]
|
||||
}
|
||||
|
||||
type dialResult struct {
|
||||
transport *quic.Transport
|
||||
addr net.Addr
|
||||
}
|
||||
|
||||
func (t *poolDialHelper) dial(ctx context.Context) (transport *quic.Transport, addr net.Addr, err error) {
|
||||
if dr := t.dialResult.Load(); dr != nil {
|
||||
return dr.transport, dr.addr, nil
|
||||
}
|
||||
|
||||
transport, addr, err = t.dialFn(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if _, ok := transport.Conn.(*net.UDPConn); ok { // only cache the system's UDPConn
|
||||
transport.SetSingleUse(false) // don't close transport in each dial
|
||||
|
||||
dr := &dialResult{transport: transport, addr: addr}
|
||||
t.dialResult.Store(dr)
|
||||
}
|
||||
|
||||
return transport, addr, err
|
||||
}
|
||||
|
||||
func (t *poolDialHelper) forceClose() {
|
||||
if dr := t.dialResult.Swap(nil); dr != nil {
|
||||
transport := dr.transport
|
||||
if transport != nil {
|
||||
_ = transport.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *PoolClient) newClient(udp bool) (client Client) {
|
||||
clients := &t.tcpClients
|
||||
clientsMutex := &t.tcpClientsMutex
|
||||
@@ -103,11 +57,10 @@ func (t *PoolClient) newClient(udp bool) (client Client) {
|
||||
clientsMutex.Lock()
|
||||
defer clientsMutex.Unlock()
|
||||
|
||||
dialHelper := t.dialHelper
|
||||
if t.newClientOptionV4 != nil {
|
||||
client = NewClientV4(t.newClientOptionV4, udp, dialHelper.dial)
|
||||
client = NewClientV4(t.newClientOptionV4, udp, t.dialFn)
|
||||
} else {
|
||||
client = NewClientV5(t.newClientOptionV5, udp, dialHelper.dial)
|
||||
client = NewClientV5(t.newClientOptionV5, udp, t.dialFn)
|
||||
}
|
||||
|
||||
client.SetLastVisited(time.Now())
|
||||
@@ -168,27 +121,18 @@ func (t *PoolClient) getClient(udp bool) Client {
|
||||
|
||||
func NewPoolClientV4(clientOption *ClientOptionV4, dialFn DialFunc) *PoolClient {
|
||||
p := &PoolClient{
|
||||
dialHelper: &poolDialHelper{dialFn: dialFn},
|
||||
dialFn: dialFn,
|
||||
}
|
||||
newClientOption := *clientOption
|
||||
p.newClientOptionV4 = &newClientOption
|
||||
runtime.SetFinalizer(p, closeClientPool)
|
||||
log.Debugln("New TuicV4 PoolClient at %p", p)
|
||||
return p
|
||||
}
|
||||
|
||||
func NewPoolClientV5(clientOption *ClientOptionV5, dialFn DialFunc) *PoolClient {
|
||||
p := &PoolClient{
|
||||
dialHelper: &poolDialHelper{dialFn: dialFn},
|
||||
dialFn: dialFn,
|
||||
}
|
||||
newClientOption := *clientOption
|
||||
p.newClientOptionV5 = &newClientOption
|
||||
runtime.SetFinalizer(p, closeClientPool)
|
||||
log.Debugln("New TuicV5 PoolClient at %p", p)
|
||||
return p
|
||||
}
|
||||
|
||||
func closeClientPool(client *PoolClient) {
|
||||
log.Debugln("Close Tuic PoolClient at %p", client)
|
||||
client.dialHelper.forceClose()
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/socks5"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
v4 "github.com/metacubex/mihomo/transport/tuic/v4"
|
||||
v5 "github.com/metacubex/mihomo/transport/tuic/v5"
|
||||
|
||||
@@ -32,6 +33,7 @@ type ServerOption struct {
|
||||
AuthenticationTimeout time.Duration
|
||||
MaxUdpRelayPacketSize int
|
||||
CWND int
|
||||
BBRProfile string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
@@ -47,7 +49,7 @@ func (s *Server) Serve() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
common.SetCongestionController(conn, s.CongestionController, s.CWND)
|
||||
common.SetCongestionController(conn, s.CongestionController, s.CWND, s.BBRProfile)
|
||||
h := &serverHandler{
|
||||
Server: s,
|
||||
quicConn: conn,
|
||||
@@ -72,8 +74,8 @@ type serverHandler struct {
|
||||
quicConn *quic.Conn
|
||||
uuid uuid.UUID
|
||||
|
||||
v4Handler common.ServerHandler
|
||||
v5Handler common.ServerHandler
|
||||
v4Handler types.ServerHandler
|
||||
v5Handler types.ServerHandler
|
||||
}
|
||||
|
||||
func (s *serverHandler) handle() {
|
||||
@@ -148,7 +150,7 @@ func (s *serverHandler) handleStream() (err error) {
|
||||
return err
|
||||
}
|
||||
go func() (err error) {
|
||||
stream := common.NewQuicStreamConn(
|
||||
stream := types.NewQuicStreamConn(
|
||||
quicStream,
|
||||
s.quicConn.LocalAddr(),
|
||||
s.quicConn.RemoteAddr(),
|
||||
|
||||
@@ -2,6 +2,7 @@ package tuic
|
||||
|
||||
import (
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
v4 "github.com/metacubex/mihomo/transport/tuic/v4"
|
||||
v5 "github.com/metacubex/mihomo/transport/tuic/v5"
|
||||
)
|
||||
@@ -9,7 +10,7 @@ import (
|
||||
type ClientOptionV4 = v4.ClientOption
|
||||
type ClientOptionV5 = v5.ClientOption
|
||||
|
||||
type Client = common.Client
|
||||
type Client = types.Client
|
||||
|
||||
func NewClientV4(clientOption *ClientOptionV4, udp bool, dialFn DialFunc) Client {
|
||||
return v4.NewClient(clientOption, udp, dialFn)
|
||||
@@ -19,9 +20,9 @@ func NewClientV5(clientOption *ClientOptionV5, udp bool, dialFn DialFunc) Client
|
||||
return v5.NewClient(clientOption, udp, dialFn)
|
||||
}
|
||||
|
||||
type DialFunc = common.DialFunc
|
||||
type DialFunc = types.DialFunc
|
||||
|
||||
var TooManyOpenStreams = common.TooManyOpenStreams
|
||||
var TooManyOpenStreams = types.TooManyOpenStreams
|
||||
|
||||
const DefaultStreamReceiveWindow = common.DefaultStreamReceiveWindow
|
||||
const DefaultConnectionReceiveWindow = common.DefaultConnectionReceiveWindow
|
||||
@@ -31,9 +32,9 @@ var PacketOverHeadV4 = v4.PacketOverHead
|
||||
var PacketOverHeadV5 = v5.PacketOverHead
|
||||
var MaxFragSizeV5 = v5.MaxFragSize
|
||||
|
||||
type UdpRelayMode = common.UdpRelayMode
|
||||
type UdpRelayMode = types.UdpRelayMode
|
||||
|
||||
const (
|
||||
QUIC = common.QUIC
|
||||
NATIVE = common.NATIVE
|
||||
QUIC = types.QUIC
|
||||
NATIVE = types.NATIVE
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
package common
|
||||
package types
|
||||
|
||||
import (
|
||||
"net"
|
||||
@@ -1,4 +1,4 @@
|
||||
package common
|
||||
package types
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@@ -18,7 +18,7 @@ var (
|
||||
TooManyOpenStreams = errors.New("tuic: too many open streams")
|
||||
)
|
||||
|
||||
type DialFunc func(ctx context.Context) (transport *quic.Transport, addr net.Addr, err error)
|
||||
type DialFunc func(ctx context.Context) (quicConn *quic.Conn, err error)
|
||||
|
||||
type Client interface {
|
||||
DialContext(ctx context.Context, metadata *C.Metadata) (net.Conn, error)
|
||||
+15
-32
@@ -17,30 +17,24 @@ import (
|
||||
"github.com/metacubex/mihomo/common/xsync"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/randv2"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type ClientOption struct {
|
||||
TlsConfig *tls.Config
|
||||
QuicConfig *quic.Config
|
||||
Token [32]byte
|
||||
UdpRelayMode common.UdpRelayMode
|
||||
CongestionController string
|
||||
ReduceRtt bool
|
||||
UdpRelayMode types.UdpRelayMode
|
||||
RequestTimeout time.Duration
|
||||
MaxUdpRelayPacketSize int
|
||||
FastOpen bool
|
||||
MaxOpenStreams int64
|
||||
CWND int
|
||||
}
|
||||
|
||||
type clientImpl struct {
|
||||
*ClientOption
|
||||
dialFn common.DialFunc
|
||||
dialFn types.DialFunc
|
||||
udp bool
|
||||
|
||||
quicConn *quic.Conn
|
||||
@@ -73,21 +67,10 @@ func (t *clientImpl) getQuicConn(ctx context.Context) (*quic.Conn, error) {
|
||||
if t.quicConn != nil {
|
||||
return t.quicConn, nil
|
||||
}
|
||||
transport, addr, err := t.dialFn(ctx)
|
||||
quicConn, err := t.dialFn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var quicConn *quic.Conn
|
||||
if t.ReduceRtt {
|
||||
quicConn, err = transport.DialEarly(ctx, addr, t.TlsConfig, t.QuicConfig)
|
||||
} else {
|
||||
quicConn, err = transport.Dial(ctx, addr, t.TlsConfig, t.QuicConfig)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
common.SetCongestionController(quicConn, t.CongestionController, t.CWND)
|
||||
|
||||
go func() {
|
||||
_ = t.sendAuthentication(quicConn)
|
||||
@@ -96,7 +79,7 @@ func (t *clientImpl) getQuicConn(ctx context.Context) (*quic.Conn, error) {
|
||||
if t.udp {
|
||||
go func() {
|
||||
switch t.UdpRelayMode {
|
||||
case common.QUIC:
|
||||
case types.QUIC:
|
||||
_ = t.handleUniStream(quicConn)
|
||||
default: // native
|
||||
_ = t.handleMessage(quicConn)
|
||||
@@ -169,7 +152,7 @@ func (t *clientImpl) handleUniStream(quicConn *quic.Conn) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if t.udp && t.UdpRelayMode == common.QUIC {
|
||||
if t.udp && t.UdpRelayMode == types.QUIC {
|
||||
assocId = packet.ASSOC_ID
|
||||
if val, ok := t.udpInputMap.Load(assocId); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
@@ -219,7 +202,7 @@ func (t *clientImpl) handleMessage(quicConn *quic.Conn) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if t.udp && t.UdpRelayMode == common.NATIVE {
|
||||
if t.udp && t.UdpRelayMode == types.NATIVE {
|
||||
assocId = packet.ASSOC_ID
|
||||
if val, ok := t.udpInputMap.Load(assocId); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
@@ -270,7 +253,7 @@ func (t *clientImpl) forceClose(quicConn *quic.Conn, err error) {
|
||||
func (t *clientImpl) Close() {
|
||||
t.closed.Store(true)
|
||||
if t.openStreams.Load() == 0 {
|
||||
t.forceClose(nil, common.ClientClosed)
|
||||
t.forceClose(nil, types.ClientClosed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +265,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
openStreams := t.openStreams.Add(1)
|
||||
if openStreams >= t.MaxOpenStreams {
|
||||
t.openStreams.Add(-1)
|
||||
return nil, common.TooManyOpenStreams
|
||||
return nil, types.TooManyOpenStreams
|
||||
}
|
||||
stream, err := func() (stream net.Conn, err error) {
|
||||
defer func() {
|
||||
@@ -298,7 +281,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stream = common.NewQuicStreamConn(
|
||||
stream = types.NewQuicStreamConn(
|
||||
quicStream,
|
||||
quicConn.LocalAddr(),
|
||||
quicConn.RemoteAddr(),
|
||||
@@ -306,7 +289,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
time.AfterFunc(C.DefaultTCPTimeout, func() {
|
||||
openStreams := t.openStreams.Add(-1)
|
||||
if openStreams == 0 && t.closed.Load() {
|
||||
t.forceClose(quicConn, common.ClientClosed)
|
||||
t.forceClose(quicConn, types.ClientClosed)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -357,7 +340,7 @@ func (t *clientImpl) ListenPacket(ctx context.Context, metadata *C.Metadata) (ne
|
||||
openStreams := t.openStreams.Add(1)
|
||||
if openStreams >= t.MaxOpenStreams {
|
||||
t.openStreams.Add(-1)
|
||||
return nil, common.TooManyOpenStreams
|
||||
return nil, types.TooManyOpenStreams
|
||||
}
|
||||
|
||||
pipe1, pipe2 := N.Pipe()
|
||||
@@ -381,7 +364,7 @@ func (t *clientImpl) ListenPacket(ctx context.Context, metadata *C.Metadata) (ne
|
||||
time.AfterFunc(C.DefaultUDPTimeout, func() {
|
||||
openStreams := t.openStreams.Add(-1)
|
||||
if openStreams == 0 && t.closed.Load() {
|
||||
t.forceClose(quicConn, common.ClientClosed)
|
||||
t.forceClose(quicConn, types.ClientClosed)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -410,10 +393,10 @@ func (t *Client) ListenPacket(ctx context.Context, metadata *C.Metadata) (net.Pa
|
||||
}
|
||||
|
||||
func (t *Client) forceClose() {
|
||||
t.clientImpl.forceClose(nil, common.ClientClosed)
|
||||
t.clientImpl.forceClose(nil, types.ClientClosed)
|
||||
}
|
||||
|
||||
func NewClient(clientOption *ClientOption, udp bool, dialFn common.DialFunc) *Client {
|
||||
func NewClient(clientOption *ClientOption, udp bool, dialFn types.DialFunc) *Client {
|
||||
ci := &clientImpl{
|
||||
ClientOption: clientOption,
|
||||
dialFn: dialFn,
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
)
|
||||
@@ -18,7 +18,7 @@ type quicStreamPacketConn struct {
|
||||
quicConn *quic.Conn
|
||||
inputConn *N.BufferedConn
|
||||
|
||||
udpRelayMode common.UdpRelayMode
|
||||
udpRelayMode types.UdpRelayMode
|
||||
maxUdpRelayPacketSize int
|
||||
|
||||
deferQuicConnFn func(quicConn *quic.Conn, err error)
|
||||
@@ -122,7 +122,7 @@ func (q *quicStreamPacketConn) WaitReadFrom() (data []byte, put func(), addr net
|
||||
}
|
||||
|
||||
func (q *quicStreamPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
if q.udpRelayMode != common.QUIC && len(p) > q.maxUdpRelayPacketSize {
|
||||
if q.udpRelayMode != types.QUIC && len(p) > q.maxUdpRelayPacketSize {
|
||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(q.maxUdpRelayPacketSize)}
|
||||
}
|
||||
if q.closed {
|
||||
@@ -148,7 +148,7 @@ func (q *quicStreamPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err erro
|
||||
return
|
||||
}
|
||||
switch q.udpRelayMode {
|
||||
case common.QUIC:
|
||||
case types.QUIC:
|
||||
var stream *quic.SendStream
|
||||
stream, err = q.quicConn.OpenUniStream()
|
||||
if err != nil {
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/xsync"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/socks5"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/metacubex/quic-go"
|
||||
@@ -28,7 +28,7 @@ type ServerOption struct {
|
||||
MaxUdpRelayPacketSize int
|
||||
}
|
||||
|
||||
func NewServerHandler(option *ServerOption, quicConn *quic.Conn, uuid uuid.UUID) common.ServerHandler {
|
||||
func NewServerHandler(option *ServerOption, quicConn *quic.Conn, uuid uuid.UUID) types.ServerHandler {
|
||||
return &serverHandler{
|
||||
ServerOption: option,
|
||||
quicConn: quicConn,
|
||||
@@ -67,10 +67,10 @@ func (s *serverHandler) HandleMessage(message []byte) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return s.parsePacket(&packet, common.NATIVE)
|
||||
return s.parsePacket(&packet, types.NATIVE)
|
||||
}
|
||||
|
||||
func (s *serverHandler) parsePacket(packet *Packet, udpRelayMode common.UdpRelayMode) (err error) {
|
||||
func (s *serverHandler) parsePacket(packet *Packet, udpRelayMode types.UdpRelayMode) (err error) {
|
||||
<-s.authCh
|
||||
if !s.authOk.Load() {
|
||||
return
|
||||
@@ -166,7 +166,7 @@ func (s *serverHandler) HandleUniStream(reader *bufio.Reader) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return s.parsePacket(&packet, common.QUIC)
|
||||
return s.parsePacket(&packet, types.QUIC)
|
||||
case DissociateType:
|
||||
var disassociate Dissociate
|
||||
disassociate, err = ReadDissociateWithHead(commandHead, reader)
|
||||
|
||||
+15
-32
@@ -17,29 +17,23 @@ import (
|
||||
"github.com/metacubex/mihomo/common/xsync"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/randv2"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
type ClientOption struct {
|
||||
TlsConfig *tls.Config
|
||||
QuicConfig *quic.Config
|
||||
Uuid [16]byte
|
||||
Password string
|
||||
UdpRelayMode common.UdpRelayMode
|
||||
CongestionController string
|
||||
ReduceRtt bool
|
||||
UdpRelayMode types.UdpRelayMode
|
||||
MaxUdpRelayPacketSize int
|
||||
MaxOpenStreams int64
|
||||
CWND int
|
||||
}
|
||||
|
||||
type clientImpl struct {
|
||||
*ClientOption
|
||||
dialFn common.DialFunc
|
||||
dialFn types.DialFunc
|
||||
udp bool
|
||||
|
||||
quicConn *quic.Conn
|
||||
@@ -72,27 +66,16 @@ func (t *clientImpl) getQuicConn(ctx context.Context) (*quic.Conn, error) {
|
||||
if t.quicConn != nil {
|
||||
return t.quicConn, nil
|
||||
}
|
||||
transport, addr, err := t.dialFn(ctx)
|
||||
quicConn, err := t.dialFn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var quicConn *quic.Conn
|
||||
if t.ReduceRtt {
|
||||
quicConn, err = transport.DialEarly(ctx, addr, t.TlsConfig, t.QuicConfig)
|
||||
} else {
|
||||
quicConn, err = transport.Dial(ctx, addr, t.TlsConfig, t.QuicConfig)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
common.SetCongestionController(quicConn, t.CongestionController, t.CWND)
|
||||
|
||||
go func() {
|
||||
_ = t.sendAuthentication(quicConn)
|
||||
}()
|
||||
|
||||
if t.udp && t.UdpRelayMode == common.QUIC {
|
||||
if t.udp && t.UdpRelayMode == types.QUIC {
|
||||
go func() {
|
||||
_ = t.handleUniStream(quicConn)
|
||||
}()
|
||||
@@ -170,7 +153,7 @@ func (t *clientImpl) handleUniStream(quicConn *quic.Conn) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if t.udp && t.UdpRelayMode == common.QUIC {
|
||||
if t.udp && t.UdpRelayMode == types.QUIC {
|
||||
assocId = packet.ASSOC_ID
|
||||
if val, ok := t.udpInputMap.Load(assocId); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
@@ -220,7 +203,7 @@ func (t *clientImpl) handleMessage(quicConn *quic.Conn) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if t.udp && t.UdpRelayMode == common.NATIVE {
|
||||
if t.udp && t.UdpRelayMode == types.NATIVE {
|
||||
assocId = packet.ASSOC_ID
|
||||
if val, ok := t.udpInputMap.Load(assocId); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
@@ -278,7 +261,7 @@ func (t *clientImpl) forceClose(quicConn *quic.Conn, err error) {
|
||||
func (t *clientImpl) Close() {
|
||||
t.closed.Store(true)
|
||||
if t.openStreams.Load() == 0 {
|
||||
t.forceClose(nil, common.ClientClosed)
|
||||
t.forceClose(nil, types.ClientClosed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +273,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
openStreams := t.openStreams.Add(1)
|
||||
if openStreams >= t.MaxOpenStreams {
|
||||
t.openStreams.Add(-1)
|
||||
return nil, common.TooManyOpenStreams
|
||||
return nil, types.TooManyOpenStreams
|
||||
}
|
||||
stream, err := func() (stream net.Conn, err error) {
|
||||
defer func() {
|
||||
@@ -306,7 +289,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stream = common.NewQuicStreamConn(
|
||||
stream = types.NewQuicStreamConn(
|
||||
quicStream,
|
||||
quicConn.LocalAddr(),
|
||||
quicConn.RemoteAddr(),
|
||||
@@ -314,7 +297,7 @@ func (t *clientImpl) DialContext(ctx context.Context, metadata *C.Metadata) (net
|
||||
time.AfterFunc(C.DefaultTCPTimeout, func() {
|
||||
openStreams := t.openStreams.Add(-1)
|
||||
if openStreams == 0 && t.closed.Load() {
|
||||
t.forceClose(quicConn, common.ClientClosed)
|
||||
t.forceClose(quicConn, types.ClientClosed)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -341,7 +324,7 @@ func (t *clientImpl) ListenPacket(ctx context.Context, metadata *C.Metadata) (ne
|
||||
openStreams := t.openStreams.Add(1)
|
||||
if openStreams >= t.MaxOpenStreams {
|
||||
t.openStreams.Add(-1)
|
||||
return nil, common.TooManyOpenStreams
|
||||
return nil, types.TooManyOpenStreams
|
||||
}
|
||||
|
||||
pipe1, pipe2 := N.Pipe()
|
||||
@@ -365,7 +348,7 @@ func (t *clientImpl) ListenPacket(ctx context.Context, metadata *C.Metadata) (ne
|
||||
time.AfterFunc(C.DefaultUDPTimeout, func() {
|
||||
openStreams := t.openStreams.Add(-1)
|
||||
if openStreams == 0 && t.closed.Load() {
|
||||
t.forceClose(quicConn, common.ClientClosed)
|
||||
t.forceClose(quicConn, types.ClientClosed)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -394,10 +377,10 @@ func (t *Client) ListenPacket(ctx context.Context, metadata *C.Metadata) (net.Pa
|
||||
}
|
||||
|
||||
func (t *Client) forceClose() {
|
||||
t.clientImpl.forceClose(nil, common.ClientClosed)
|
||||
t.clientImpl.forceClose(nil, types.ClientClosed)
|
||||
}
|
||||
|
||||
func NewClient(clientOption *ClientOption, udp bool, dialFn common.DialFunc) *Client {
|
||||
func NewClient(clientOption *ClientOption, udp bool, dialFn types.DialFunc) *Client {
|
||||
ci := &clientImpl{
|
||||
ClientOption: clientOption,
|
||||
dialFn: dialFn,
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/atomic"
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
"github.com/metacubex/mihomo/common/pool"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/randv2"
|
||||
@@ -20,7 +20,7 @@ type quicStreamPacketConn struct {
|
||||
quicConn *quic.Conn
|
||||
inputConn *N.BufferedConn
|
||||
|
||||
udpRelayMode common.UdpRelayMode
|
||||
udpRelayMode types.UdpRelayMode
|
||||
maxUdpRelayPacketSize int
|
||||
|
||||
deferQuicConnFn func(quicConn *quic.Conn, err error)
|
||||
@@ -160,7 +160,7 @@ func (q *quicStreamPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err erro
|
||||
pktId := uint16(randv2.Uint32())
|
||||
packet := NewPacket(q.connId, pktId, 1, 0, uint16(len(p)), address, p)
|
||||
switch q.udpRelayMode {
|
||||
case common.QUIC:
|
||||
case types.QUIC:
|
||||
err = packet.WriteTo(buf)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/xsync"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/transport/socks5"
|
||||
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||
"github.com/metacubex/mihomo/transport/tuic/types"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/metacubex/quic-go"
|
||||
@@ -27,7 +27,7 @@ type ServerOption struct {
|
||||
MaxUdpRelayPacketSize int
|
||||
}
|
||||
|
||||
func NewServerHandler(option *ServerOption, quicConn *quic.Conn, uuid uuid.UUID) common.ServerHandler {
|
||||
func NewServerHandler(option *ServerOption, quicConn *quic.Conn, uuid uuid.UUID) types.ServerHandler {
|
||||
return &serverHandler{
|
||||
ServerOption: option,
|
||||
quicConn: quicConn,
|
||||
@@ -74,7 +74,7 @@ func (s *serverHandler) HandleMessage(message []byte) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return s.parsePacket(&packet, common.NATIVE)
|
||||
return s.parsePacket(&packet, types.NATIVE)
|
||||
case HeartbeatType:
|
||||
var heartbeat Heartbeat
|
||||
heartbeat, err = ReadHeartbeatWithHead(commandHead, reader)
|
||||
@@ -86,7 +86,7 @@ func (s *serverHandler) HandleMessage(message []byte) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *serverHandler) parsePacket(packet *Packet, udpRelayMode common.UdpRelayMode) (err error) {
|
||||
func (s *serverHandler) parsePacket(packet *Packet, udpRelayMode types.UdpRelayMode) (err error) {
|
||||
<-s.authCh
|
||||
if !s.authOk.Load() {
|
||||
return
|
||||
@@ -179,7 +179,7 @@ func (s *serverHandler) HandleUniStream(reader *bufio.Reader) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return s.parsePacket(&packet, common.QUIC)
|
||||
return s.parsePacket(&packet, types.QUIC)
|
||||
case DissociateType:
|
||||
var disassociate Dissociate
|
||||
disassociate, err = ReadDissociateWithHead(commandHead, reader)
|
||||
|
||||
@@ -3,11 +3,10 @@ package vmess
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/textproto"
|
||||
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"net/url"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/randv2"
|
||||
@@ -64,10 +63,12 @@ func (hc *httpConn) Write(b []byte) (int, error) {
|
||||
host = header[randv2.IntN(len(header))]
|
||||
}
|
||||
|
||||
u := fmt.Sprintf("http://%s%s", net.JoinHostPort(host, "80"), path)
|
||||
req, err := http.NewRequest(utils.EmptyOr(hc.cfg.Method, http.MethodGet), u, bytes.NewBuffer(b))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
req := http.Request{
|
||||
Method: hc.cfg.Method, // default is GET
|
||||
Host: host,
|
||||
URL: &url.URL{Scheme: "http", Host: host, Path: path},
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(bytes.NewReader(b)),
|
||||
}
|
||||
for key, list := range hc.cfg.Headers {
|
||||
req.Header.Set(key, list[randv2.IntN(len(list))])
|
||||
|
||||
@@ -39,10 +39,9 @@ type websocketConn struct {
|
||||
}
|
||||
|
||||
type websocketWithEarlyDataConn struct {
|
||||
net.Conn
|
||||
wsWriter N.ExtendedWriter
|
||||
conn N.ExtendedConn
|
||||
underlay net.Conn
|
||||
dialed chan bool
|
||||
dialed chan struct{}
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
config *WebsocketConfig
|
||||
@@ -174,7 +173,7 @@ func (wsc *websocketConn) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Dial(earlyData []byte) error {
|
||||
func (wsedc *websocketWithEarlyDataConn) dial(earlyData []byte) error {
|
||||
base64DataBuf := &bytes.Buffer{}
|
||||
base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, base64DataBuf)
|
||||
|
||||
@@ -183,87 +182,88 @@ func (wsedc *websocketWithEarlyDataConn) Dial(earlyData []byte) error {
|
||||
return fmt.Errorf("failed to encode early data: %w", err)
|
||||
}
|
||||
|
||||
if errc := base64EarlyDataEncoder.Close(); errc != nil {
|
||||
return fmt.Errorf("failed to encode early data tail: %w", errc)
|
||||
if err := base64EarlyDataEncoder.Close(); err != nil {
|
||||
return fmt.Errorf("failed to encode early data tail: %w", err)
|
||||
}
|
||||
|
||||
var err error
|
||||
if wsedc.Conn, err = streamWebsocketConn(wsedc.ctx, wsedc.underlay, wsedc.config, base64DataBuf); err != nil {
|
||||
wsedc.Close()
|
||||
conn, err := streamWebsocketConn(wsedc.ctx, wsedc.underlay, wsedc.config, base64DataBuf)
|
||||
if err != nil {
|
||||
_ = wsedc.Close()
|
||||
return fmt.Errorf("failed to dial WebSocket: %w", err)
|
||||
}
|
||||
|
||||
wsedc.dialed <- true
|
||||
wsedc.wsWriter = N.NewExtendedWriter(wsedc.Conn)
|
||||
wsedc.conn = N.NewExtendedConn(conn)
|
||||
close(wsedc.dialed)
|
||||
if earlyDataBuf.Len() != 0 {
|
||||
_, err = wsedc.Conn.Write(earlyDataBuf.Bytes())
|
||||
_, err = wsedc.conn.Write(earlyDataBuf.Bytes())
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Write(b []byte) (int, error) {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
select {
|
||||
case <-wsedc.ctx.Done():
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
if err := wsedc.Dial(b); err != nil {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.Write(b)
|
||||
default:
|
||||
if err := wsedc.dial(b); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
return wsedc.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
select {
|
||||
case <-wsedc.ctx.Done():
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
if err := wsedc.Dial(buffer.Bytes()); err != nil {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.WriteBuffer(buffer)
|
||||
default:
|
||||
if err := wsedc.dial(buffer.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return wsedc.wsWriter.WriteBuffer(buffer)
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Read(b []byte) (int, error) {
|
||||
if wsedc.ctx.Err() != nil {
|
||||
select {
|
||||
case <-wsedc.ctx.Done():
|
||||
return 0, io.ErrClosedPipe
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.Read(b)
|
||||
}
|
||||
if wsedc.Conn == nil {
|
||||
select {
|
||||
case <-wsedc.ctx.Done():
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
case <-wsedc.dialed:
|
||||
}
|
||||
}
|
||||
return wsedc.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) Close() error {
|
||||
wsedc.cancel()
|
||||
if wsedc.Conn == nil { // is dialing or not dialed
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.Close()
|
||||
default:
|
||||
return wsedc.underlay.Close()
|
||||
}
|
||||
return wsedc.Conn.Close()
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) LocalAddr() net.Addr {
|
||||
if wsedc.Conn == nil {
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.LocalAddr()
|
||||
default:
|
||||
return wsedc.underlay.LocalAddr()
|
||||
}
|
||||
return wsedc.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) RemoteAddr() net.Addr {
|
||||
if wsedc.Conn == nil {
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.RemoteAddr()
|
||||
default:
|
||||
return wsedc.underlay.RemoteAddr()
|
||||
}
|
||||
return wsedc.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) SetDeadline(t time.Time) error {
|
||||
@@ -274,17 +274,21 @@ func (wsedc *websocketWithEarlyDataConn) SetDeadline(t time.Time) error {
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) SetReadDeadline(t time.Time) error {
|
||||
if wsedc.Conn == nil {
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.SetReadDeadline(t)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return wsedc.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) SetWriteDeadline(t time.Time) error {
|
||||
if wsedc.Conn == nil {
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return wsedc.conn.SetReadDeadline(t)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return wsedc.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) FrontHeadroom() int {
|
||||
@@ -307,13 +311,18 @@ func (wsedc *websocketWithEarlyDataConn) Upstream() any {
|
||||
//}
|
||||
|
||||
func (wsedc *websocketWithEarlyDataConn) NeedHandshake() bool {
|
||||
return wsedc.Conn == nil
|
||||
select {
|
||||
case <-wsedc.dialed:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func streamWebsocketWithEarlyDataConn(conn net.Conn, c *WebsocketConfig) (net.Conn, error) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
conn = &websocketWithEarlyDataConn{
|
||||
dialed: make(chan bool, 1),
|
||||
dialed: make(chan struct{}),
|
||||
cancel: cancel,
|
||||
ctx: ctx,
|
||||
underlay: conn,
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package xhttp
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/randv2"
|
||||
)
|
||||
|
||||
// The Chrome version generator will suffer from deviation of a normal distribution.
|
||||
|
||||
func ChromeVersion() int {
|
||||
// Start from Chrome 144, released on 2026.1.13.
|
||||
var startVersion int = 144
|
||||
var timeStart int64 = time.Date(2026, 1, 13, 0, 0, 0, 0, time.UTC).Unix() / 86400
|
||||
var timeCurrent int64 = time.Now().Unix() / 86400
|
||||
var timeDiff int = int((timeCurrent - timeStart - 35)) - int(math.Floor(math.Pow(randv2.Float64(), 2)*105))
|
||||
return startVersion + (timeDiff / 35) // It's 31.15 currently.
|
||||
}
|
||||
|
||||
var safariMinorMap [25]int = [25]int{0, 0, 0, 1, 1,
|
||||
1, 2, 2, 2, 2, 3, 3, 3, 4, 4,
|
||||
4, 5, 5, 5, 5, 5, 6, 6, 6, 6}
|
||||
|
||||
// The following version generators use deterministic generators, but with the distribution scaled by a curve.
|
||||
|
||||
func CurlVersion() string {
|
||||
// curl 8.0.0 was released on 20/03/2023.
|
||||
var timeCurrent int64 = time.Now().Unix() / 86400
|
||||
var timeStart int64 = time.Date(2023, 3, 20, 0, 0, 0, 0, time.UTC).Unix() / 86400
|
||||
var timeDiff int = int((timeCurrent - timeStart - 60)) - int(math.Floor(math.Pow(randv2.Float64(), 2)*165))
|
||||
var minorValue int = int(timeDiff / 57) // The release cadence is actually 56.67 days.
|
||||
return "8." + strconv.Itoa(minorValue) + ".0"
|
||||
}
|
||||
func FirefoxVersion() int {
|
||||
// Firefox 128 ESR was released on 09/07/2023.
|
||||
var timeCurrent int64 = time.Now().Unix() / 86400
|
||||
var timeStart int64 = time.Date(2024, 7, 29, 0, 0, 0, 0, time.UTC).Unix() / 86400
|
||||
var timeDiff = timeCurrent - timeStart - 25 - int64(math.Floor(math.Pow(randv2.Float64(), 2)*50))
|
||||
return int(timeDiff/30) + 128
|
||||
}
|
||||
func SafariVersion() string {
|
||||
var anchoredTime time.Time = time.Now()
|
||||
var releaseYear int = anchoredTime.Year()
|
||||
var splitPoint time.Time = time.Date(releaseYear, 9, 23, 0, 0, 0, 0, time.UTC)
|
||||
var delayedDays = int(math.Floor(math.Pow(randv2.Float64(), 3) * 75))
|
||||
splitPoint = splitPoint.AddDate(0, 0, delayedDays)
|
||||
if anchoredTime.Compare(splitPoint) < 0 {
|
||||
releaseYear--
|
||||
splitPoint = time.Date(releaseYear, 9, 23, 0, 0, 0, 0, time.UTC)
|
||||
splitPoint = splitPoint.AddDate(0, 0, delayedDays)
|
||||
}
|
||||
var minorVersion = safariMinorMap[(anchoredTime.Unix()-splitPoint.Unix())/1296000]
|
||||
return strconv.Itoa(releaseYear-1999) + "." + strconv.Itoa(minorVersion)
|
||||
}
|
||||
|
||||
// The full Chromium brand GREASE implementation
|
||||
var clientHintGreaseNA = []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"}
|
||||
var clientHintVersionNA = []string{"8", "99", "24"}
|
||||
var clientHintShuffle3 = [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
|
||||
var clientHintShuffle4 = [][4]int{
|
||||
{0, 1, 2, 3}, {0, 1, 3, 2}, {0, 2, 1, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}, {0, 3, 2, 1},
|
||||
{1, 0, 2, 3}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 2, 3, 0}, {1, 3, 0, 2}, {1, 3, 2, 0},
|
||||
{2, 0, 1, 3}, {2, 0, 3, 1}, {2, 1, 0, 3}, {2, 1, 3, 0}, {2, 3, 0, 1}, {2, 3, 1, 0},
|
||||
{3, 0, 1, 2}, {3, 0, 2, 1}, {3, 1, 0, 2}, {3, 1, 2, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}}
|
||||
|
||||
func getGreasedChInvalidBrand(seed int) string {
|
||||
return "\"Not" + clientHintGreaseNA[seed%len(clientHintGreaseNA)] + "A" + clientHintGreaseNA[(seed+1)%len(clientHintGreaseNA)] + "Brand\";v=\"" + clientHintVersionNA[seed%len(clientHintVersionNA)] + "\""
|
||||
}
|
||||
func getGreasedChOrder(brandLength int, seed int) []int {
|
||||
switch brandLength {
|
||||
case 1:
|
||||
return []int{0}
|
||||
case 2:
|
||||
return []int{seed % brandLength, (seed + 1) % brandLength}
|
||||
case 3:
|
||||
return clientHintShuffle3[seed%len(clientHintShuffle3)][:]
|
||||
default:
|
||||
return clientHintShuffle4[seed%len(clientHintShuffle4)][:]
|
||||
}
|
||||
//return []int{}
|
||||
}
|
||||
func getUngreasedChUa(majorVersion int, forkName string) []string {
|
||||
// Set the capacity to 4, the maximum allowed brand size, so Go will never allocate memory twice
|
||||
baseChUa := make([]string, 0, 4)
|
||||
baseChUa = append(baseChUa, getGreasedChInvalidBrand(majorVersion),
|
||||
"\"Chromium\";v=\""+strconv.Itoa(majorVersion)+"\"")
|
||||
switch forkName {
|
||||
case "chrome":
|
||||
baseChUa = append(baseChUa, "\"Google Chrome\";v=\""+strconv.Itoa(majorVersion)+"\"")
|
||||
case "edge":
|
||||
baseChUa = append(baseChUa, "\"Microsoft Edge\";v=\""+strconv.Itoa(majorVersion)+"\"")
|
||||
}
|
||||
return baseChUa
|
||||
}
|
||||
func getGreasedChUa(majorVersion int, forkName string) string {
|
||||
ungreasedCh := getUngreasedChUa(majorVersion, forkName)
|
||||
shuffleMap := getGreasedChOrder(len(ungreasedCh), majorVersion)
|
||||
shuffledCh := make([]string, len(ungreasedCh))
|
||||
for i, e := range shuffleMap {
|
||||
shuffledCh[e] = ungreasedCh[i]
|
||||
}
|
||||
return strings.Join(shuffledCh, ", ")
|
||||
}
|
||||
|
||||
// The code below provides a coherent default browser user agent string based on a CPU-seeded PRNG.
|
||||
|
||||
var CurlUA = "curl/" + CurlVersion()
|
||||
var AnchoredFirefoxVersion = strconv.Itoa(FirefoxVersion())
|
||||
var FirefoxUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:" + AnchoredFirefoxVersion + ".0) Gecko/20100101 Firefox/" + AnchoredFirefoxVersion + ".0"
|
||||
var SafariUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/" + SafariVersion() + " Safari/605.1.15"
|
||||
|
||||
// Chromium browsers.
|
||||
|
||||
var AnchoredChromeVersion = ChromeVersion()
|
||||
var ChromeUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + strconv.Itoa(AnchoredChromeVersion) + ".0.0.0 Safari/537.36"
|
||||
var ChromeUACH = getGreasedChUa(AnchoredChromeVersion, "chrome")
|
||||
var MSEdgeUA = ChromeUA + "Edg/" + strconv.Itoa(AnchoredChromeVersion) + ".0.0.0"
|
||||
var MSEdgeUACH = getGreasedChUa(AnchoredChromeVersion, "edge")
|
||||
|
||||
func applyMasqueradedHeaders(header http.Header, browser string, variant string) {
|
||||
// Browser-specific.
|
||||
switch browser {
|
||||
case "chrome":
|
||||
header["Sec-CH-UA"] = []string{ChromeUACH}
|
||||
header["Sec-CH-UA-Mobile"] = []string{"?0"}
|
||||
header["Sec-CH-UA-Platform"] = []string{"\"Windows\""}
|
||||
header["DNT"] = []string{"1"}
|
||||
header.Set("User-Agent", ChromeUA)
|
||||
header.Set("Accept-Language", "en-US,en;q=0.9")
|
||||
case "edge":
|
||||
header["Sec-CH-UA"] = []string{MSEdgeUACH}
|
||||
header["Sec-CH-UA-Mobile"] = []string{"?0"}
|
||||
header["Sec-CH-UA-Platform"] = []string{"\"Windows\""}
|
||||
header["DNT"] = []string{"1"}
|
||||
header.Set("User-Agent", MSEdgeUA)
|
||||
header.Set("Accept-Language", "en-US,en;q=0.9")
|
||||
case "firefox":
|
||||
header.Set("User-Agent", FirefoxUA)
|
||||
header["DNT"] = []string{"1"}
|
||||
header.Set("Accept-Language", "en-US,en;q=0.5")
|
||||
case "safari":
|
||||
header.Set("User-Agent", SafariUA)
|
||||
header.Set("Accept-Language", "en-US,en;q=0.9")
|
||||
case "golang":
|
||||
// Expose the default net/http header.
|
||||
header.Del("User-Agent")
|
||||
return
|
||||
case "curl":
|
||||
header.Set("User-Agent", CurlUA)
|
||||
return
|
||||
}
|
||||
// Context-specific.
|
||||
switch variant {
|
||||
case "nav":
|
||||
if header.Get("Cache-Control") == "" {
|
||||
switch browser {
|
||||
case "chrome", "edge":
|
||||
header.Set("Cache-Control", "max-age=0")
|
||||
}
|
||||
}
|
||||
header.Set("Upgrade-Insecure-Requests", "1")
|
||||
if header.Get("Accept") == "" {
|
||||
switch browser {
|
||||
case "chrome", "edge":
|
||||
header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
|
||||
case "firefox", "safari":
|
||||
header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
}
|
||||
}
|
||||
header.Set("Sec-Fetch-Site", "none")
|
||||
header.Set("Sec-Fetch-Mode", "navigate")
|
||||
switch browser {
|
||||
case "safari":
|
||||
default:
|
||||
header.Set("Sec-Fetch-User", "?1")
|
||||
}
|
||||
header.Set("Sec-Fetch-Dest", "document")
|
||||
header.Set("Priority", "u=0, i")
|
||||
case "ws":
|
||||
header.Set("Sec-Fetch-Mode", "websocket")
|
||||
switch browser {
|
||||
case "safari":
|
||||
// Safari is NOT web-compliant here!
|
||||
header.Set("Sec-Fetch-Dest", "websocket")
|
||||
default:
|
||||
header.Set("Sec-Fetch-Dest", "empty")
|
||||
}
|
||||
header.Set("Sec-Fetch-Site", "same-origin")
|
||||
if header.Get("Cache-Control") == "" {
|
||||
header.Set("Cache-Control", "no-cache")
|
||||
}
|
||||
if header.Get("Pragma") == "" {
|
||||
header.Set("Pragma", "no-cache")
|
||||
}
|
||||
if header.Get("Accept") == "" {
|
||||
header.Set("Accept", "*/*")
|
||||
}
|
||||
case "fetch":
|
||||
header.Set("Sec-Fetch-Mode", "cors")
|
||||
header.Set("Sec-Fetch-Dest", "empty")
|
||||
header.Set("Sec-Fetch-Site", "same-origin")
|
||||
if header.Get("Priority") == "" {
|
||||
switch browser {
|
||||
case "chrome", "edge":
|
||||
header.Set("Priority", "u=1, i")
|
||||
case "firefox":
|
||||
header.Set("Priority", "u=4")
|
||||
case "safari":
|
||||
header.Set("Priority", "u=3, i")
|
||||
}
|
||||
}
|
||||
if header.Get("Cache-Control") == "" {
|
||||
header.Set("Cache-Control", "no-cache")
|
||||
}
|
||||
if header.Get("Pragma") == "" {
|
||||
header.Set("Pragma", "no-cache")
|
||||
}
|
||||
if header.Get("Accept") == "" {
|
||||
header.Set("Accept", "*/*")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TryDefaultHeadersWith(header http.Header, variant string) {
|
||||
// The global UA special value handler for transports. Used to be called HandleTransportUASettings.
|
||||
// Just a FYI to whoever needing to fix this piece of code after some spontaneous event, I tried to make the two methods separate to let the code be cleaner and more organized.
|
||||
if len(header.Values("User-Agent")) < 1 {
|
||||
applyMasqueradedHeaders(header, "chrome", variant)
|
||||
} else {
|
||||
switch header.Get("User-Agent") {
|
||||
case "chrome":
|
||||
applyMasqueradedHeaders(header, "chrome", variant)
|
||||
case "firefox":
|
||||
applyMasqueradedHeaders(header, "firefox", variant)
|
||||
case "safari":
|
||||
applyMasqueradedHeaders(header, "safari", variant)
|
||||
case "edge":
|
||||
applyMasqueradedHeaders(header, "edge", variant)
|
||||
case "curl":
|
||||
applyMasqueradedHeaders(header, "curl", variant)
|
||||
case "golang":
|
||||
applyMasqueradedHeaders(header, "golang", variant)
|
||||
}
|
||||
}
|
||||
}
|
||||
+328
-95
@@ -1,6 +1,7 @@
|
||||
package xhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
@@ -11,48 +12,99 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/mihomo/common/httputils"
|
||||
|
||||
"github.com/metacubex/http"
|
||||
"github.com/metacubex/http/httptrace"
|
||||
"github.com/metacubex/quic-go"
|
||||
"github.com/metacubex/quic-go/http3"
|
||||
"github.com/metacubex/tls"
|
||||
)
|
||||
|
||||
// ConnIdleTimeout defines the maximum time an idle TCP session can survive in the tunnel,
|
||||
// so it should be consistent across HTTP versions and with other transports.
|
||||
const ConnIdleTimeout = 300 * time.Second
|
||||
|
||||
// QuicgoH3KeepAlivePeriod consistent with quic-go
|
||||
const QuicgoH3KeepAlivePeriod = 10 * time.Second
|
||||
|
||||
// ChromeH2KeepAlivePeriod consistent with chrome
|
||||
const ChromeH2KeepAlivePeriod = 45 * time.Second
|
||||
|
||||
type DialRawFunc func(ctx context.Context) (net.Conn, error)
|
||||
type WrapTLSFunc func(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
type DialQUICFunc func(ctx context.Context, cfg *quic.Config) (*quic.Conn, error)
|
||||
|
||||
type TransportMaker func() http.RoundTripper
|
||||
|
||||
type PacketUpWriter struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
cfg *Config
|
||||
sessionID string
|
||||
transport http.RoundTripper
|
||||
writeMu sync.Mutex
|
||||
seq uint64
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
cfg *Config
|
||||
scMaxEachPostBytes int
|
||||
scMinPostsIntervalMs Range
|
||||
sessionID string
|
||||
transport http.RoundTripper
|
||||
writeMu sync.Mutex
|
||||
writeCond sync.Cond
|
||||
seq uint64
|
||||
buf []byte
|
||||
timer *time.Timer
|
||||
flushErr error
|
||||
}
|
||||
|
||||
func (c *PacketUpWriter) Write(b []byte) (int, error) {
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
scMaxEachPostBytes := c.cfg.GetNormalizedScMaxEachPostBytes()
|
||||
if len(b) < scMaxEachPostBytes {
|
||||
return c.write(b)
|
||||
|
||||
if err := c.flushErr; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var n int
|
||||
for start := 0; start < len(b); start += scMaxEachPostBytes {
|
||||
end := start + scMaxEachPostBytes
|
||||
if end > len(b) {
|
||||
end = len(b)
|
||||
|
||||
data := bytes.NewBuffer(b)
|
||||
for data.Len() > 0 {
|
||||
if c.timer == nil { // start a timer to flush the buffer
|
||||
c.timer = time.AfterFunc(time.Duration(c.scMinPostsIntervalMs.Rand())*time.Millisecond, c.flush)
|
||||
}
|
||||
_n, err := c.write(b[start:end])
|
||||
n += _n
|
||||
if err != nil {
|
||||
return n, err
|
||||
|
||||
c.buf = append(c.buf, data.Next(c.scMaxEachPostBytes-len(c.buf))...) // let buffer fill up to scMaxEachPostBytes
|
||||
|
||||
if len(c.buf) >= c.scMaxEachPostBytes { // too much data in buffer, wait the flush complete
|
||||
c.writeCond.Wait()
|
||||
if err := c.flushErr; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (c *PacketUpWriter) flush() {
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
|
||||
defer c.writeCond.Broadcast() // wake up the waited Write() call
|
||||
|
||||
if c.timer != nil {
|
||||
c.timer.Stop()
|
||||
c.timer = nil
|
||||
}
|
||||
|
||||
if c.flushErr != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(c.buf) == 0 {
|
||||
return
|
||||
}
|
||||
_, err := c.write(c.buf)
|
||||
c.buf = c.buf[:0] // reset buffer
|
||||
if err != nil {
|
||||
c.flushErr = err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (c *PacketUpWriter) write(b []byte) (int, error) {
|
||||
@@ -62,7 +114,7 @@ func (c *PacketUpWriter) write(b []byte) (int, error) {
|
||||
Path: c.cfg.NormalizedPath(),
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(c.ctx, http.MethodPost, u.String(), nil)
|
||||
req, err := http.NewRequestWithContext(c.ctx, c.cfg.GetNormalizedUplinkHTTPMethod(), u.String(), nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -90,12 +142,65 @@ func (c *PacketUpWriter) write(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (c *PacketUpWriter) Close() error {
|
||||
ch := make(chan struct{})
|
||||
go func() { // flush in the background
|
||||
defer close(ch)
|
||||
c.flush()
|
||||
}()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
c.cancel()
|
||||
httputils.CloseTransport(c.transport)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, alpn []string) http.RoundTripper {
|
||||
func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, dialQUIC DialQUICFunc, alpn []string, keepAlivePeriod time.Duration) http.RoundTripper {
|
||||
if len(alpn) == 1 && alpn[0] == "h3" { // `alpn: [h3]` means using h3 mode
|
||||
if keepAlivePeriod == 0 {
|
||||
keepAlivePeriod = QuicgoH3KeepAlivePeriod
|
||||
}
|
||||
if keepAlivePeriod < 0 {
|
||||
keepAlivePeriod = 0
|
||||
}
|
||||
return &http3.Transport{
|
||||
QUICConfig: &quic.Config{
|
||||
MaxIncomingStreams: -1, // don't allow the server to create bidirectional streams
|
||||
KeepAlivePeriod: keepAlivePeriod,
|
||||
MaxIdleTimeout: ConnIdleTimeout,
|
||||
},
|
||||
Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (*quic.Conn, error) {
|
||||
return dialQUIC(ctx, cfg)
|
||||
},
|
||||
}
|
||||
}
|
||||
if len(alpn) == 1 && alpn[0] == "http/1.1" { // `alpn: [http/1.1]` means using http/1.1 mode
|
||||
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
raw, err := dialRaw(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
wrapped, err := wrapTLS(ctx, raw, false)
|
||||
if err != nil {
|
||||
_ = raw.Close()
|
||||
return nil, err
|
||||
}
|
||||
return wrapped, nil
|
||||
}
|
||||
return &http.Transport{
|
||||
DialContext: dialContext,
|
||||
DialTLSContext: dialContext,
|
||||
IdleConnTimeout: ConnIdleTimeout,
|
||||
ForceAttemptHTTP2: false, // only http/1.1
|
||||
}
|
||||
}
|
||||
if keepAlivePeriod == 0 {
|
||||
keepAlivePeriod = ChromeH2KeepAlivePeriod
|
||||
}
|
||||
if keepAlivePeriod < 0 {
|
||||
keepAlivePeriod = 0
|
||||
}
|
||||
return &http.Http2Transport{
|
||||
DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
|
||||
raw, err := dialRaw(ctx)
|
||||
@@ -109,6 +214,8 @@ func NewTransport(dialRaw DialRawFunc, wrapTLS WrapTLSFunc, alpn []string) http.
|
||||
}
|
||||
return wrapped, nil
|
||||
},
|
||||
IdleConnTimeout: ConnIdleTimeout,
|
||||
ReadIdleTimeout: keepAlivePeriod,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +224,8 @@ type Client struct {
|
||||
cancel context.CancelFunc
|
||||
mode string
|
||||
cfg *Config
|
||||
scMaxEachPostBytes Range
|
||||
scMinPostsIntervalMs Range
|
||||
makeTransport TransportMaker
|
||||
makeDownloadTransport TransportMaker
|
||||
uploadManager *ReuseManager
|
||||
@@ -130,22 +239,32 @@ func NewClient(cfg *Config, makeTransport TransportMaker, makeDownloadTransport
|
||||
default:
|
||||
return nil, fmt.Errorf("xhttp mode %s is not implemented yet", mode)
|
||||
}
|
||||
scMaxEachPostBytes, err := cfg.GetNormalizedScMaxEachPostBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scMinPostsIntervalMs, err := cfg.GetNormalizedScMinPostsIntervalMs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
client := &Client{
|
||||
mode: mode,
|
||||
cfg: cfg,
|
||||
scMaxEachPostBytes: scMaxEachPostBytes,
|
||||
scMinPostsIntervalMs: scMinPostsIntervalMs,
|
||||
makeTransport: makeTransport,
|
||||
makeDownloadTransport: makeDownloadTransport,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
if cfg.ReuseConfig != nil {
|
||||
var err error
|
||||
client.uploadManager, err = NewReuseManager(cfg.ReuseConfig, makeTransport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client.makeTransport = client.uploadManager.GetTransport
|
||||
if cfg.DownloadConfig != nil {
|
||||
if makeDownloadTransport == nil {
|
||||
return nil, fmt.Errorf("xhttp: download manager requires download transport maker")
|
||||
@@ -154,6 +273,7 @@ func NewClient(cfg *Config, makeTransport TransportMaker, makeDownloadTransport
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client.makeDownloadTransport = client.downloadManager.GetTransport
|
||||
}
|
||||
}
|
||||
return client, nil
|
||||
@@ -196,26 +316,10 @@ type onlyRoundTripper struct {
|
||||
}
|
||||
|
||||
func (c *Client) getTransport() (uploadTransport http.RoundTripper, downloadTransport http.RoundTripper, err error) {
|
||||
if c.uploadManager == nil {
|
||||
uploadTransport = c.makeTransport()
|
||||
downloadTransport = onlyRoundTripper{uploadTransport}
|
||||
if c.makeDownloadTransport != nil {
|
||||
downloadTransport = c.makeDownloadTransport()
|
||||
}
|
||||
} else {
|
||||
uploadTransport, err = c.uploadManager.GetTransport()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
downloadTransport = onlyRoundTripper{uploadTransport}
|
||||
if c.downloadManager != nil {
|
||||
downloadTransport, err = c.downloadManager.GetTransport()
|
||||
if err != nil {
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
return
|
||||
}
|
||||
}
|
||||
uploadTransport = c.makeTransport()
|
||||
downloadTransport = onlyRoundTripper{uploadTransport}
|
||||
if c.makeDownloadTransport != nil {
|
||||
downloadTransport = c.makeDownloadTransport()
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -235,7 +339,21 @@ func (c *Client) DialStreamOne() (net.Conn, error) {
|
||||
|
||||
conn := &Conn{writer: pw}
|
||||
|
||||
req, err := http.NewRequestWithContext(httputils.NewAddrContext(&conn.NetAddr, c.ctx), http.MethodPost, requestURL.String(), pr)
|
||||
// Use gotConn to detect when TCP connection is established, so we can
|
||||
// return the conn immediately without waiting for the HTTP response.
|
||||
// This breaks the deadlock where CDN buffers response headers until the
|
||||
// server sends body data, but the server waits for our request body,
|
||||
// which can't be sent because we haven't returned the conn yet.
|
||||
gotConn := make(chan bool, 1)
|
||||
|
||||
addrCtx := httputils.NewAddrContext(&conn.NetAddr, c.ctx)
|
||||
ctx := httptrace.WithClientTrace(addrCtx, &httptrace.ClientTrace{
|
||||
GotConn: func(info httptrace.GotConnInfo) {
|
||||
gotConn <- true
|
||||
},
|
||||
})
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, c.cfg.GetNormalizedUplinkHTTPMethod(), requestURL.String(), pr)
|
||||
if err != nil {
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
@@ -244,28 +362,41 @@ func (c *Client) DialStreamOne() (net.Conn, error) {
|
||||
}
|
||||
req.Host = c.cfg.Host
|
||||
|
||||
if err := c.cfg.FillStreamRequest(req, ""); err != nil {
|
||||
if err = c.cfg.FillStreamRequest(req, ""); err != nil {
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
httputils.CloseTransport(transport)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
wrc := NewWaitReadCloser()
|
||||
|
||||
go func() {
|
||||
resp, err := transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
wrc.CloseWithError(err)
|
||||
close(gotConn)
|
||||
return
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_ = resp.Body.Close()
|
||||
wrc.CloseWithError(fmt.Errorf("xhttp stream-one bad status: %s", resp.Status))
|
||||
return
|
||||
}
|
||||
wrc.Set(resp.Body)
|
||||
}()
|
||||
|
||||
if !<-gotConn {
|
||||
// RoundTrip failed before TCP connected (e.g. DNS failure)
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
httputils.CloseTransport(transport)
|
||||
var buf [0]byte
|
||||
_, err = wrc.Read(buf[:])
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_ = resp.Body.Close()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
httputils.CloseTransport(transport)
|
||||
return nil, fmt.Errorf("xhttp stream-one bad status: %s", resp.Status)
|
||||
}
|
||||
conn.reader = resp.Body
|
||||
|
||||
conn.reader = wrc
|
||||
conn.onClose = func() {
|
||||
_ = pr.Close()
|
||||
httputils.CloseTransport(transport)
|
||||
@@ -302,8 +433,18 @@ func (c *Client) DialStreamUp() (net.Conn, error) {
|
||||
|
||||
sessionID := newSessionID()
|
||||
|
||||
// Async download: avoid blocking on CDN response header buffering
|
||||
gotConn := make(chan bool, 1)
|
||||
|
||||
addrCtx := httputils.NewAddrContext(&conn.NetAddr, c.ctx)
|
||||
downloadCtx := httptrace.WithClientTrace(addrCtx, &httptrace.ClientTrace{
|
||||
GotConn: func(info httptrace.GotConnInfo) {
|
||||
gotConn <- true
|
||||
},
|
||||
})
|
||||
|
||||
downloadReq, err := http.NewRequestWithContext(
|
||||
httputils.NewAddrContext(&conn.NetAddr, c.ctx),
|
||||
downloadCtx,
|
||||
http.MethodGet,
|
||||
downloadURL.String(),
|
||||
nil,
|
||||
@@ -321,44 +462,55 @@ func (c *Client) DialStreamUp() (net.Conn, error) {
|
||||
}
|
||||
downloadReq.Host = downloadCfg.Host
|
||||
|
||||
downloadResp, err := downloadTransport.RoundTrip(downloadReq)
|
||||
if err != nil {
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, err
|
||||
}
|
||||
if downloadResp.StatusCode != http.StatusOK {
|
||||
_ = downloadResp.Body.Close()
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, fmt.Errorf("xhttp stream-up download bad status: %s", downloadResp.Status)
|
||||
}
|
||||
|
||||
uploadReq, err := http.NewRequestWithContext(
|
||||
c.ctx,
|
||||
http.MethodPost,
|
||||
c.cfg.GetNormalizedUplinkHTTPMethod(),
|
||||
streamURL.String(),
|
||||
pr,
|
||||
)
|
||||
if err != nil {
|
||||
_ = downloadResp.Body.Close()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := c.cfg.FillStreamRequest(uploadReq, sessionID); err != nil {
|
||||
_ = downloadResp.Body.Close()
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
if err = c.cfg.FillStreamRequest(uploadReq, sessionID); err != nil {
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, err
|
||||
}
|
||||
uploadReq.Host = c.cfg.Host
|
||||
|
||||
wrc := NewWaitReadCloser()
|
||||
|
||||
go func() {
|
||||
resp, err := downloadTransport.RoundTrip(downloadReq)
|
||||
if err != nil {
|
||||
wrc.CloseWithError(err)
|
||||
close(gotConn)
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = resp.Body.Close()
|
||||
wrc.CloseWithError(fmt.Errorf("xhttp stream-up download bad status: %s", resp.Status))
|
||||
return
|
||||
}
|
||||
wrc.Set(resp.Body)
|
||||
}()
|
||||
|
||||
if !<-gotConn {
|
||||
_ = pr.Close()
|
||||
_ = pw.Close()
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
var buf [0]byte
|
||||
_, err = wrc.Read(buf[:])
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Start upload after download TCP is connected, so the server has likely
|
||||
// already processed the GET and created the session. This preserves the
|
||||
// original ordering (download before upload) while still being async.
|
||||
go func() {
|
||||
resp, err := uploadTransport.RoundTrip(uploadReq)
|
||||
if err != nil {
|
||||
@@ -373,7 +525,7 @@ func (c *Client) DialStreamUp() (net.Conn, error) {
|
||||
}
|
||||
}()
|
||||
|
||||
conn.reader = downloadResp.Body
|
||||
conn.reader = wrc
|
||||
conn.onClose = func() {
|
||||
_ = pr.Close()
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
@@ -403,17 +555,30 @@ func (c *Client) DialPacketUp() (net.Conn, error) {
|
||||
|
||||
writerCtx, writerCancel := context.WithCancel(c.ctx)
|
||||
writer := &PacketUpWriter{
|
||||
ctx: writerCtx,
|
||||
cancel: writerCancel,
|
||||
cfg: c.cfg,
|
||||
sessionID: sessionID,
|
||||
transport: uploadTransport,
|
||||
seq: 0,
|
||||
ctx: writerCtx,
|
||||
cancel: writerCancel,
|
||||
cfg: c.cfg,
|
||||
scMaxEachPostBytes: c.scMaxEachPostBytes.Rand(),
|
||||
scMinPostsIntervalMs: c.scMinPostsIntervalMs,
|
||||
sessionID: sessionID,
|
||||
transport: uploadTransport,
|
||||
seq: 0,
|
||||
}
|
||||
writer.writeCond = sync.Cond{L: &writer.writeMu}
|
||||
conn := &Conn{writer: writer}
|
||||
|
||||
// Async download: avoid blocking on CDN response header buffering
|
||||
gotConn := make(chan bool, 1)
|
||||
|
||||
addrCtx := httputils.NewAddrContext(&conn.NetAddr, c.ctx)
|
||||
downloadCtx := httptrace.WithClientTrace(addrCtx, &httptrace.ClientTrace{
|
||||
GotConn: func(info httptrace.GotConnInfo) {
|
||||
gotConn <- true
|
||||
},
|
||||
})
|
||||
|
||||
downloadReq, err := http.NewRequestWithContext(
|
||||
httputils.NewAddrContext(&conn.NetAddr, c.ctx),
|
||||
downloadCtx,
|
||||
http.MethodGet,
|
||||
downloadURL.String(),
|
||||
nil,
|
||||
@@ -423,27 +588,39 @@ func (c *Client) DialPacketUp() (net.Conn, error) {
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, err
|
||||
}
|
||||
if err := downloadCfg.FillDownloadRequest(downloadReq, sessionID); err != nil {
|
||||
if err = downloadCfg.FillDownloadRequest(downloadReq, sessionID); err != nil {
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, err
|
||||
}
|
||||
downloadReq.Host = downloadCfg.Host
|
||||
|
||||
resp, err := downloadTransport.RoundTrip(downloadReq)
|
||||
if err != nil {
|
||||
wrc := NewWaitReadCloser()
|
||||
|
||||
go func() {
|
||||
resp, err := downloadTransport.RoundTrip(downloadReq)
|
||||
if err != nil {
|
||||
wrc.CloseWithError(err)
|
||||
close(gotConn)
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = resp.Body.Close()
|
||||
wrc.CloseWithError(fmt.Errorf("xhttp packet-up download bad status: %s", resp.Status))
|
||||
return
|
||||
}
|
||||
wrc.Set(resp.Body)
|
||||
}()
|
||||
|
||||
if !<-gotConn {
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
var buf [0]byte
|
||||
_, err = wrc.Read(buf[:])
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = resp.Body.Close()
|
||||
httputils.CloseTransport(uploadTransport)
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
return nil, fmt.Errorf("xhttp packet-up download bad status: %s", resp.Status)
|
||||
}
|
||||
|
||||
conn.reader = resp.Body
|
||||
conn.reader = wrc
|
||||
conn.onClose = func() {
|
||||
// uploadTransport already closed by writer
|
||||
httputils.CloseTransport(downloadTransport)
|
||||
@@ -457,3 +634,59 @@ func newSessionID() string {
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// WaitReadCloser is an io.ReadCloser that blocks on Read() until the underlying
|
||||
// ReadCloser is provided via Set(). This enables returning a reader immediately
|
||||
// while the actual HTTP response body is obtained asynchronously in a goroutine,
|
||||
// breaking the synchronous RoundTrip deadlock with CDN header buffering.
|
||||
type WaitReadCloser struct {
|
||||
wait chan struct{}
|
||||
once sync.Once
|
||||
rc io.ReadCloser
|
||||
err error
|
||||
}
|
||||
|
||||
func NewWaitReadCloser() *WaitReadCloser {
|
||||
return &WaitReadCloser{wait: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Set provides the underlying ReadCloser and unblocks any pending Read calls.
|
||||
// Must be called at most once. If Close was already called, rc is closed to
|
||||
// prevent leaks.
|
||||
func (w *WaitReadCloser) Set(rc io.ReadCloser) {
|
||||
w.setup(rc, nil)
|
||||
}
|
||||
|
||||
// CloseWithError records an error and unblocks any pending Read calls.
|
||||
func (w *WaitReadCloser) CloseWithError(err error) {
|
||||
w.setup(nil, err)
|
||||
}
|
||||
|
||||
// setup sets the underlying ReadCloser and error.
|
||||
func (w *WaitReadCloser) setup(rc io.ReadCloser, err error) {
|
||||
w.once.Do(func() {
|
||||
w.rc = rc
|
||||
w.err = err
|
||||
close(w.wait)
|
||||
})
|
||||
if w.err != nil && rc != nil {
|
||||
_ = rc.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WaitReadCloser) Read(b []byte) (int, error) {
|
||||
<-w.wait
|
||||
if w.rc == nil {
|
||||
return 0, w.err
|
||||
}
|
||||
return w.rc.Read(b)
|
||||
}
|
||||
|
||||
func (w *WaitReadCloser) Close() error {
|
||||
w.setup(nil, net.ErrClosed)
|
||||
<-w.wait
|
||||
if w.rc != nil {
|
||||
return w.rc.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+414
-155
@@ -2,6 +2,7 @@ package xhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
@@ -11,6 +12,16 @@ import (
|
||||
"github.com/metacubex/http"
|
||||
)
|
||||
|
||||
const (
|
||||
PlacementQueryInHeader = "queryInHeader"
|
||||
PlacementCookie = "cookie"
|
||||
PlacementHeader = "header"
|
||||
PlacementQuery = "query"
|
||||
PlacementPath = "path"
|
||||
PlacementBody = "body"
|
||||
PlacementAuto = "auto"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Path string
|
||||
@@ -18,16 +29,31 @@ type Config struct {
|
||||
Headers map[string]string
|
||||
NoGRPCHeader bool
|
||||
XPaddingBytes string
|
||||
XPaddingObfsMode bool
|
||||
XPaddingKey string
|
||||
XPaddingHeader string
|
||||
XPaddingPlacement string
|
||||
XPaddingMethod string
|
||||
UplinkHTTPMethod string
|
||||
SessionPlacement string
|
||||
SessionKey string
|
||||
SeqPlacement string
|
||||
SeqKey string
|
||||
UplinkDataPlacement string
|
||||
UplinkDataKey string
|
||||
UplinkChunkSize string
|
||||
NoSSEHeader bool // server only
|
||||
ScStreamUpServerSecs string // server only
|
||||
ScMaxEachPostBytes int
|
||||
ScMaxBufferedPosts string // server only
|
||||
ScMaxEachPostBytes string
|
||||
ScMinPostsIntervalMs string
|
||||
ReuseConfig *ReuseConfig
|
||||
DownloadConfig *Config
|
||||
}
|
||||
|
||||
type ReuseConfig struct {
|
||||
MaxConnections string
|
||||
MaxConcurrency string
|
||||
MaxConnections string
|
||||
CMaxReuseTimes string
|
||||
HMaxRequestTimes string
|
||||
HMaxReusableSecs string
|
||||
@@ -68,197 +94,298 @@ func (c *Config) NormalizedPath() string {
|
||||
return path
|
||||
}
|
||||
|
||||
func (c *Config) RequestHeader() http.Header {
|
||||
func (c *Config) GetRequestHeader() http.Header {
|
||||
h := http.Header{}
|
||||
for k, v := range c.Headers {
|
||||
h.Set(k, v)
|
||||
}
|
||||
|
||||
if h.Get("User-Agent") == "" {
|
||||
h.Set("User-Agent", "Mozilla/5.0")
|
||||
}
|
||||
if h.Get("Accept") == "" {
|
||||
h.Set("Accept", "*/*")
|
||||
}
|
||||
if h.Get("Accept-Language") == "" {
|
||||
h.Set("Accept-Language", "en-US,en;q=0.9")
|
||||
}
|
||||
if h.Get("Cache-Control") == "" {
|
||||
h.Set("Cache-Control", "no-cache")
|
||||
}
|
||||
if h.Get("Pragma") == "" {
|
||||
h.Set("Pragma", "no-cache")
|
||||
}
|
||||
|
||||
TryDefaultHeadersWith(h, "fetch")
|
||||
return h
|
||||
}
|
||||
|
||||
func (c *Config) RandomPadding() (string, error) {
|
||||
paddingRange := c.XPaddingBytes
|
||||
if paddingRange == "" {
|
||||
paddingRange = "100-1000"
|
||||
func (c *Config) GetRequestHeaderWithPayload(payload []byte, uplinkChunkSize Range) http.Header {
|
||||
header := c.GetRequestHeader()
|
||||
|
||||
key := c.UplinkDataKey
|
||||
encodedData := base64.RawURLEncoding.EncodeToString(payload)
|
||||
|
||||
for i := 0; len(encodedData) > 0; i++ {
|
||||
chunkSize := uplinkChunkSize.Rand()
|
||||
if len(encodedData) < chunkSize {
|
||||
chunkSize = len(encodedData)
|
||||
}
|
||||
chunk := encodedData[:chunkSize]
|
||||
encodedData = encodedData[chunkSize:]
|
||||
headerKey := fmt.Sprintf("%s-%d", key, i)
|
||||
header.Set(headerKey, chunk)
|
||||
}
|
||||
|
||||
minVal, maxVal, err := parseRange(paddingRange)
|
||||
return header
|
||||
}
|
||||
|
||||
func (c *Config) GetRequestCookiesWithPayload(payload []byte, uplinkChunkSize Range) []*http.Cookie {
|
||||
cookies := []*http.Cookie{}
|
||||
|
||||
key := c.UplinkDataKey
|
||||
encodedData := base64.RawURLEncoding.EncodeToString(payload)
|
||||
|
||||
for i := 0; len(encodedData) > 0; i++ {
|
||||
chunkSize := uplinkChunkSize.Rand()
|
||||
if len(encodedData) < chunkSize {
|
||||
chunkSize = len(encodedData)
|
||||
}
|
||||
chunk := encodedData[:chunkSize]
|
||||
encodedData = encodedData[chunkSize:]
|
||||
cookieName := fmt.Sprintf("%s_%d", key, i)
|
||||
cookies = append(cookies, &http.Cookie{Name: cookieName, Value: chunk})
|
||||
}
|
||||
|
||||
return cookies
|
||||
}
|
||||
|
||||
func (c *Config) WriteResponseHeader(writer http.ResponseWriter, requestMethod string, requestHeader http.Header) {
|
||||
if origin := requestHeader.Get("Origin"); origin == "" {
|
||||
writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
} else {
|
||||
// Chrome says: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
|
||||
writer.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
}
|
||||
|
||||
if c.GetNormalizedSessionPlacement() == PlacementCookie ||
|
||||
c.GetNormalizedSeqPlacement() == PlacementCookie ||
|
||||
c.XPaddingPlacement == PlacementCookie ||
|
||||
c.GetNormalizedUplinkDataPlacement() == PlacementCookie {
|
||||
writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
|
||||
if requestMethod == "OPTIONS" {
|
||||
requestedMethod := requestHeader.Get("Access-Control-Request-Method")
|
||||
if requestedMethod != "" {
|
||||
writer.Header().Set("Access-Control-Allow-Methods", requestedMethod)
|
||||
} else {
|
||||
writer.Header().Set("Access-Control-Allow-Methods", "*")
|
||||
}
|
||||
|
||||
requestedHeaders := requestHeader.Get("Access-Control-Request-Headers")
|
||||
if requestedHeaders == "" {
|
||||
writer.Header().Set("Access-Control-Allow-Headers", "*")
|
||||
} else {
|
||||
writer.Header().Set("Access-Control-Allow-Headers", requestedHeaders)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedUplinkHTTPMethod() string {
|
||||
if c.UplinkHTTPMethod == "" {
|
||||
return "POST"
|
||||
}
|
||||
return c.UplinkHTTPMethod
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedScStreamUpServerSecs() (Range, error) {
|
||||
r, err := ParseRange(c.ScStreamUpServerSecs, "20-80")
|
||||
if err != nil {
|
||||
return "", err
|
||||
return Range{}, fmt.Errorf("invalid sc-stream-up-server-secs: %w", err)
|
||||
}
|
||||
if minVal < 0 || maxVal < minVal {
|
||||
return "", fmt.Errorf("invalid x-padding-bytes range: %s", paddingRange)
|
||||
}
|
||||
if maxVal == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
n := minVal
|
||||
if maxVal > minVal {
|
||||
n = minVal + rand.Intn(maxVal-minVal+1)
|
||||
}
|
||||
|
||||
return strings.Repeat("X", n), nil
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedScStreamUpServerSecs() (int, error) {
|
||||
scStreamUpServerSecs := c.ScStreamUpServerSecs
|
||||
if scStreamUpServerSecs == "" {
|
||||
scStreamUpServerSecs = "20-80"
|
||||
}
|
||||
|
||||
minVal, maxVal, err := parseRange(scStreamUpServerSecs)
|
||||
func (c *Config) GetNormalizedScMaxBufferedPosts() (Range, error) {
|
||||
r, err := ParseRange(c.ScMaxBufferedPosts, "30")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return Range{}, fmt.Errorf("invalid sc-max-buffered-posts: %w", err)
|
||||
}
|
||||
if minVal < 0 || maxVal < minVal {
|
||||
return 0, fmt.Errorf("invalid sc-stream-up-server-secs range: %s", scStreamUpServerSecs)
|
||||
if r.Max == 0 {
|
||||
return Range{}, fmt.Errorf("invalid sc-max-buffered-posts: must be greater than zero")
|
||||
}
|
||||
if maxVal == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
n := minVal
|
||||
if maxVal > minVal {
|
||||
n = minVal + rand.Intn(maxVal-minVal+1)
|
||||
}
|
||||
|
||||
return n, nil
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedScMaxEachPostBytes() int {
|
||||
if c.ScMaxEachPostBytes == 0 {
|
||||
return 1000000
|
||||
func (c *Config) GetNormalizedScMaxEachPostBytes() (Range, error) {
|
||||
r, err := ParseRange(c.ScMaxEachPostBytes, "1000000")
|
||||
if err != nil {
|
||||
return Range{}, fmt.Errorf("invalid sc-max-each-post-bytes: %w", err)
|
||||
}
|
||||
return c.ScMaxEachPostBytes
|
||||
if r.Max == 0 {
|
||||
return Range{}, fmt.Errorf("invalid sc-max-each-post-bytes: must be greater than zero")
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func parseRange(s string) (int, int, error) {
|
||||
func (c *Config) GetNormalizedScMinPostsIntervalMs() (Range, error) {
|
||||
r, err := ParseRange(c.ScMinPostsIntervalMs, "30")
|
||||
if err != nil {
|
||||
return Range{}, fmt.Errorf("invalid sc-min-posts-interval-ms: %w", err)
|
||||
}
|
||||
if r.Max == 0 {
|
||||
return Range{}, fmt.Errorf("invalid sc-min-posts-interval-ms: must be greater than zero")
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedUplinkChunkSize() (Range, error) {
|
||||
uplinkChunkSize, err := ParseRange(c.UplinkChunkSize, "")
|
||||
if err != nil {
|
||||
return Range{}, fmt.Errorf("invalid uplink-chunk-size: %w", err)
|
||||
}
|
||||
if uplinkChunkSize.Max == 0 {
|
||||
switch c.GetNormalizedUplinkDataPlacement() {
|
||||
case PlacementCookie:
|
||||
return Range{
|
||||
Min: 2 * 1024, // 2 KiB
|
||||
Max: 3 * 1024, // 3 KiB
|
||||
}, nil
|
||||
case PlacementHeader:
|
||||
return Range{
|
||||
Min: 3 * 1024, // 3 KiB
|
||||
Max: 4 * 1024, // 4 KiB
|
||||
}, nil
|
||||
default:
|
||||
return c.GetNormalizedScMaxEachPostBytes()
|
||||
}
|
||||
} else if uplinkChunkSize.Min < 64 {
|
||||
uplinkChunkSize.Min = 64
|
||||
if uplinkChunkSize.Max < 64 {
|
||||
uplinkChunkSize.Max = 64
|
||||
}
|
||||
}
|
||||
return uplinkChunkSize, nil
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedSessionPlacement() string {
|
||||
if c.SessionPlacement == "" {
|
||||
return PlacementPath
|
||||
}
|
||||
return c.SessionPlacement
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedSeqPlacement() string {
|
||||
if c.SeqPlacement == "" {
|
||||
return PlacementPath
|
||||
}
|
||||
return c.SeqPlacement
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedUplinkDataPlacement() string {
|
||||
if c.UplinkDataPlacement == "" {
|
||||
return PlacementBody
|
||||
}
|
||||
return c.UplinkDataPlacement
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedSessionKey() string {
|
||||
if c.SessionKey != "" {
|
||||
return c.SessionKey
|
||||
}
|
||||
switch c.GetNormalizedSessionPlacement() {
|
||||
case PlacementHeader:
|
||||
return "X-Session"
|
||||
case PlacementCookie, PlacementQuery:
|
||||
return "x_session"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) GetNormalizedSeqKey() string {
|
||||
if c.SeqKey != "" {
|
||||
return c.SeqKey
|
||||
}
|
||||
switch c.GetNormalizedSeqPlacement() {
|
||||
case PlacementHeader:
|
||||
return "X-Seq"
|
||||
case PlacementCookie, PlacementQuery:
|
||||
return "x_seq"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type Range struct {
|
||||
Min int
|
||||
Max int
|
||||
}
|
||||
|
||||
func (r Range) Rand() int {
|
||||
if r.Min == r.Max {
|
||||
return r.Min
|
||||
}
|
||||
return r.Min + rand.Intn(r.Max-r.Min+1)
|
||||
}
|
||||
|
||||
func ParseRange(s string, fallback string) (Range, error) {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return parseRange(fallback)
|
||||
}
|
||||
return parseRange(s)
|
||||
}
|
||||
|
||||
func parseRange(s string) (Range, error) {
|
||||
parts := strings.Split(strings.TrimSpace(s), "-")
|
||||
if len(parts) == 1 {
|
||||
v, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
return Range{}, err
|
||||
}
|
||||
return v, v, nil
|
||||
return Range{v, v}, nil
|
||||
}
|
||||
if len(parts) != 2 {
|
||||
return 0, 0, fmt.Errorf("invalid range: %s", s)
|
||||
return Range{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
|
||||
minVal, err := strconv.Atoi(strings.TrimSpace(parts[0]))
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
return Range{}, err
|
||||
}
|
||||
maxVal, err := strconv.Atoi(strings.TrimSpace(parts[1]))
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return minVal, maxVal, nil
|
||||
}
|
||||
|
||||
func resolveRangeValue(s string, fallback int) (int, error) {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
minVal, maxVal, err := parseRange(s)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return Range{}, err
|
||||
}
|
||||
if minVal < 0 || maxVal < minVal {
|
||||
return 0, fmt.Errorf("invalid range: %s", s)
|
||||
return Range{}, fmt.Errorf("invalid range: %s", s)
|
||||
}
|
||||
|
||||
if minVal == maxVal {
|
||||
return minVal, nil
|
||||
}
|
||||
|
||||
return minVal + rand.Intn(maxVal-minVal+1), nil
|
||||
return Range{minVal, maxVal}, nil
|
||||
}
|
||||
|
||||
func (c *ReuseConfig) ResolveManagerConfig() (int, int, error) {
|
||||
func (c *ReuseConfig) ResolveManagerConfig() (Range, Range, error) {
|
||||
if c == nil {
|
||||
return 0, 0, nil
|
||||
return Range{}, Range{}, nil
|
||||
}
|
||||
|
||||
maxConnections, err := resolveRangeValue(c.MaxConnections, 0)
|
||||
maxConcurrency, err := ParseRange(c.MaxConcurrency, "0")
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("invalid max-connections: %w", err)
|
||||
return Range{}, Range{}, fmt.Errorf("invalid max-concurrency: %w", err)
|
||||
}
|
||||
|
||||
maxConcurrency, err := resolveRangeValue(c.MaxConcurrency, 0)
|
||||
maxConnections, err := ParseRange(c.MaxConnections, "0")
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("invalid max-concurrency: %w", err)
|
||||
return Range{}, Range{}, fmt.Errorf("invalid max-connections: %w", err)
|
||||
}
|
||||
|
||||
return maxConnections, maxConcurrency, nil
|
||||
return maxConcurrency, maxConnections, nil
|
||||
}
|
||||
|
||||
func (c *ReuseConfig) ResolveEntryConfig() (int, int, int, error) {
|
||||
func (c *ReuseConfig) ResolveEntryConfig() (Range, Range, Range, error) {
|
||||
if c == nil {
|
||||
return 0, 0, 0, nil
|
||||
return Range{}, Range{}, Range{}, nil
|
||||
}
|
||||
|
||||
hMaxRequestTimes, err := resolveRangeValue(c.HMaxRequestTimes, 0)
|
||||
cMaxReuseTimes, err := ParseRange(c.CMaxReuseTimes, "0")
|
||||
if err != nil {
|
||||
return 0, 0, 0, fmt.Errorf("invalid h-max-request-times: %w", err)
|
||||
return Range{}, Range{}, Range{}, fmt.Errorf("invalid c-max-reuse-times: %w", err)
|
||||
}
|
||||
|
||||
hMaxReusableSecs, err := resolveRangeValue(c.HMaxReusableSecs, 0)
|
||||
hMaxRequestTimes, err := ParseRange(c.HMaxRequestTimes, "0")
|
||||
if err != nil {
|
||||
return 0, 0, 0, fmt.Errorf("invalid h-max-reusable-secs: %w", err)
|
||||
return Range{}, Range{}, Range{}, fmt.Errorf("invalid h-max-request-times: %w", err)
|
||||
}
|
||||
|
||||
cMaxReuseTimes, err := resolveRangeValue(c.CMaxReuseTimes, 0)
|
||||
hMaxReusableSecs, err := ParseRange(c.HMaxReusableSecs, "0")
|
||||
if err != nil {
|
||||
return 0, 0, 0, fmt.Errorf("invalid c-max-reuse-times: %w", err)
|
||||
return Range{}, Range{}, Range{}, fmt.Errorf("invalid h-max-reusable-secs: %w", err)
|
||||
}
|
||||
|
||||
return hMaxRequestTimes, hMaxReusableSecs, cMaxReuseTimes, nil
|
||||
}
|
||||
|
||||
func (c *Config) FillStreamRequest(req *http.Request, sessionID string) error {
|
||||
req.Header = c.RequestHeader()
|
||||
|
||||
paddingValue, err := c.RandomPadding()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if paddingValue != "" {
|
||||
rawURL := req.URL.String()
|
||||
sep := "?"
|
||||
if strings.Contains(rawURL, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
req.Header.Set("Referer", rawURL+sep+"x_padding="+paddingValue)
|
||||
}
|
||||
|
||||
c.ApplyMetaToRequest(req, sessionID, "")
|
||||
|
||||
if req.Body != nil && !c.NoGRPCHeader {
|
||||
req.Header.Set("Content-Type", "application/grpc")
|
||||
}
|
||||
|
||||
return nil
|
||||
return cMaxReuseTimes, hMaxRequestTimes, hMaxReusableSecs, nil
|
||||
}
|
||||
|
||||
func appendToPath(path, value string) string {
|
||||
@@ -268,53 +395,185 @@ func appendToPath(path, value string) string {
|
||||
return path + "/" + value
|
||||
}
|
||||
|
||||
func (c *Config) ApplyMetaToRequest(req *http.Request, sessionID string, seqStr string) {
|
||||
if sessionID != "" {
|
||||
req.URL.Path = appendToPath(req.URL.Path, sessionID)
|
||||
func (c *Config) ApplyMetaToRequest(req *http.Request, sessionId string, seqStr string) {
|
||||
sessionPlacement := c.GetNormalizedSessionPlacement()
|
||||
seqPlacement := c.GetNormalizedSeqPlacement()
|
||||
sessionKey := c.GetNormalizedSessionKey()
|
||||
seqKey := c.GetNormalizedSeqKey()
|
||||
|
||||
if sessionId != "" {
|
||||
switch sessionPlacement {
|
||||
case PlacementPath:
|
||||
req.URL.Path = appendToPath(req.URL.Path, sessionId)
|
||||
case PlacementQuery:
|
||||
q := req.URL.Query()
|
||||
q.Set(sessionKey, sessionId)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
case PlacementHeader:
|
||||
req.Header.Set(sessionKey, sessionId)
|
||||
case PlacementCookie:
|
||||
req.AddCookie(&http.Cookie{Name: sessionKey, Value: sessionId})
|
||||
}
|
||||
}
|
||||
|
||||
if seqStr != "" {
|
||||
req.URL.Path = appendToPath(req.URL.Path, seqStr)
|
||||
switch seqPlacement {
|
||||
case PlacementPath:
|
||||
req.URL.Path = appendToPath(req.URL.Path, seqStr)
|
||||
case PlacementQuery:
|
||||
q := req.URL.Query()
|
||||
q.Set(seqKey, seqStr)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
case PlacementHeader:
|
||||
req.Header.Set(seqKey, seqStr)
|
||||
case PlacementCookie:
|
||||
req.AddCookie(&http.Cookie{Name: seqKey, Value: seqStr})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) FillPacketRequest(req *http.Request, sessionID string, seqStr string, payload []byte) error {
|
||||
req.Header = c.RequestHeader()
|
||||
req.Body = io.NopCloser(bytes.NewReader(payload))
|
||||
req.ContentLength = int64(len(payload))
|
||||
func (c *Config) ExtractMetaFromRequest(req *http.Request, path string) (sessionId string, seqStr string) {
|
||||
sessionPlacement := c.GetNormalizedSessionPlacement()
|
||||
seqPlacement := c.GetNormalizedSeqPlacement()
|
||||
sessionKey := c.GetNormalizedSessionKey()
|
||||
seqKey := c.GetNormalizedSeqKey()
|
||||
|
||||
paddingValue, err := c.RandomPadding()
|
||||
var subpath []string
|
||||
pathPart := 0
|
||||
if sessionPlacement == PlacementPath || seqPlacement == PlacementPath {
|
||||
subpath = strings.Split(req.URL.Path[len(path):], "/")
|
||||
}
|
||||
|
||||
switch sessionPlacement {
|
||||
case PlacementPath:
|
||||
if len(subpath) > pathPart {
|
||||
sessionId = subpath[pathPart]
|
||||
pathPart += 1
|
||||
}
|
||||
case PlacementQuery:
|
||||
sessionId = req.URL.Query().Get(sessionKey)
|
||||
case PlacementHeader:
|
||||
sessionId = req.Header.Get(sessionKey)
|
||||
case PlacementCookie:
|
||||
if cookie, e := req.Cookie(sessionKey); e == nil {
|
||||
sessionId = cookie.Value
|
||||
}
|
||||
}
|
||||
|
||||
switch seqPlacement {
|
||||
case PlacementPath:
|
||||
if len(subpath) > pathPart {
|
||||
seqStr = subpath[pathPart]
|
||||
pathPart += 1
|
||||
}
|
||||
case PlacementQuery:
|
||||
seqStr = req.URL.Query().Get(seqKey)
|
||||
case PlacementHeader:
|
||||
seqStr = req.Header.Get(seqKey)
|
||||
case PlacementCookie:
|
||||
if cookie, e := req.Cookie(seqKey); e == nil {
|
||||
seqStr = cookie.Value
|
||||
}
|
||||
}
|
||||
|
||||
return sessionId, seqStr
|
||||
}
|
||||
|
||||
func (c *Config) FillStreamRequest(req *http.Request, sessionID string) error {
|
||||
req.Header = c.GetRequestHeader()
|
||||
xPaddingBytes, err := c.GetNormalizedXPaddingBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if paddingValue != "" {
|
||||
rawURL := req.URL.String()
|
||||
sep := "?"
|
||||
if strings.Contains(rawURL, "?") {
|
||||
sep = "&"
|
||||
length := xPaddingBytes.Rand()
|
||||
config := XPaddingConfig{Length: length}
|
||||
|
||||
if c.XPaddingObfsMode {
|
||||
config.Placement = XPaddingPlacement{
|
||||
Placement: c.XPaddingPlacement,
|
||||
Key: c.XPaddingKey,
|
||||
Header: c.XPaddingHeader,
|
||||
RawURL: req.URL.String(),
|
||||
}
|
||||
config.Method = PaddingMethod(c.XPaddingMethod)
|
||||
} else {
|
||||
config.Placement = XPaddingPlacement{
|
||||
Placement: PlacementQueryInHeader,
|
||||
Key: "x_padding",
|
||||
Header: "Referer",
|
||||
RawURL: req.URL.String(),
|
||||
}
|
||||
req.Header.Set("Referer", rawURL+sep+"x_padding="+paddingValue)
|
||||
}
|
||||
|
||||
c.ApplyMetaToRequest(req, sessionID, seqStr)
|
||||
c.ApplyXPaddingToRequest(req, config)
|
||||
c.ApplyMetaToRequest(req, sessionID, "")
|
||||
|
||||
if req.Body != nil && !c.NoGRPCHeader { // stream-up/one
|
||||
req.Header.Set("Content-Type", "application/grpc")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) FillDownloadRequest(req *http.Request, sessionID string) error {
|
||||
req.Header = c.RequestHeader()
|
||||
return c.FillStreamRequest(req, sessionID)
|
||||
}
|
||||
|
||||
paddingValue, err := c.RandomPadding()
|
||||
func (c *Config) FillPacketRequest(request *http.Request, sessionId string, seqStr string, data []byte) error {
|
||||
dataPlacement := c.GetNormalizedUplinkDataPlacement()
|
||||
|
||||
if dataPlacement == PlacementBody || dataPlacement == PlacementAuto {
|
||||
request.Header = c.GetRequestHeader()
|
||||
request.Body = io.NopCloser(bytes.NewReader(data))
|
||||
request.ContentLength = int64(len(data))
|
||||
} else {
|
||||
request.Body = nil
|
||||
request.ContentLength = 0
|
||||
switch dataPlacement {
|
||||
case PlacementHeader:
|
||||
uplinkChunkSize, err := c.GetNormalizedUplinkChunkSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header = c.GetRequestHeaderWithPayload(data, uplinkChunkSize)
|
||||
case PlacementCookie:
|
||||
request.Header = c.GetRequestHeader()
|
||||
uplinkChunkSize, err := c.GetNormalizedUplinkChunkSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, cookie := range c.GetRequestCookiesWithPayload(data, uplinkChunkSize) {
|
||||
request.AddCookie(cookie)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
xPaddingBytes, err := c.GetNormalizedXPaddingBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if paddingValue != "" {
|
||||
rawURL := req.URL.String()
|
||||
sep := "?"
|
||||
if strings.Contains(rawURL, "?") {
|
||||
sep = "&"
|
||||
length := xPaddingBytes.Rand()
|
||||
config := XPaddingConfig{Length: length}
|
||||
|
||||
if c.XPaddingObfsMode {
|
||||
config.Placement = XPaddingPlacement{
|
||||
Placement: c.XPaddingPlacement,
|
||||
Key: c.XPaddingKey,
|
||||
Header: c.XPaddingHeader,
|
||||
RawURL: request.URL.String(),
|
||||
}
|
||||
config.Method = PaddingMethod(c.XPaddingMethod)
|
||||
} else {
|
||||
config.Placement = XPaddingPlacement{
|
||||
Placement: PlacementQueryInHeader,
|
||||
Key: "x_padding",
|
||||
Header: "Referer",
|
||||
RawURL: request.URL.String(),
|
||||
}
|
||||
req.Header.Set("Referer", rawURL+sep+"x_padding="+paddingValue)
|
||||
}
|
||||
|
||||
c.ApplyMetaToRequest(req, sessionID, "")
|
||||
c.ApplyXPaddingToRequest(request, config)
|
||||
c.ApplyMetaToRequest(request, sessionId, seqStr)
|
||||
|
||||
return nil
|
||||
}
|
||||
+42
-38
@@ -1,7 +1,6 @@
|
||||
package xhttp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -23,20 +22,19 @@ type reuseEntry struct {
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func (e *reuseEntry) isClosed() bool {
|
||||
return e.closed.Load()
|
||||
func (entry *reuseEntry) isClosed() bool {
|
||||
return entry.closed.Load()
|
||||
}
|
||||
|
||||
func (e *reuseEntry) close() {
|
||||
if !e.closed.CompareAndSwap(false, true) {
|
||||
func (entry *reuseEntry) close() {
|
||||
if !entry.closed.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
httputils.CloseTransport(e.transport)
|
||||
httputils.CloseTransport(entry.transport)
|
||||
}
|
||||
|
||||
type ReuseTransport struct {
|
||||
entry *reuseEntry
|
||||
manager *ReuseManager
|
||||
removed atomic.Bool
|
||||
}
|
||||
|
||||
@@ -48,39 +46,43 @@ func (rt *ReuseTransport) Close() error {
|
||||
if !rt.removed.CompareAndSwap(false, true) {
|
||||
return nil
|
||||
}
|
||||
rt.manager.release(rt.entry)
|
||||
rt.entry.release()
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ http.RoundTripper = (*ReuseTransport)(nil)
|
||||
|
||||
type ReuseManager struct {
|
||||
cfg *ReuseConfig
|
||||
maxConnections int
|
||||
maxConcurrency int
|
||||
maker TransportMaker
|
||||
mu sync.Mutex
|
||||
entries []*reuseEntry
|
||||
maxConcurrency int
|
||||
maxConnections int
|
||||
cMaxReuseTimes Range
|
||||
hMaxRequestTimes Range
|
||||
hMaxReusableSecs Range
|
||||
maker TransportMaker
|
||||
mu sync.Mutex
|
||||
entries []*reuseEntry
|
||||
}
|
||||
|
||||
func NewReuseManager(cfg *ReuseConfig, makeTransport TransportMaker) (*ReuseManager, error) {
|
||||
if cfg == nil {
|
||||
return nil, nil
|
||||
}
|
||||
connections, concurrency, err := cfg.ResolveManagerConfig()
|
||||
concurrency, connections, err := cfg.ResolveManagerConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, _, _, err = cfg.ResolveEntryConfig() // check if config is valid
|
||||
cMaxReuseTimes, hMaxRequestTimes, hMaxReusableSecs, err := cfg.ResolveEntryConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ReuseManager{
|
||||
cfg: cfg,
|
||||
maxConnections: connections,
|
||||
maxConcurrency: concurrency,
|
||||
maker: makeTransport,
|
||||
entries: make([]*reuseEntry, 0),
|
||||
maxConcurrency: concurrency.Rand(),
|
||||
maxConnections: connections.Rand(),
|
||||
cMaxReuseTimes: cMaxReuseTimes,
|
||||
hMaxRequestTimes: hMaxRequestTimes,
|
||||
hMaxReusableSecs: hMaxReusableSecs,
|
||||
maker: makeTransport,
|
||||
entries: make([]*reuseEntry, 0),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ func (m *ReuseManager) cleanupLocked(now time.Time) {
|
||||
m.entries = kept
|
||||
}
|
||||
|
||||
func (m *ReuseManager) release(entry *reuseEntry) {
|
||||
func (entry *reuseEntry) release() {
|
||||
if entry == nil {
|
||||
return
|
||||
}
|
||||
@@ -159,34 +161,36 @@ func (m *ReuseManager) pickLocked() *reuseEntry {
|
||||
return best
|
||||
}
|
||||
|
||||
func (m *ReuseManager) canCreateLocked() bool {
|
||||
if m.maxConnections <= 0 {
|
||||
func (m *ReuseManager) shouldCreateLocked() bool {
|
||||
if len(m.entries) == 0 {
|
||||
return true
|
||||
}
|
||||
return len(m.entries) < m.maxConnections
|
||||
if m.maxConnections > 0 {
|
||||
return len(m.entries) < m.maxConnections
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *ReuseManager) newEntryLocked(transport http.RoundTripper, now time.Time) *reuseEntry {
|
||||
entry := &reuseEntry{transport: transport}
|
||||
|
||||
hMaxRequestTimes, hMaxReusableSecs, cMaxReuseTimes, _ := m.cfg.ResolveEntryConfig() // error already checked in [NewReuseManager]
|
||||
if hMaxRequestTimes > 0 {
|
||||
entry.leftRequests.Store(int32(hMaxRequestTimes))
|
||||
if m.hMaxRequestTimes.Max > 0 {
|
||||
entry.leftRequests.Store(int32(m.hMaxRequestTimes.Rand()))
|
||||
} else {
|
||||
entry.leftRequests.Store(1<<30 - 1)
|
||||
}
|
||||
if hMaxReusableSecs > 0 {
|
||||
entry.unreusableAt = now.Add(time.Duration(hMaxReusableSecs) * time.Second)
|
||||
if m.hMaxReusableSecs.Max > 0 {
|
||||
entry.unreusableAt = now.Add(time.Duration(m.hMaxReusableSecs.Rand()) * time.Second)
|
||||
}
|
||||
if cMaxReuseTimes > 0 {
|
||||
entry.maxReuseTimes = int32(cMaxReuseTimes)
|
||||
if m.cMaxReuseTimes.Max > 0 {
|
||||
entry.maxReuseTimes = int32(m.cMaxReuseTimes.Rand())
|
||||
}
|
||||
|
||||
m.entries = append(m.entries, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
func (m *ReuseManager) GetTransport() (*ReuseTransport, error) {
|
||||
func (m *ReuseManager) GetTransport() http.RoundTripper {
|
||||
now := time.Now()
|
||||
|
||||
m.mu.Lock()
|
||||
@@ -194,13 +198,13 @@ func (m *ReuseManager) GetTransport() (*ReuseTransport, error) {
|
||||
|
||||
m.cleanupLocked(now)
|
||||
|
||||
entry := m.pickLocked()
|
||||
var entry *reuseEntry
|
||||
if !m.shouldCreateLocked() {
|
||||
entry = m.pickLocked()
|
||||
}
|
||||
reused := entry != nil
|
||||
|
||||
if entry == nil {
|
||||
if !m.canCreateLocked() {
|
||||
return nil, fmt.Errorf("manager: no available connection")
|
||||
}
|
||||
transport := m.maker()
|
||||
entry = m.newEntryLocked(transport, now)
|
||||
}
|
||||
@@ -214,5 +218,5 @@ func (m *ReuseManager) GetTransport() (*ReuseTransport, error) {
|
||||
entry.leftRequests.Add(-1)
|
||||
}
|
||||
|
||||
return &ReuseTransport{entry: entry, manager: m}, nil
|
||||
return &ReuseTransport{entry: entry}
|
||||
}
|
||||
@@ -23,35 +23,29 @@ func makeTestTransportFactory(counter *atomic.Int64) TransportMaker {
|
||||
}
|
||||
}
|
||||
|
||||
func transportID(rt http.RoundTripper) int64 {
|
||||
return rt.(*testRoundTripper).id
|
||||
func transportID(rt *ReuseTransport) int64 {
|
||||
return rt.entry.transport.(*testRoundTripper).id
|
||||
}
|
||||
|
||||
func TestManagerReuseSameEntry(t *testing.T) {
|
||||
var created atomic.Int64
|
||||
|
||||
manager, err := NewReuseManager(&ReuseConfig{
|
||||
MaxConnections: "1",
|
||||
MaxConcurrency: "1",
|
||||
MaxConnections: "1",
|
||||
HMaxRequestTimes: "10",
|
||||
}, makeTestTransportFactory(&created))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport1, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id1 := transportID(transport1.entry.transport)
|
||||
transport1 := manager.GetTransport().(*ReuseTransport)
|
||||
id1 := transportID(transport1)
|
||||
|
||||
transport1.Close()
|
||||
|
||||
transport2, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id2 := transportID(transport2.entry.transport)
|
||||
transport2 := manager.GetTransport().(*ReuseTransport)
|
||||
id2 := transportID(transport2)
|
||||
|
||||
if id1 != id2 {
|
||||
t.Fatalf("expected same transport to be reused, got %d and %d", id1, id2)
|
||||
@@ -65,44 +59,46 @@ func TestManagerRespectMaxConnections(t *testing.T) {
|
||||
var created atomic.Int64
|
||||
|
||||
manager, err := NewReuseManager(&ReuseConfig{
|
||||
MaxConcurrency: "2",
|
||||
MaxConnections: "2",
|
||||
MaxConcurrency: "1",
|
||||
HMaxRequestTimes: "100",
|
||||
}, makeTestTransportFactory(&created))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport1, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if transport1 == nil {
|
||||
t.Fatal("expected first entry")
|
||||
transport1 := manager.GetTransport().(*ReuseTransport)
|
||||
id1 := transportID(transport1)
|
||||
transport2 := manager.GetTransport().(*ReuseTransport)
|
||||
id2 := transportID(transport2)
|
||||
transport3 := manager.GetTransport().(*ReuseTransport)
|
||||
id3 := transportID(transport3)
|
||||
transport4 := manager.GetTransport().(*ReuseTransport)
|
||||
id4 := transportID(transport4)
|
||||
transport5 := manager.GetTransport().(*ReuseTransport)
|
||||
id5 := transportID(transport5)
|
||||
|
||||
if id1 == id2 {
|
||||
t.Fatal("expected the second transport to be new")
|
||||
}
|
||||
|
||||
transport2, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if transport2 == nil {
|
||||
t.Fatal("expected second entry")
|
||||
if id3 != id1 && id3 != id2 {
|
||||
t.Fatal("expected the third transport to be reused")
|
||||
}
|
||||
|
||||
if transport1.entry == transport2.entry {
|
||||
t.Fatal("expected different entries for first two allocations")
|
||||
if id4 != id1 && id4 != id2 {
|
||||
t.Fatal("expected the fourth transport to be reused")
|
||||
}
|
||||
|
||||
transport3, err := manager.GetTransport()
|
||||
if err == nil {
|
||||
t.Fatal("expected error when max-connections reached and all entries are at max-concurrency")
|
||||
}
|
||||
if transport3 != nil {
|
||||
t.Fatal("expected nil entry on allocation failure")
|
||||
if id5 == id1 || id5 == id2 {
|
||||
t.Fatal("expected the fifth transport to be new")
|
||||
}
|
||||
|
||||
transport1.Close()
|
||||
transport2.Close()
|
||||
transport3.Close()
|
||||
transport4.Close()
|
||||
transport5.Close()
|
||||
manager.Close()
|
||||
}
|
||||
|
||||
@@ -110,27 +106,21 @@ func TestManagerRotateOnRequestLimit(t *testing.T) {
|
||||
var created atomic.Int64
|
||||
|
||||
manager, err := NewReuseManager(&ReuseConfig{
|
||||
MaxConnections: "1",
|
||||
MaxConcurrency: "1",
|
||||
MaxConnections: "1",
|
||||
HMaxRequestTimes: "1",
|
||||
}, makeTestTransportFactory(&created))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport1, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id1 := transportID(transport1.entry.transport)
|
||||
transport1 := manager.GetTransport().(*ReuseTransport)
|
||||
id1 := transportID(transport1)
|
||||
|
||||
transport1.Close()
|
||||
|
||||
transport2, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id2 := transportID(transport2.entry.transport)
|
||||
transport2 := manager.GetTransport().(*ReuseTransport)
|
||||
id2 := transportID(transport2)
|
||||
|
||||
if id1 == id2 {
|
||||
t.Fatalf("expected new transport after request limit, got same id %d", id1)
|
||||
@@ -144,8 +134,8 @@ func TestManagerRotateOnReusableSecs(t *testing.T) {
|
||||
var created atomic.Int64
|
||||
|
||||
manager, err := NewReuseManager(&ReuseConfig{
|
||||
MaxConnections: "1",
|
||||
MaxConcurrency: "1",
|
||||
MaxConnections: "1",
|
||||
HMaxRequestTimes: "100",
|
||||
HMaxReusableSecs: "1",
|
||||
}, makeTestTransportFactory(&created))
|
||||
@@ -153,20 +143,14 @@ func TestManagerRotateOnReusableSecs(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport1, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id1 := transportID(transport1.entry.transport)
|
||||
transport1 := manager.GetTransport().(*ReuseTransport)
|
||||
id1 := transportID(transport1)
|
||||
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
transport1.Close()
|
||||
|
||||
transport2, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id2 := transportID(transport2.entry.transport)
|
||||
transport2 := manager.GetTransport().(*ReuseTransport)
|
||||
id2 := transportID(transport2)
|
||||
|
||||
if id1 == id2 {
|
||||
t.Fatalf("expected new transport after reusable timeout, got same id %d", id1)
|
||||
@@ -180,8 +164,8 @@ func TestManagerRotateOnConnReuseLimit(t *testing.T) {
|
||||
var created atomic.Int64
|
||||
|
||||
manager, err := NewReuseManager(&ReuseConfig{
|
||||
MaxConnections: "1",
|
||||
MaxConcurrency: "1",
|
||||
MaxConnections: "1",
|
||||
CMaxReuseTimes: "1",
|
||||
HMaxRequestTimes: "100",
|
||||
}, makeTestTransportFactory(&created))
|
||||
@@ -189,19 +173,13 @@ func TestManagerRotateOnConnReuseLimit(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
transport1, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id1 := transportID(transport1.entry.transport)
|
||||
transport1 := manager.GetTransport().(*ReuseTransport)
|
||||
id1 := transportID(transport1)
|
||||
|
||||
transport1.Close()
|
||||
|
||||
transport2, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id2 := transportID(transport2.entry.transport)
|
||||
transport2 := manager.GetTransport().(*ReuseTransport)
|
||||
id2 := transportID(transport2)
|
||||
|
||||
if id1 != id2 {
|
||||
t.Fatalf("expected first reuse to use same transport, got %d and %d", id1, id2)
|
||||
@@ -209,11 +187,8 @@ func TestManagerRotateOnConnReuseLimit(t *testing.T) {
|
||||
|
||||
transport2.Close()
|
||||
|
||||
transport3, err := manager.GetTransport()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id3 := transportID(transport3.entry.transport)
|
||||
transport3 := manager.GetTransport().(*ReuseTransport)
|
||||
id3 := transportID(transport3)
|
||||
|
||||
if id3 == id2 {
|
||||
t.Fatalf("expected new transport after c-max-reuse-times limit, got same id %d", id3)
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user