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

     1  package tcp
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/v2fly/v2ray-core/v5/common"
     7  	"github.com/v2fly/v2ray-core/v5/common/net"
     8  	"github.com/v2fly/v2ray-core/v5/common/serial"
     9  	"github.com/v2fly/v2ray-core/v5/common/session"
    10  	"github.com/v2fly/v2ray-core/v5/transport/internet"
    11  	"github.com/v2fly/v2ray-core/v5/transport/internet/security"
    12  )
    13  
    14  // Dial dials a new TCP connection to the given destination.
    15  func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
    16  	newError("dialing TCP to ", dest).WriteToLog(session.ExportIDToError(ctx))
    17  	conn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	securityEngine, err := security.CreateSecurityEngineFromSettings(ctx, streamSettings)
    23  	if err != nil {
    24  		return nil, newError("unable to create security engine").Base(err)
    25  	}
    26  
    27  	if securityEngine != nil {
    28  		conn, err = securityEngine.Client(conn, security.OptionWithDestination{Dest: dest})
    29  		if err != nil {
    30  			return nil, newError("unable to create security protocol client from security engine").Base(err)
    31  		}
    32  	}
    33  
    34  	tcpSettings := streamSettings.ProtocolSettings.(*Config)
    35  	if tcpSettings.HeaderSettings != nil {
    36  		headerConfig, err := serial.GetInstanceOf(tcpSettings.HeaderSettings)
    37  		if err != nil {
    38  			return nil, newError("failed to get header settings").Base(err).AtError()
    39  		}
    40  		auth, err := internet.CreateConnectionAuthenticator(headerConfig)
    41  		if err != nil {
    42  			return nil, newError("failed to create header authenticator").Base(err).AtError()
    43  		}
    44  		conn = auth.Client(conn)
    45  	}
    46  	return internet.Connection(conn), nil
    47  }
    48  
    49  func init() {
    50  	common.Must(internet.RegisterTransportDialer(protocolName, Dial))
    51  }