github.com/yaling888/clash@v1.53.0/transport/v2ray-plugin/websocket.go (about)

     1  package obfs
     2  
     3  import (
     4  	"crypto/tls"
     5  	"net"
     6  	"net/http"
     7  
     8  	"github.com/yaling888/clash/common/convert"
     9  	"github.com/yaling888/clash/transport/vmess"
    10  )
    11  
    12  // Option is options of websocket obfs
    13  type Option struct {
    14  	Host           string
    15  	Port           string
    16  	Path           string
    17  	Headers        map[string]string
    18  	TLS            bool
    19  	SkipCertVerify bool
    20  	Mux            bool
    21  	RandomHost     bool
    22  }
    23  
    24  // NewV2rayObfs return a HTTPObfs
    25  func NewV2rayObfs(conn net.Conn, option *Option) (net.Conn, error) {
    26  	header := http.Header{}
    27  	for k, v := range option.Headers {
    28  		header.Add(k, v)
    29  	}
    30  
    31  	config := &vmess.WebsocketConfig{
    32  		Host:    option.Host,
    33  		Port:    option.Port,
    34  		Path:    option.Path,
    35  		Headers: header,
    36  	}
    37  
    38  	if option.TLS {
    39  		config.TLS = true
    40  		config.TLSConfig = &tls.Config{
    41  			ServerName:         option.Host,
    42  			InsecureSkipVerify: option.SkipCertVerify,
    43  			NextProtos:         []string{"http/1.1"},
    44  		}
    45  		if host := config.Headers.Get("Host"); host != "" {
    46  			config.TLSConfig.ServerName = host
    47  		}
    48  	} else if option.RandomHost {
    49  		config.Headers.Set("Host", convert.RandHost())
    50  	}
    51  
    52  	if config.Headers.Get("User-Agent") == "" {
    53  		config.Headers.Set("User-Agent", convert.RandUserAgent())
    54  	}
    55  
    56  	var err error
    57  	conn, err = vmess.StreamWebsocketConn(conn, config)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	if option.Mux {
    63  		conn = NewMux(conn, MuxOption{
    64  			ID:   [2]byte{0, 0},
    65  			Host: "127.0.0.1",
    66  			Port: 0,
    67  		})
    68  	}
    69  	return conn, nil
    70  }