1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-18 10:26:01 -05:00
v2fly/transport/internet/system_dialer.go

70 lines
1.6 KiB
Go
Raw Normal View History

2016-07-26 11:11:58 -04:00
package internet
import (
2017-02-26 08:38:41 -05:00
"context"
2016-07-26 11:11:58 -04:00
"time"
"v2ray.com/core/common/net"
2016-07-26 11:11:58 -04:00
)
var (
2017-05-01 18:28:06 -04:00
effectiveSystemDialer SystemDialer = DefaultSystemDialer{}
2016-07-26 11:11:58 -04:00
)
type SystemDialer interface {
Dial(ctx context.Context, source net.Address, destination net.Destination) (net.Conn, error)
2016-07-26 11:11:58 -04:00
}
type DefaultSystemDialer struct {
}
func (DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest net.Destination) (net.Conn, error) {
2016-07-26 11:11:58 -04:00
dialer := &net.Dialer{
Timeout: time.Second * 60,
DualStack: true,
}
if src != nil && src != net.AnyIP {
2016-07-26 11:11:58 -04:00
var addr net.Addr
if dest.Network == net.Network_TCP {
2016-07-26 11:11:58 -04:00
addr = &net.TCPAddr{
IP: src.IP(),
Port: 0,
}
} else {
addr = &net.UDPAddr{
IP: src.IP(),
Port: 0,
}
}
dialer.LocalAddr = addr
}
2017-02-23 17:48:47 -05:00
return dialer.DialContext(ctx, dest.Network.SystemString(), dest.NetAddr())
2016-07-26 11:11:58 -04:00
}
type SystemDialerAdapter interface {
Dial(network string, address string) (net.Conn, error)
}
type SimpleSystemDialer struct {
adapter SystemDialerAdapter
}
2016-07-26 11:25:13 -04:00
func WithAdapter(dialer SystemDialerAdapter) SystemDialer {
return &SimpleSystemDialer{
adapter: dialer,
}
}
func (v *SimpleSystemDialer) Dial(ctx context.Context, src net.Address, dest net.Destination) (net.Conn, error) {
2016-11-27 15:39:09 -05:00
return v.adapter.Dial(dest.Network.SystemString(), dest.NetAddr())
2016-07-26 11:11:58 -04:00
}
2016-07-26 11:25:13 -04:00
// UseAlternativeSystemDialer replaces the current system dialer with a given one.
// Caller must ensure there is no race condition.
2016-07-26 11:11:58 -04:00
func UseAlternativeSystemDialer(dialer SystemDialer) {
2017-04-30 17:37:30 -04:00
if dialer == nil {
2017-05-01 18:28:06 -04:00
effectiveSystemDialer = DefaultSystemDialer{}
2017-04-30 17:37:30 -04:00
}
2016-07-26 11:11:58 -04:00
effectiveSystemDialer = dialer
}