github.com/xraypb/xray-core@v1.6.6/transport/internet/tcp/dialer.go (about)

     1  package tcp
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/xraypb/xray-core/common"
     7  	"github.com/xraypb/xray-core/common/net"
     8  	"github.com/xraypb/xray-core/common/session"
     9  	"github.com/xraypb/xray-core/transport/internet"
    10  	"github.com/xraypb/xray-core/transport/internet/stat"
    11  	"github.com/xraypb/xray-core/transport/internet/tls"
    12  	"github.com/xraypb/xray-core/transport/internet/xtls"
    13  )
    14  
    15  // Dial dials a new TCP connection to the given destination.
    16  func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
    17  	newError("dialing TCP to ", dest).WriteToLog(session.ExportIDToError(ctx))
    18  	conn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	if config := tls.ConfigFromStreamSettings(streamSettings); config != nil {
    24  		tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
    25  		if fingerprint, ok := tls.Fingerprints[config.Fingerprint]; ok {
    26  			conn = tls.UClient(conn, tlsConfig, fingerprint)
    27  			if err := conn.(*tls.UConn).Handshake(); err != nil {
    28  				return nil, err
    29  			}
    30  		} else {
    31  			conn = tls.Client(conn, tlsConfig)
    32  		}
    33  	} else if config := xtls.ConfigFromStreamSettings(streamSettings); config != nil {
    34  		xtlsConfig := config.GetXTLSConfig(xtls.WithDestination(dest))
    35  		conn = xtls.Client(conn, xtlsConfig)
    36  	}
    37  
    38  	tcpSettings := streamSettings.ProtocolSettings.(*Config)
    39  	if tcpSettings.HeaderSettings != nil {
    40  		headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
    41  		if err != nil {
    42  			return nil, newError("failed to get header settings").Base(err).AtError()
    43  		}
    44  		auth, err := internet.CreateConnectionAuthenticator(headerConfig)
    45  		if err != nil {
    46  			return nil, newError("failed to create header authenticator").Base(err).AtError()
    47  		}
    48  		conn = auth.Client(conn)
    49  	}
    50  	return stat.Connection(conn), nil
    51  }
    52  
    53  func init() {
    54  	common.Must(internet.RegisterTransportDialer(protocolName, Dial))
    55  }