tls.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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) GetConnectionApplicationProtocol() (string, error) {
  15. if err := c.Handshake(); err != nil {
  16. return "", err
  17. }
  18. return c.ConnectionState().NegotiatedProtocol, nil
  19. }
  20. func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
  21. mb = buf.Compact(mb)
  22. mb, err := buf.WriteMultiBuffer(c, mb)
  23. buf.ReleaseMulti(mb)
  24. return err
  25. }
  26. func (c *Conn) HandshakeAddress() net.Address {
  27. if err := c.Handshake(); err != nil {
  28. return nil
  29. }
  30. state := c.ConnectionState()
  31. if state.ServerName == "" {
  32. return nil
  33. }
  34. return net.ParseAddress(state.ServerName)
  35. }
  36. // Client initiates a TLS client handshake on the given connection.
  37. func Client(c net.Conn, config *tls.Config) *Conn {
  38. tlsConn := tls.Client(c, config)
  39. return &Conn{Conn: tlsConn}
  40. }
  41. /*
  42. func copyConfig(c *tls.Config) *utls.Config {
  43. return &utls.Config{
  44. NextProtos: c.NextProtos,
  45. ServerName: c.ServerName,
  46. InsecureSkipVerify: c.InsecureSkipVerify,
  47. MinVersion: utls.VersionTLS12,
  48. MaxVersion: utls.VersionTLS12,
  49. }
  50. }
  51. func UClient(c net.Conn, config *tls.Config) net.Conn {
  52. uConfig := copyConfig(config)
  53. return utls.Client(c, uConfig)
  54. }
  55. */
  56. // Server initiates a TLS server handshake on the given connection.
  57. func Server(c net.Conn, config *tls.Config) net.Conn {
  58. tlsConn := tls.Server(c, config)
  59. return &Conn{Conn: tlsConn}
  60. }
  61. func init() {
  62. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  63. return NewTLSSecurityEngineFromConfig(config.(*Config))
  64. }))
  65. }