github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/transport/internet/tls/tls.go (about)

     1  package tls
     2  
     3  import (
     4  	"context"
     5  	"crypto/tls"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/common"
     8  	"github.com/v2fly/v2ray-core/v5/common/buf"
     9  	"github.com/v2fly/v2ray-core/v5/common/net"
    10  )
    11  
    12  //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
    13  
    14  var _ buf.Writer = (*Conn)(nil)
    15  
    16  type Conn struct {
    17  	*tls.Conn
    18  }
    19  
    20  func (c *Conn) GetConnectionApplicationProtocol() (string, error) {
    21  	if err := c.Handshake(); err != nil {
    22  		return "", err
    23  	}
    24  	return c.ConnectionState().NegotiatedProtocol, nil
    25  }
    26  
    27  func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
    28  	mb = buf.Compact(mb)
    29  	mb, err := buf.WriteMultiBuffer(c, mb)
    30  	buf.ReleaseMulti(mb)
    31  	return err
    32  }
    33  
    34  func (c *Conn) HandshakeAddress() net.Address {
    35  	if err := c.Handshake(); err != nil {
    36  		return nil
    37  	}
    38  	state := c.ConnectionState()
    39  	if state.ServerName == "" {
    40  		return nil
    41  	}
    42  	return net.ParseAddress(state.ServerName)
    43  }
    44  
    45  // Client initiates a TLS client handshake on the given connection.
    46  func Client(c net.Conn, config *tls.Config) *Conn {
    47  	tlsConn := tls.Client(c, config)
    48  	return &Conn{Conn: tlsConn}
    49  }
    50  
    51  /*
    52  func copyConfig(c *tls.Config) *utls.Config {
    53  	return &utls.Config{
    54  		NextProtos:         c.NextProtos,
    55  		ServerName:         c.ServerName,
    56  		InsecureSkipVerify: c.InsecureSkipVerify,
    57  		MinVersion:         utls.VersionTLS12,
    58  		MaxVersion:         utls.VersionTLS12,
    59  	}
    60  }
    61  
    62  func UClient(c net.Conn, config *tls.Config) net.Conn {
    63  	uConfig := copyConfig(config)
    64  	return utls.Client(c, uConfig)
    65  }
    66  */
    67  
    68  // Server initiates a TLS server handshake on the given connection.
    69  func Server(c net.Conn, config *tls.Config) net.Conn {
    70  	tlsConn := tls.Server(c, config)
    71  	return &Conn{Conn: tlsConn}
    72  }
    73  
    74  func init() {
    75  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
    76  		return NewTLSSecurityEngineFromConfig(config.(*Config))
    77  	}))
    78  }