2016-06-14 16:54:08 -04:00
|
|
|
package internet
|
|
|
|
|
|
|
|
import (
|
2017-01-26 14:46:44 -05:00
|
|
|
"context"
|
2016-06-14 16:54:08 -04:00
|
|
|
"net"
|
2017-01-03 08:53:59 -05:00
|
|
|
|
2016-12-04 03:10:47 -05:00
|
|
|
"v2ray.com/core/common/errors"
|
2016-08-20 14:55:45 -04:00
|
|
|
v2net "v2ray.com/core/common/net"
|
2016-06-14 16:54:08 -04:00
|
|
|
)
|
|
|
|
|
2017-01-26 14:46:44 -05:00
|
|
|
type Dialer func(ctx context.Context, dest v2net.Destination) (Connection, error)
|
2016-06-14 16:54:08 -04:00
|
|
|
|
|
|
|
var (
|
2017-01-12 06:54:34 -05:00
|
|
|
transportDialerCache = make(map[TransportProtocol]Dialer)
|
2016-06-14 16:54:08 -04:00
|
|
|
)
|
|
|
|
|
2017-01-12 06:54:34 -05:00
|
|
|
func RegisterTransportDialer(protocol TransportProtocol, dialer Dialer) error {
|
|
|
|
if _, found := transportDialerCache[protocol]; found {
|
|
|
|
return errors.New("Internet|Dialer: ", protocol, " dialer already registered.")
|
2017-01-03 09:16:48 -05:00
|
|
|
}
|
2017-01-12 06:54:34 -05:00
|
|
|
transportDialerCache[protocol] = dialer
|
2017-01-03 09:16:48 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-01-26 14:46:44 -05:00
|
|
|
func Dial(ctx context.Context, dest v2net.Destination) (Connection, error) {
|
2016-09-20 05:53:05 -04:00
|
|
|
if dest.Network == v2net.Network_TCP {
|
2017-01-26 14:46:44 -05:00
|
|
|
streamSettings, _ := StreamSettingsFromContext(ctx)
|
|
|
|
protocol := streamSettings.GetEffectiveProtocol()
|
|
|
|
transportSettings, err := streamSettings.GetEffectiveTransportSettings()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ctx = ContextWithTransportSettings(ctx, transportSettings)
|
|
|
|
if streamSettings != nil && streamSettings.HasSecuritySettings() {
|
|
|
|
securitySettings, err := streamSettings.GetEffectiveSecuritySettings()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ctx = ContextWithSecuritySettings(ctx, securitySettings)
|
|
|
|
}
|
2017-01-12 06:54:34 -05:00
|
|
|
dialer := transportDialerCache[protocol]
|
2017-01-03 09:16:48 -05:00
|
|
|
if dialer == nil {
|
2017-01-26 14:46:44 -05:00
|
|
|
return nil, errors.New("Internet|Dialer: ", protocol, " dialer not registered.")
|
2016-06-14 16:54:08 -04:00
|
|
|
}
|
2017-01-26 14:46:44 -05:00
|
|
|
return dialer(ctx, dest)
|
2016-06-14 16:54:08 -04:00
|
|
|
}
|
|
|
|
|
2017-01-12 06:54:34 -05:00
|
|
|
udpDialer := transportDialerCache[TransportProtocol_UDP]
|
2017-01-03 09:16:48 -05:00
|
|
|
if udpDialer == nil {
|
|
|
|
return nil, errors.New("Internet|Dialer: UDP dialer not registered.")
|
|
|
|
}
|
2017-01-26 14:46:44 -05:00
|
|
|
return udpDialer(ctx, dest)
|
2016-06-14 16:54:08 -04:00
|
|
|
}
|
|
|
|
|
2017-01-03 09:16:48 -05:00
|
|
|
// DialSystem calls system dialer to create a network connection.
|
|
|
|
func DialSystem(src v2net.Address, dest v2net.Destination) (net.Conn, error) {
|
2016-07-26 11:11:58 -04:00
|
|
|
return effectiveSystemDialer.Dial(src, dest)
|
2016-06-14 16:54:08 -04:00
|
|
|
}
|