tls.go 1.9 KB

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