2018-06-26 16:15:48 +08:00
|
|
|
package proxy
|
2017-08-23 16:35:39 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net"
|
|
|
|
"net/url"
|
2018-06-26 16:15:48 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/nadoo/glider/common/log"
|
2017-08-23 16:35:39 +08:00
|
|
|
)
|
|
|
|
|
2019-09-18 19:40:14 +08:00
|
|
|
// Dialer is used to create connection.
|
2017-08-23 16:35:39 +08:00
|
|
|
type Dialer interface {
|
2020-04-13 12:26:21 +08:00
|
|
|
TCPDialer
|
|
|
|
UDPDialer
|
|
|
|
}
|
|
|
|
|
2020-04-14 00:17:46 +08:00
|
|
|
// TCPDialer is used to create tcp connection.
|
2020-04-13 12:26:21 +08:00
|
|
|
type TCPDialer interface {
|
2019-09-18 19:40:14 +08:00
|
|
|
// Addr is the dialer's addr
|
2017-08-23 16:35:39 +08:00
|
|
|
Addr() string
|
|
|
|
|
2019-09-18 19:40:14 +08:00
|
|
|
// Dial connects to the given address
|
|
|
|
Dial(network, addr string) (c net.Conn, err error)
|
2020-04-13 12:26:21 +08:00
|
|
|
}
|
|
|
|
|
2020-04-14 00:17:46 +08:00
|
|
|
// UDPDialer is used to create udp PacketConn.
|
2020-04-13 12:26:21 +08:00
|
|
|
type UDPDialer interface {
|
|
|
|
// Addr is the dialer's addr
|
|
|
|
Addr() string
|
2017-08-23 17:45:57 +08:00
|
|
|
|
2019-09-18 19:40:14 +08:00
|
|
|
// DialUDP connects to the given address
|
2018-01-17 00:26:38 +08:00
|
|
|
DialUDP(network, addr string) (pc net.PacketConn, writeTo net.Addr, err error)
|
2017-08-23 16:35:39 +08:00
|
|
|
}
|
|
|
|
|
2018-06-26 17:00:13 +08:00
|
|
|
// DialerCreator is a function to create dialers.
|
2018-06-26 16:15:48 +08:00
|
|
|
type DialerCreator func(s string, dialer Dialer) (Dialer, error)
|
|
|
|
|
|
|
|
var (
|
|
|
|
dialerMap = make(map[string]DialerCreator)
|
|
|
|
)
|
|
|
|
|
2019-09-18 19:40:14 +08:00
|
|
|
// RegisterDialer is used to register a dialer.
|
2018-06-26 16:15:48 +08:00
|
|
|
func RegisterDialer(name string, c DialerCreator) {
|
|
|
|
dialerMap[name] = c
|
|
|
|
}
|
|
|
|
|
2018-06-26 17:00:13 +08:00
|
|
|
// DialerFromURL calls the registered creator to create dialers.
|
2018-08-20 22:23:00 +08:00
|
|
|
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function.
|
2018-03-24 19:57:46 +08:00
|
|
|
func DialerFromURL(s string, dialer Dialer) (Dialer, error) {
|
2018-08-20 22:23:00 +08:00
|
|
|
if dialer == nil {
|
|
|
|
return nil, errors.New("DialerFromURL: dialer cannot be nil")
|
|
|
|
}
|
|
|
|
|
2017-08-23 16:35:39 +08:00
|
|
|
u, err := url.Parse(s)
|
|
|
|
if err != nil {
|
2018-06-26 16:15:48 +08:00
|
|
|
log.F("parse err: %s", err)
|
2017-08-23 16:35:39 +08:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-06-26 16:15:48 +08:00
|
|
|
c, ok := dialerMap[strings.ToLower(u.Scheme)]
|
|
|
|
if ok {
|
|
|
|
return c(s, dialer)
|
2017-08-23 16:35:39 +08:00
|
|
|
}
|
|
|
|
|
2018-06-03 13:54:16 +08:00
|
|
|
return nil, errors.New("unknown scheme '" + u.Scheme + "'")
|
2017-08-23 16:35:39 +08:00
|
|
|
}
|