tls.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // +build !confonly
  2. package tls
  3. import (
  4. "crypto/tls"
  5. "v2ray.com/core/common/buf"
  6. "v2ray.com/core/common/net"
  7. utls "v2ray.com/core/external/github.com/refraction-networking/utls"
  8. )
  9. //go:generate errorgen
  10. var (
  11. _ buf.Writer = (*conn)(nil)
  12. )
  13. type conn struct {
  14. *tls.Conn
  15. }
  16. func (c *conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
  17. mb = buf.Compact(mb)
  18. mb, err := buf.WriteMultiBuffer(c, mb)
  19. buf.ReleaseMulti(mb)
  20. return err
  21. }
  22. func (c *conn) HandshakeAddress() net.Address {
  23. if err := c.Handshake(); err != nil {
  24. return nil
  25. }
  26. state := c.Conn.ConnectionState()
  27. if state.ServerName == "" {
  28. return nil
  29. }
  30. return net.ParseAddress(state.ServerName)
  31. }
  32. // Client initiates a TLS client handshake on the given connection.
  33. func Client(c net.Conn, config *tls.Config) net.Conn {
  34. tlsConn := tls.Client(c, config)
  35. return &conn{Conn: tlsConn}
  36. }
  37. func copyConfig(c *tls.Config) *utls.Config {
  38. return &utls.Config{
  39. NextProtos: c.NextProtos,
  40. ServerName: c.ServerName,
  41. InsecureSkipVerify: c.InsecureSkipVerify,
  42. MinVersion: utls.VersionTLS12,
  43. MaxVersion: utls.VersionTLS12,
  44. }
  45. }
  46. func UClient(c net.Conn, config *tls.Config) net.Conn {
  47. uConfig := copyConfig(config)
  48. return utls.Client(c, uConfig)
  49. }
  50. // Server initiates a TLS server handshake on the given connection.
  51. func Server(c net.Conn, config *tls.Config) net.Conn {
  52. tlsConn := tls.Server(c, config)
  53. return &conn{Conn: tlsConn}
  54. }