clash/adapter/outbound/hysteria.go

322 lines
9.2 KiB
Go
Raw Normal View History

2022-06-07 05:38:45 +00:00
package outbound
import (
"context"
2022-07-12 06:32:34 +00:00
"crypto/sha256"
2022-06-07 05:38:45 +00:00
"crypto/tls"
"encoding/base64"
2022-07-12 06:32:34 +00:00
"encoding/hex"
"encoding/pem"
2022-06-07 05:38:45 +00:00
"fmt"
"net"
2022-12-11 01:25:46 +00:00
"net/netip"
2022-08-11 15:56:50 +00:00
"os"
2022-06-07 05:38:45 +00:00
"strconv"
"time"
"github.com/metacubex/quic-go"
"github.com/metacubex/quic-go/congestion"
M "github.com/sagernet/sing/common/metadata"
2022-06-07 05:38:45 +00:00
"github.com/Dreamacro/clash/component/dialer"
"github.com/Dreamacro/clash/component/proxydialer"
tlsC "github.com/Dreamacro/clash/component/tls"
2022-06-07 05:38:45 +00:00
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
"github.com/Dreamacro/clash/transport/hysteria/core"
"github.com/Dreamacro/clash/transport/hysteria/obfs"
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
"github.com/Dreamacro/clash/transport/hysteria/transport"
"github.com/Dreamacro/clash/transport/hysteria/utils"
2022-06-07 05:38:45 +00:00
)
const (
mbpsToBps = 125000
2022-06-07 05:38:45 +00:00
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
DefaultALPN = "hysteria"
DefaultProtocol = "udp"
DefaultHopInterval = 10
2022-06-07 05:38:45 +00:00
)
type Hysteria struct {
*Base
option *HysteriaOption
client *core.Client
2022-06-07 05:38:45 +00:00
}
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), h.genHdc(ctx, opts...))
2022-06-07 05:38:45 +00:00
if err != nil {
return nil, err
}
2022-06-07 05:38:45 +00:00
return NewConn(tcpConn, h), nil
}
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
udpConn, err := h.client.DialUDP(h.genHdc(ctx, opts...))
if err != nil {
return nil, err
}
return newPacketConn(&hyPacketConn{udpConn}, h), nil
}
func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.PacketDialer {
return &hyDialerWithContext{
ctx: context.Background(),
2022-12-11 01:25:46 +00:00
hyDialer: func(network string) (net.PacketConn, error) {
var err error
var cDialer C.Dialer = dialer.NewDialer(h.Base.DialOptions(opts...)...)
if len(h.option.DialerProxy) > 0 {
cDialer, err = proxydialer.NewByName(h.option.DialerProxy, cDialer)
if err != nil {
return nil, err
}
}
rAddrPort, _ := netip.ParseAddrPort(h.Addr())
return cDialer.ListenPacket(ctx, network, "", rAddrPort)
},
2022-08-29 04:10:46 +00:00
remoteAddr: func(addr string) (net.Addr, error) {
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
2022-08-29 04:10:46 +00:00
},
}
2022-06-07 05:38:45 +00:00
}
type HysteriaOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port,omitempty"`
2022-11-27 04:52:14 +00:00
Ports string `proxy:"ports,omitempty"`
Protocol string `proxy:"protocol,omitempty"`
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
Up string `proxy:"up"`
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
Down string `proxy:"down"`
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
Auth string `proxy:"auth,omitempty"`
AuthString string `proxy:"auth-str,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
ALPN []string `proxy:"alpn,omitempty"`
CustomCA string `proxy:"ca,omitempty"`
CustomCAString string `proxy:"ca-str,omitempty"`
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
ReceiveWindow int `proxy:"recv-window,omitempty"`
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
FastOpen bool `proxy:"fast-open,omitempty"`
HopInterval int `proxy:"hop-interval,omitempty"`
2022-06-07 05:38:45 +00:00
}
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
var up, down uint64
2023-09-21 06:52:26 +00:00
up = StringToBps(c.Up)
if up == 0 {
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
}
2023-09-21 06:52:26 +00:00
down = StringToBps(c.Down)
2022-06-25 04:43:47 +00:00
if down == 0 {
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
}
2022-06-07 05:38:45 +00:00
return up, down, nil
}
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
clientTransport := &transport.ClientTransport{
Dialer: &net.Dialer{
Timeout: 8 * time.Second,
},
}
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
ports := option.Ports
2022-06-07 05:38:45 +00:00
2022-06-07 17:47:50 +00:00
serverName := option.Server
if option.SNI != "" {
2022-06-11 16:00:42 +00:00
serverName = option.SNI
2022-06-07 17:47:50 +00:00
}
2022-07-11 05:42:28 +00:00
tlsConfig := &tls.Config{
2022-06-07 17:47:50 +00:00
ServerName: serverName,
2022-06-07 05:38:45 +00:00
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
2022-07-11 05:42:28 +00:00
}
2022-07-12 06:32:34 +00:00
var bs []byte
var err error
if len(option.CustomCA) > 0 {
2022-08-11 15:56:50 +00:00
bs, err = os.ReadFile(option.CustomCA)
2022-07-12 06:32:34 +00:00
if err != nil {
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
}
} else if option.CustomCAString != "" {
bs = []byte(option.CustomCAString)
2022-07-12 06:32:34 +00:00
}
if len(bs) > 0 {
block, _ := pem.Decode(bs)
if block == nil {
return nil, fmt.Errorf("CA cert is not PEM")
}
fpBytes := sha256.Sum256(block.Bytes)
if len(option.Fingerprint) == 0 {
option.Fingerprint = hex.EncodeToString(fpBytes[:])
}
}
2022-07-11 05:42:28 +00:00
if len(option.Fingerprint) != 0 {
var err error
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
if err != nil {
return nil, err
}
} else {
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
2022-07-11 05:42:28 +00:00
}
2022-06-07 05:38:45 +00:00
if len(option.ALPN) > 0 {
tlsConfig.NextProtos = option.ALPN
2022-06-07 05:38:45 +00:00
} else {
tlsConfig.NextProtos = []string{DefaultALPN}
}
quicConfig := &quic.Config{
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
KeepAlivePeriod: 10 * time.Second,
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
2022-06-07 05:38:45 +00:00
EnableDatagrams: true,
}
if option.ObfsProtocol != "" {
option.Protocol = option.ObfsProtocol
}
2022-06-07 17:47:50 +00:00
if option.Protocol == "" {
option.Protocol = DefaultProtocol
}
if option.HopInterval == 0 {
option.HopInterval = DefaultHopInterval
}
hopInterval := time.Duration(int64(option.HopInterval)) * time.Second
if option.ReceiveWindow == 0 {
2022-08-28 05:41:19 +00:00
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
2022-06-07 05:38:45 +00:00
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
}
if option.ReceiveWindow == 0 {
2022-08-28 05:41:19 +00:00
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow / 10
2022-06-07 05:38:45 +00:00
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
}
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
}
var auth = []byte(option.AuthString)
if option.Auth != "" {
auth, err = base64.StdEncoding.DecodeString(option.Auth)
if err != nil {
return nil, err
}
}
2022-06-07 05:38:45 +00:00
var obfuscator obfs.Obfuscator
if len(option.Obfs) > 0 {
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
}
up, down, err := option.Speed()
if err != nil {
return nil, err
}
if option.UpSpeed != 0 {
up = uint64(option.UpSpeed * mbpsToBps)
}
if option.DownSpeed != 0 {
down = uint64(option.DownSpeed * mbpsToBps)
}
2022-06-07 05:38:45 +00:00
client, err := core.NewClient(
addr, ports, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
2022-06-07 05:38:45 +00:00
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
}, obfuscator, hopInterval, option.FastOpen,
2022-06-07 05:38:45 +00:00
)
if err != nil {
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
}
return &Hysteria{
Base: &Base{
2022-08-28 05:41:19 +00:00
name: option.Name,
addr: addr,
tp: C.Hysteria,
udp: true,
tfo: option.FastOpen,
2022-08-28 05:41:19 +00:00
iface: option.Interface,
rmark: option.RoutingMark,
prefer: C.NewDNSPrefer(option.IPVersion),
2022-06-07 05:38:45 +00:00
},
option: &option,
client: client,
2022-06-07 05:38:45 +00:00
}, nil
}
type hyPacketConn struct {
core.UDPConn
}
func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
b, addrStr, err := c.UDPConn.ReadFrom()
if err != nil {
return
}
n = copy(p, b)
addr = M.ParseSocksaddr(addrStr).UDPAddr()
return
}
func (c *hyPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
b, addrStr, err := c.UDPConn.ReadFrom()
if err != nil {
return
}
data = b
addr = M.ParseSocksaddr(addrStr).UDPAddr()
return
}
2022-06-07 05:38:45 +00:00
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
if err != nil {
return
}
n = len(p)
return
}
2022-06-07 07:49:10 +00:00
type hyDialerWithContext struct {
2022-12-11 01:25:46 +00:00
hyDialer func(network string) (net.PacketConn, error)
2022-08-28 05:41:19 +00:00
ctx context.Context
remoteAddr func(host string) (net.Addr, error)
}
2022-12-11 05:41:44 +00:00
func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, error) {
network := "udp"
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
network = dialer.ParseNetwork(network, addrPort.Addr())
2022-12-11 05:41:44 +00:00
}
return h.hyDialer(network)
}
2022-06-07 07:49:10 +00:00
func (h *hyDialerWithContext) Context() context.Context {
return h.ctx
2022-06-07 07:49:10 +00:00
}
2022-08-28 05:41:19 +00:00
func (h *hyDialerWithContext) RemoteAddr(host string) (net.Addr, error) {
2022-12-11 05:41:44 +00:00
return h.remoteAddr(host)
2022-08-28 05:41:19 +00:00
}