mihomo/adapter/outbound/hysteria.go

279 lines
7.3 KiB
Go
Raw Normal View History

2022-06-07 13:38:45 +08:00
package outbound
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
2022-07-11 12:37:27 +08:00
tlsC "github.com/Dreamacro/clash/component/tls"
"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"
2022-06-07 13:38:45 +08:00
"io/ioutil"
"net"
"regexp"
"strconv"
"time"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
2022-06-07 13:38:45 +08:00
"github.com/lucas-clemente/quic-go"
"github.com/lucas-clemente/quic-go/congestion"
M "github.com/sagernet/sing/common/metadata"
)
const (
mbpsToBps = 125000
minSpeedBPS = 16384
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
DefaultMaxIncomingStreams = 1024
2022-06-08 01:47:50 +08:00
DefaultALPN = "hysteria"
DefaultProtocol = "udp"
2022-06-07 13:38:45 +08:00
)
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
type Hysteria struct {
*Base
client *core.Client
2022-06-07 13:38:45 +08:00
}
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
hdc := hyDialerWithContext{
ctx: context.Background(),
hyDialer: func() (net.PacketConn, error) {
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
},
}
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), &hdc)
2022-06-07 13:38:45 +08:00
if err != nil {
return nil, err
}
2022-06-07 13:38:45 +08:00
return NewConn(tcpConn, h), nil
}
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
hdc := hyDialerWithContext{
ctx: context.Background(),
hyDialer: func() (net.PacketConn, error) {
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
},
}
udpConn, err := h.client.DialUDP(&hdc)
2022-06-07 13:38:45 +08:00
if err != nil {
return nil, err
}
return newPacketConn(&hyPacketConn{udpConn}, h), nil
}
type HysteriaOption struct {
BasicOption
2022-06-07 17:19:25 +08:00
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Protocol string `proxy:"protocol,omitempty"`
Up string `proxy:"up"`
Down string `proxy:"down"`
2022-06-07 17:19:25 +08:00
AuthString string `proxy:"auth_str,omitempty"`
Obfs string `proxy:"obfs,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
ALPN string `proxy:"alpn,omitempty"`
CustomCA string `proxy:"ca,omitempty"`
CustomCAString string `proxy:"ca_str,omitempty"`
2022-06-08 01:47:50 +08:00
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
ReceiveWindow int `proxy:"recv_window,omitempty"`
2022-06-07 17:19:25 +08:00
DisableMTUDiscovery bool `proxy:"disable_mtu_discovery,omitempty"`
2022-06-07 13:38:45 +08:00
}
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
var up, down uint64
up = stringToBps(c.Up)
if up == 0 {
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
}
down = stringToBps(c.Down)
2022-06-25 12:43:47 +08:00
if down == 0 {
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
}
2022-06-07 13:38:45 +08: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))
2022-06-08 01:47:50 +08:00
serverName := option.Server
if option.SNI != "" {
2022-06-12 00:00:42 +08:00
serverName = option.SNI
2022-06-08 01:47:50 +08:00
}
2022-07-10 20:44:24 +08:00
tlsConfig := tlsC.MixinTLSConfig(&tls.Config{
2022-06-08 01:47:50 +08:00
ServerName: serverName,
2022-06-07 13:38:45 +08:00
InsecureSkipVerify: option.SkipCertVerify,
MinVersion: tls.VersionTLS13,
2022-07-10 20:44:24 +08:00
})
2022-06-07 13:38:45 +08:00
if len(option.ALPN) > 0 {
2022-06-07 17:19:25 +08:00
tlsConfig.NextProtos = []string{option.ALPN}
2022-06-07 13:38:45 +08:00
} else {
tlsConfig.NextProtos = []string{DefaultALPN}
}
if len(option.CustomCA) > 0 {
bs, err := ioutil.ReadFile(option.CustomCA)
if err != nil {
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(bs) {
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
}
tlsConfig.RootCAs = cp
} else if option.CustomCAString != "" {
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM([]byte(option.CustomCAString)) {
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
}
tlsConfig.RootCAs = cp
}
quicConfig := &quic.Config{
2022-06-08 01:47:50 +08:00
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
KeepAlivePeriod: 10 * time.Second,
2022-06-07 13:38:45 +08:00
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
EnableDatagrams: true,
}
2022-06-08 01:47:50 +08:00
if option.Protocol == "" {
option.Protocol = DefaultProtocol
}
2022-06-07 13:38:45 +08:00
if option.ReceiveWindowConn == 0 {
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
}
if option.ReceiveWindow == 0 {
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow
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)
2022-06-07 13:38:45 +08: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
}
2022-06-07 13:38:45 +08:00
client, err := core.NewClient(
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
}, obfuscator,
)
if err != nil {
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
}
return &Hysteria{
Base: &Base{
name: option.Name,
addr: addr,
tp: C.Hysteria,
2022-06-08 01:47:50 +08:00
udp: true,
2022-06-07 13:38:45 +08:00
iface: option.Interface,
rmark: option.RoutingMark,
},
client: client,
2022-06-07 13:38:45 +08:00
}, nil
}
func stringToBps(s string) uint64 {
if s == "" {
return 0
}
// when have not unit, use Mbps
if v, err := strconv.Atoi(s); err == nil {
return stringToBps(fmt.Sprintf("%d Mbps", v))
}
2022-06-07 13:38:45 +08:00
m := rateStringRegexp.FindStringSubmatch(s)
if m == nil {
return 0
}
var n uint64
switch m[2] {
case "K":
n = 1 << 10
case "M":
n = 1 << 20
case "G":
n = 1 << 30
case "T":
n = 1 << 40
default:
n = 1
}
v, _ := strconv.ParseUint(m[1], 10, 64)
n = v * n
if m[3] == "b" {
// Bits, need to convert to bytes
n = n >> 3
}
return n
}
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) 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 15:49:10 +08:00
type hyDialerWithContext struct {
hyDialer func() (net.PacketConn, error)
ctx context.Context
}
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
return h.hyDialer()
}
2022-06-07 15:49:10 +08:00
func (h *hyDialerWithContext) Context() context.Context {
return h.ctx
2022-06-07 15:49:10 +08:00
}