github.com/eagleql/xray-core@v1.4.4/transport/internet/tls/tls.go (about) 1 package tls 2 3 import ( 4 "crypto/tls" 5 6 utls "github.com/refraction-networking/utls" 7 8 "github.com/eagleql/xray-core/common/buf" 9 "github.com/eagleql/xray-core/common/net" 10 ) 11 12 //go:generate go run github.com/eagleql/xray-core/common/errors/errorgen 13 14 var ( 15 _ buf.Writer = (*Conn)(nil) 16 ) 17 18 type Conn struct { 19 *tls.Conn 20 } 21 22 func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error { 23 mb = buf.Compact(mb) 24 mb, err := buf.WriteMultiBuffer(c, mb) 25 buf.ReleaseMulti(mb) 26 return err 27 } 28 29 func (c *Conn) HandshakeAddress() net.Address { 30 if err := c.Handshake(); err != nil { 31 return nil 32 } 33 state := c.ConnectionState() 34 if state.ServerName == "" { 35 return nil 36 } 37 return net.ParseAddress(state.ServerName) 38 } 39 40 // Client initiates a TLS client handshake on the given connection. 41 func Client(c net.Conn, config *tls.Config) net.Conn { 42 tlsConn := tls.Client(c, config) 43 return &Conn{Conn: tlsConn} 44 } 45 46 // Server initiates a TLS server handshake on the given connection. 47 func Server(c net.Conn, config *tls.Config) net.Conn { 48 tlsConn := tls.Server(c, config) 49 return &Conn{Conn: tlsConn} 50 } 51 52 type UConn struct { 53 *utls.UConn 54 } 55 56 func (c *UConn) HandshakeAddress() net.Address { 57 if err := c.Handshake(); err != nil { 58 return nil 59 } 60 state := c.ConnectionState() 61 if state.ServerName == "" { 62 return nil 63 } 64 return net.ParseAddress(state.ServerName) 65 } 66 67 func UClient(c net.Conn, config *tls.Config, fingerprint *utls.ClientHelloID) net.Conn { 68 utlsConn := utls.UClient(c, copyConfig(config), *fingerprint) 69 return &UConn{UConn: utlsConn} 70 } 71 72 func copyConfig(c *tls.Config) *utls.Config { 73 return &utls.Config{ 74 RootCAs: c.RootCAs, 75 ServerName: c.ServerName, 76 InsecureSkipVerify: c.InsecureSkipVerify, 77 } 78 } 79 80 var Fingerprints = map[string]*utls.ClientHelloID{ 81 "chrome": &utls.HelloChrome_Auto, 82 "firefox": &utls.HelloFirefox_Auto, 83 "safari": &utls.HelloIOS_Auto, 84 "randomized": &utls.HelloRandomized, 85 }