59 lines
1.6 KiB
Go
Raw Normal View History

2016-06-14 22:54:08 +02:00
package internet
import (
"context"
2017-01-03 14:53:59 +01:00
"v2ray.com/core/common/net"
2016-06-14 22:54:08 +02:00
)
type Dialer func(ctx context.Context, dest net.Destination) (Connection, error)
2016-06-14 22:54:08 +02:00
var (
2018-08-06 13:48:35 +02:00
transportDialerCache = make(map[string]Dialer)
2016-06-14 22:54:08 +02:00
)
2018-08-06 13:48:35 +02:00
func RegisterTransportDialer(protocol string, dialer Dialer) error {
if _, found := transportDialerCache[protocol]; found {
2017-04-09 01:43:25 +02:00
return newError(protocol, " dialer already registered").AtError()
2017-01-03 15:16:48 +01:00
}
transportDialerCache[protocol] = dialer
2017-01-03 15:16:48 +01:00
return nil
}
2018-04-17 23:33:39 +02:00
// Dial dials a internet connection towards the given destination.
func Dial(ctx context.Context, dest net.Destination) (Connection, error) {
if dest.Network == net.Network_TCP {
2017-02-26 14:38:41 +01:00
streamSettings := StreamSettingsFromContext(ctx)
2018-09-07 14:50:25 +02:00
var protocol string
if streamSettings != nil {
protocol = streamSettings.ProtocolName
} else {
protocol = "tcp"
pSettings, err := CreateTransportConfigByName(protocol)
if err != nil {
2018-09-07 14:50:25 +02:00
return nil, newError("failed to create default config for protocol: ", protocol).Base(err)
}
2018-09-07 14:50:25 +02:00
ctx = ContextWithStreamSettings(ctx, &MemoryStreamConfig{
ProtocolName: protocol,
ProtocolSettings: pSettings,
})
}
dialer := transportDialerCache[protocol]
2017-01-03 15:16:48 +01:00
if dialer == nil {
2017-04-09 01:43:25 +02:00
return nil, newError(protocol, " dialer not registered").AtError()
2016-06-14 22:54:08 +02:00
}
return dialer(ctx, dest)
2016-06-14 22:54:08 +02:00
}
2018-08-06 13:48:35 +02:00
udpDialer := transportDialerCache["udp"]
2017-01-03 15:16:48 +01:00
if udpDialer == nil {
2017-04-09 01:43:25 +02:00
return nil, newError("UDP dialer not registered").AtError()
2017-01-03 15:16:48 +01:00
}
return udpDialer(ctx, dest)
2016-06-14 22:54:08 +02:00
}
2017-01-03 15:16:48 +01:00
// DialSystem calls system dialer to create a network connection.
func DialSystem(ctx context.Context, src net.Address, dest net.Destination) (net.Conn, error) {
2017-02-23 23:48:47 +01:00
return effectiveSystemDialer.Dial(ctx, src, dest)
2016-06-14 22:54:08 +02:00
}