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"
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
"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 {
|
2017-08-29 06:56:57 -04:00
|
|
|
Dial(ctx context.Context, source net.Address, destination net.Destination) (net.Conn, error)
|
2016-07-26 11:11:58 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
type DefaultSystemDialer struct {
|
|
|
|
}
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
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,
|
|
|
|
}
|
2017-08-29 06:56:57 -04:00
|
|
|
if src != nil && src != net.AnyIP {
|
2016-07-26 11:11:58 -04:00
|
|
|
var addr net.Addr
|
2017-08-29 06:56:57 -04:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
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
|
|
|
|
}
|