tls.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "github.com/v2fly/v2ray-core/v5/common"
  6. "github.com/v2fly/v2ray-core/v5/common/buf"
  7. "github.com/v2fly/v2ray-core/v5/common/net"
  8. )
  9. //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
  10. var _ buf.Writer = (*Conn)(nil)
  11. type Conn struct {
  12. *tls.Conn
  13. }
  14. func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
  15. mb = buf.Compact(mb)
  16. mb, err := buf.WriteMultiBuffer(c, mb)
  17. buf.ReleaseMulti(mb)
  18. return err
  19. }
  20. func (c *Conn) HandshakeAddress() net.Address {
  21. if err := c.Handshake(); err != nil {
  22. return nil
  23. }
  24. state := c.ConnectionState()
  25. if state.ServerName == "" {
  26. return nil
  27. }
  28. return net.ParseAddress(state.ServerName)
  29. }
  30. // Client initiates a TLS client handshake on the given connection.
  31. func Client(c net.Conn, config *tls.Config) net.Conn {
  32. tlsConn := tls.Client(c, config)
  33. return &Conn{Conn: tlsConn}
  34. }
  35. /*
  36. func copyConfig(c *tls.Config) *utls.Config {
  37. return &utls.Config{
  38. NextProtos: c.NextProtos,
  39. ServerName: c.ServerName,
  40. InsecureSkipVerify: c.InsecureSkipVerify,
  41. MinVersion: utls.VersionTLS12,
  42. MaxVersion: utls.VersionTLS12,
  43. }
  44. }
  45. func UClient(c net.Conn, config *tls.Config) net.Conn {
  46. uConfig := copyConfig(config)
  47. return utls.Client(c, uConfig)
  48. }
  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. }
  55. func init() {
  56. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  57. return NewTLSSecurityEngineFromConfig(config.(*Config))
  58. }))
  59. }