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