mihomo/adapter/outbound/vmess.go

531 lines
15 KiB
Go
Raw Normal View History

2019-12-08 12:17:24 +08:00
package outbound
2018-09-06 10:53:29 +08:00
import (
"context"
"crypto/tls"
2020-02-17 17:34:19 +08:00
"errors"
2018-09-06 10:53:29 +08:00
"fmt"
"net"
"net/http"
2018-09-06 10:53:29 +08:00
"strconv"
"strings"
2022-06-28 08:12:40 +08:00
"sync"
2018-09-06 10:53:29 +08:00
N "github.com/Dreamacro/clash/common/net"
2023-06-07 23:03:36 +08:00
"github.com/Dreamacro/clash/common/utils"
2023-09-22 14:45:34 +08:00
"github.com/Dreamacro/clash/component/ca"
"github.com/Dreamacro/clash/component/dialer"
"github.com/Dreamacro/clash/component/proxydialer"
2020-02-17 17:34:19 +08:00
"github.com/Dreamacro/clash/component/resolver"
tlsC "github.com/Dreamacro/clash/component/tls"
2018-09-06 10:53:29 +08:00
C "github.com/Dreamacro/clash/constant"
2023-09-01 03:11:35 +08:00
"github.com/Dreamacro/clash/ntp"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/gun"
clashVMess "github.com/Dreamacro/clash/transport/vmess"
2023-06-19 08:23:48 +08:00
vmess "github.com/metacubex/sing-vmess"
"github.com/metacubex/sing-vmess/packetaddr"
M "github.com/sagernet/sing/common/metadata"
2018-09-06 10:53:29 +08:00
)
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
2018-09-06 10:53:29 +08:00
type Vmess struct {
2018-12-22 23:56:42 +08:00
*Base
2018-09-06 10:53:29 +08:00
client *vmess.Client
option *VmessOption
// for gun mux
gunTLSConfig *tls.Config
gunConfig *gun.Config
transport *gun.TransportWrap
2023-03-08 17:18:46 +08:00
realityConfig *tlsC.RealityConfig
2018-09-06 10:53:29 +08:00
}
type VmessOption struct {
BasicOption
2023-03-08 17:18:46 +08:00
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UUID string `proxy:"uuid"`
AlterID int `proxy:"alterId"`
Cipher string `proxy:"cipher"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
TLS bool `proxy:"tls,omitempty"`
2023-08-14 15:48:13 +08:00
ALPN []string `proxy:"alpn,omitempty"`
2023-03-08 17:18:46 +08:00
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Fingerprint string `proxy:"fingerprint,omitempty"`
ServerName string `proxy:"servername,omitempty"`
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
PacketAddr bool `proxy:"packet-addr,omitempty"`
XUDP bool `proxy:"xudp,omitempty"`
PacketEncoding string `proxy:"packet-encoding,omitempty"`
GlobalPadding bool `proxy:"global-padding,omitempty"`
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
}
type HTTPOptions struct {
Method string `proxy:"method,omitempty"`
Path []string `proxy:"path,omitempty"`
Headers map[string][]string `proxy:"headers,omitempty"`
}
type HTTP2Options struct {
Host []string `proxy:"host,omitempty"`
Path string `proxy:"path,omitempty"`
}
type GrpcOptions struct {
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
}
type WSOptions struct {
Path string `proxy:"path,omitempty"`
Headers map[string]string `proxy:"headers,omitempty"`
MaxEarlyData int `proxy:"max-early-data,omitempty"`
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
}
// StreamConnContext implements C.ProxyAdapter
func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
var err error
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
}
switch v.option.Network {
case "ws":
host, port, _ := net.SplitHostPort(v.addr)
wsOpts := &clashVMess.WebsocketConfig{
Host: host,
Port: port,
Path: v.option.WSOpts.Path,
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
ClientFingerprint: v.option.ClientFingerprint,
Headers: http.Header{},
}
if len(v.option.WSOpts.Headers) != 0 {
for key, value := range v.option.WSOpts.Headers {
2022-06-09 16:23:06 +08:00
wsOpts.Headers.Add(key, value)
}
}
if v.option.TLS {
wsOpts.TLS = true
2022-07-11 13:42:28 +08:00
tlsConfig := &tls.Config{
2021-10-16 20:19:59 +08:00
ServerName: host,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
2022-07-11 13:42:28 +08:00
}
2023-09-22 14:45:34 +08:00
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
if err != nil {
return nil, err
2022-07-11 13:42:28 +08:00
}
2021-10-16 20:19:59 +08:00
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
}
}
c, err = clashVMess.StreamWebsocketConn(ctx, c, wsOpts)
case "http":
// readability first, so just copy default TLS logic
if v.option.TLS {
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := &clashVMess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
ClientFingerprint: v.option.ClientFingerprint,
2023-03-08 17:18:46 +08:00
Reality: v.realityConfig,
2023-08-14 15:48:13 +08:00
NextProtos: v.option.ALPN,
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
if err != nil {
return nil, err
}
}
host, _, _ := net.SplitHostPort(v.addr)
httpOpts := &clashVMess.HTTPConfig{
Host: host,
Method: v.option.HTTPOpts.Method,
Path: v.option.HTTPOpts.Path,
Headers: v.option.HTTPOpts.Headers,
}
c = clashVMess.StreamHTTPConn(c, httpOpts)
case "h2":
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := clashVMess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NextProtos: []string{"h2"},
ClientFingerprint: v.option.ClientFingerprint,
2023-03-08 17:18:46 +08:00
Reality: v.realityConfig,
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = clashVMess.StreamTLSConn(ctx, c, &tlsOpts)
if err != nil {
return nil, err
}
h2Opts := &clashVMess.H2Config{
Hosts: v.option.HTTP2Opts.Host,
Path: v.option.HTTP2Opts.Path,
}
c, err = clashVMess.StreamH2Conn(c, h2Opts)
case "grpc":
2023-03-10 10:01:05 +08:00
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
2020-04-03 16:04:24 +08:00
default:
// handle TLS
if v.option.TLS {
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := &clashVMess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
ClientFingerprint: v.option.ClientFingerprint,
2023-03-08 17:18:46 +08:00
Reality: v.realityConfig,
2023-08-14 15:48:13 +08:00
NextProtos: v.option.ALPN,
2020-04-03 16:04:24 +08:00
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
2020-04-03 16:04:24 +08:00
}
}
if err != nil {
return nil, err
}
return v.streamConn(c, metadata)
}
func (v *Vmess) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
if metadata.NetWork == C.UDP {
2022-09-19 18:26:43 +08:00
if v.option.XUDP {
var globalID [8]byte
if metadata.SourceValid() {
globalID = utils.GlobalID(metadata.SourceAddress())
}
if N.NeedHandshake(c) {
2023-06-07 23:03:36 +08:00
conn = v.client.DialEarlyXUDPPacketConn(c,
globalID,
2023-06-07 23:03:36 +08:00
M.SocksaddrFromNet(metadata.UDPAddr()))
} else {
2023-06-07 23:03:36 +08:00
conn, err = v.client.DialXUDPPacketConn(c,
globalID,
2023-06-07 23:03:36 +08:00
M.SocksaddrFromNet(metadata.UDPAddr()))
}
} else if v.option.PacketAddr {
if N.NeedHandshake(c) {
2023-06-07 23:03:36 +08:00
conn = v.client.DialEarlyPacketConn(c,
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
} else {
2023-06-07 23:03:36 +08:00
conn, err = v.client.DialPacketConn(c,
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
}
conn = packetaddr.NewBindConn(conn)
2022-09-19 18:26:43 +08:00
} else {
if N.NeedHandshake(c) {
2023-06-07 23:03:36 +08:00
conn = v.client.DialEarlyPacketConn(c,
M.SocksaddrFromNet(metadata.UDPAddr()))
} else {
2023-06-07 23:03:36 +08:00
conn, err = v.client.DialPacketConn(c,
M.SocksaddrFromNet(metadata.UDPAddr()))
}
2022-09-19 18:26:43 +08:00
}
} else {
if N.NeedHandshake(c) {
2023-06-07 23:03:36 +08:00
conn = v.client.DialEarlyConn(c,
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
} else {
2023-06-07 23:03:36 +08:00
conn, err = v.client.DialConn(c,
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
}
}
if err != nil {
conn = nil
}
return
}
2021-04-29 11:23:14 +08:00
// DialContext implements C.ProxyAdapter
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
// gun transport
if v.transport != nil && len(opts) == 0 {
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
if err != nil {
return nil, err
}
defer func(c net.Conn) {
2022-12-13 13:20:40 +08:00
safeConnClose(c, err)
}(c)
c, err = v.client.DialConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
if err != nil {
return nil, err
}
return NewConn(c, v), nil
}
2022-12-20 00:11:02 +08:00
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
2022-12-19 21:34:07 +08:00
}
2022-12-19 21:34:07 +08:00
// DialContextWithDialer implements C.ProxyAdapter
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
if len(v.option.DialerProxy) > 0 {
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
if err != nil {
return nil, err
}
}
2022-12-19 21:34:07 +08:00
c, err := dialer.DialContext(ctx, "tcp", v.addr)
2018-09-06 10:53:29 +08:00
if err != nil {
2020-06-11 22:07:20 +08:00
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
2018-09-06 10:53:29 +08:00
}
N.TCPKeepAlive(c)
2022-12-16 22:15:44 +08:00
defer func(c net.Conn) {
2022-12-13 13:20:40 +08:00
safeConnClose(c, err)
2022-12-16 22:15:44 +08:00
}(c)
c, err = v.StreamConnContext(ctx, c, metadata)
return NewConn(c, v), err
2018-11-21 13:47:46 +08:00
}
// ListenPacketContext implements C.ProxyAdapter
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
2020-02-17 17:34:19 +08:00
if !metadata.Resolved() {
ip, err := resolver.ResolveIP(ctx, metadata.Host)
2020-02-17 17:34:19 +08:00
if err != nil {
return nil, errors.New("can't resolve ip")
}
metadata.DstIP = ip
}
var c net.Conn
// gun transport
if v.transport != nil && len(opts) == 0 {
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
if err != nil {
return nil, err
}
defer func(c net.Conn) {
2022-12-13 13:20:40 +08:00
safeConnClose(c, err)
}(c)
c, err = v.streamConn(c, metadata)
if err != nil {
2022-12-19 21:34:07 +08:00
return nil, fmt.Errorf("new vmess client error: %v", err)
}
return v.ListenPacketOnStreamConn(ctx, c, metadata)
2022-12-19 21:34:07 +08:00
}
2022-12-20 00:11:02 +08:00
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
2022-12-19 21:34:07 +08:00
}
2022-12-19 21:34:07 +08:00
// ListenPacketWithDialer implements C.ProxyAdapter
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
if len(v.option.DialerProxy) > 0 {
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
if err != nil {
return nil, err
}
}
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
2022-12-19 21:34:07 +08:00
if !metadata.Resolved() {
ip, err := resolver.ResolveIP(ctx, metadata.Host)
if err != nil {
return nil, errors.New("can't resolve ip")
}
metadata.DstIP = ip
}
2022-12-19 21:34:07 +08:00
c, err := dialer.DialContext(ctx, "tcp", v.addr)
if err != nil {
2023-01-10 13:21:32 +08:00
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
}
N.TCPKeepAlive(c)
2023-01-10 13:21:32 +08:00
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = v.StreamConnContext(ctx, c, metadata)
2023-01-10 13:21:32 +08:00
if err != nil {
return nil, fmt.Errorf("new vmess client error: %v", err)
}
return v.ListenPacketOnStreamConn(ctx, c, metadata)
2022-12-19 21:34:07 +08:00
}
// SupportWithDialer implements C.ProxyAdapter
func (v *Vmess) SupportWithDialer() C.NetWork {
return C.ALLNet
}
// ListenPacketOnStreamConn implements C.ProxyAdapter
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
if !metadata.Resolved() {
ip, err := resolver.ResolveIP(ctx, metadata.Host)
if err != nil {
return nil, errors.New("can't resolve ip")
}
metadata.DstIP = ip
}
if pc, ok := c.(net.PacketConn); ok {
2023-05-11 15:34:28 +08:00
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
}
2020-02-17 17:34:19 +08:00
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
2019-04-25 16:32:15 +08:00
}
// SupportUOT implements C.ProxyAdapter
func (v *Vmess) SupportUOT() bool {
return true
}
func NewVmess(option VmessOption) (*Vmess, error) {
security := strings.ToLower(option.Cipher)
var options []vmess.ClientOption
2022-10-02 22:42:33 +08:00
if option.GlobalPadding {
options = append(options, vmess.ClientWithGlobalPadding())
}
if option.AuthenticatedLength {
options = append(options, vmess.ClientWithAuthenticatedLength())
}
2023-09-01 03:11:35 +08:00
options = append(options, vmess.ClientWithTimeFunc(ntp.Now))
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
2018-09-06 10:53:29 +08:00
if err != nil {
return nil, err
}
2022-09-19 18:26:43 +08:00
switch option.PacketEncoding {
2022-10-02 21:10:29 +08:00
case "packetaddr", "packet":
2022-09-19 18:26:43 +08:00
option.PacketAddr = true
case "xudp":
option.XUDP = true
}
if option.XUDP {
option.PacketAddr = false
}
v := &Vmess{
2018-12-22 23:56:42 +08:00
Base: &Base{
2022-08-28 13:41:19 +08:00
name: option.Name,
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
tp: C.Vmess,
udp: option.UDP,
xudp: option.XUDP,
2023-02-24 13:53:44 +08:00
tfo: option.TFO,
2023-08-09 16:57:39 +08:00
mpTcp: option.MPTCP,
2022-08-28 13:41:19 +08:00
iface: option.Interface,
rmark: option.RoutingMark,
prefer: C.NewDNSPrefer(option.IPVersion),
2018-12-22 23:56:42 +08:00
},
2018-09-06 10:53:29 +08:00
client: client,
option: &option,
}
switch option.Network {
case "h2":
if len(option.HTTP2Opts.Host) == 0 {
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
}
case "grpc":
dialFn := func(network, addr string) (net.Conn, error) {
var err error
var cDialer C.Dialer = dialer.NewDialer(v.Base.DialOptions()...)
if len(v.option.DialerProxy) > 0 {
cDialer, err = proxydialer.NewByName(v.option.DialerProxy, cDialer)
if err != nil {
return nil, err
}
}
c, err := cDialer.DialContext(context.Background(), "tcp", v.addr)
if err != nil {
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
}
N.TCPKeepAlive(c)
return c, nil
}
gunConfig := &gun.Config{
ServiceName: v.option.GrpcOpts.GrpcServiceName,
Host: v.option.ServerName,
ClientFingerprint: v.option.ClientFingerprint,
}
2023-05-13 09:38:14 +08:00
if option.ServerName == "" {
gunConfig.Host = v.addr
}
2023-05-13 09:38:14 +08:00
var tlsConfig *tls.Config
if option.TLS {
2023-09-22 14:45:34 +08:00
tlsConfig = ca.GetGlobalTLSConfig(&tls.Config{
2023-05-13 09:38:14 +08:00
InsecureSkipVerify: v.option.SkipCertVerify,
ServerName: v.option.ServerName,
})
if option.ServerName == "" {
host, _, _ := net.SplitHostPort(v.addr)
tlsConfig.ServerName = host
}
}
v.gunTLSConfig = tlsConfig
v.gunConfig = gunConfig
2023-03-10 10:01:05 +08:00
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
2023-03-08 17:18:46 +08:00
}
2023-03-08 17:18:46 +08:00
v.realityConfig, err = v.option.RealityOpts.Parse()
if err != nil {
return nil, err
}
2023-03-08 17:18:46 +08:00
return v, nil
2018-09-06 10:53:29 +08:00
}
2020-02-17 17:34:19 +08:00
type vmessPacketConn struct {
2019-10-11 20:11:18 +08:00
net.Conn
2022-06-28 08:12:40 +08:00
rAddr net.Addr
access sync.Mutex
2019-10-11 20:11:18 +08:00
}
// WriteTo implments C.PacketConn.WriteTo
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
2020-02-17 17:34:19 +08:00
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
allowedAddr := uc.rAddr
destAddr := addr
if allowedAddr.String() != destAddr.String() {
return 0, ErrUDPRemoteAddrMismatch
}
2022-06-28 08:12:40 +08:00
uc.access.Lock()
defer uc.access.Unlock()
2019-10-11 20:11:18 +08:00
return uc.Conn.Write(b)
}
2020-02-17 17:34:19 +08:00
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
2019-10-11 20:11:18 +08:00
n, err := uc.Conn.Read(b)
return n, uc.rAddr, err
2019-10-11 20:11:18 +08:00
}