1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-19 02:46:33 -05:00
v2fly/transport/internet/system_dialer.go

79 lines
1.8 KiB
Go
Raw Normal View History

2016-07-26 11:11:58 -04:00
package internet
import (
"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 {
Dial(source v2net.Address, destination v2net.Destination) (net.Conn, error)
}
type DefaultSystemDialer struct {
}
2016-11-27 15:39:09 -05:00
func (v *DefaultSystemDialer) Dial(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
}
2016-09-20 05:53:05 -04:00
return dialer.Dial(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,
}
}
2016-11-27 15:39:09 -05:00
func (v *SimpleSystemDialer) Dial(src v2net.Address, dest v2net.Destination) (net.Conn, error) {
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
}
2016-07-26 11:25:13 -04:00
// SubstituteDialer 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
// @Deprecated: Use UseAlternativeSimpleSystemDialer.
func SubstituteDialer(dialer SystemDialerAdapter) error {
2016-07-26 11:25:13 -04:00
UseAlternativeSystemDialer(WithAdapter(dialer))
2016-07-26 11:11:58 -04:00
return nil
}
func init() {
effectiveSystemDialer = &DefaultSystemDialer{}
}