tls.go 1.6 KB

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