1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 02:26:49 -05:00
v2fly/transport/internet/system_dialer.go

72 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
"net"
"time"
2016-08-20 14:55:45 -04:00
v2net "v2ray.com/core/common/net"
2016-07-26 11:11:58 -04:00
)
var (
effectiveSystemDialer SystemDialer
)
type SystemDialer interface {
2017-02-23 17:48:47 -05:00
Dial(ctx context.Context, source v2net.Address, destination v2net.Destination) (net.Conn, error)
2016-07-26 11:11:58 -04:00
}
type DefaultSystemDialer struct {
}
2017-02-23 17:48:47 -05:00
func (v *DefaultSystemDialer) Dial(ctx context.Context, src v2net.Address, dest v2net.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 != v2net.AnyIP {
var addr net.Addr
2016-09-20 05:53:05 -04:00
if dest.Network == v2net.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,
}
}
2017-02-23 17:48:47 -05:00
func (v *SimpleSystemDialer) Dial(ctx context.Context, src v2net.Address, dest v2net.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) {
effectiveSystemDialer = dialer
}
func init() {
effectiveSystemDialer = &DefaultSystemDialer{}
}