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

     1  package tcp
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/xmplusdev/xray-core/common"
     7  	"github.com/xmplusdev/xray-core/common/net"
     8  	"github.com/xmplusdev/xray-core/common/session"
     9  	"github.com/xmplusdev/xray-core/transport/internet"
    10  	"github.com/xmplusdev/xray-core/transport/internet/reality"
    11  	"github.com/xmplusdev/xray-core/transport/internet/stat"
    12  	"github.com/xmplusdev/xray-core/transport/internet/tls"
    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 := tls.GetFingerprint(config.Fingerprint); fingerprint != nil {
    26  			conn = tls.UClient(conn, tlsConfig, fingerprint)
    27  			if err := conn.(*tls.UConn).HandshakeContext(ctx); err != nil {
    28  				return nil, err
    29  			}
    30  		} else {
    31  			conn = tls.Client(conn, tlsConfig)
    32  		}
    33  	} else if config := reality.ConfigFromStreamSettings(streamSettings); config != nil {
    34  		if conn, err = reality.UClient(conn, config, ctx, dest); err != nil {
    35  			return nil, err
    36  		}
    37  	}
    38  
    39  	tcpSettings := streamSettings.ProtocolSettings.(*Config)
    40  	if tcpSettings.HeaderSettings != nil {
    41  		headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
    42  		if err != nil {
    43  			return nil, newError("failed to get header settings").Base(err).AtError()
    44  		}
    45  		auth, err := internet.CreateConnectionAuthenticator(headerConfig)
    46  		if err != nil {
    47  			return nil, newError("failed to create header authenticator").Base(err).AtError()
    48  		}
    49  		conn = auth.Client(conn)
    50  	}
    51  	return stat.Connection(conn), nil
    52  }
    53  
    54  func init() {
    55  	common.Must(internet.RegisterTransportDialer(protocolName, Dial))
    56  }