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
|
|
|
)
|
|
|
|
|
2018-06-26 17:00:13 +08:00
|
|
|
// Dialer means to establish a connection and relay it.
|
2017-08-23 16:35:39 +08:00
|
|
|
type Dialer interface {
|
|
|
|
// Addr()
|
|
|
|
Addr() string
|
|
|
|
|
|
|
|
// Dial connects to the given address via the proxy.
|
|
|
|
Dial(network, addr string) (c net.Conn, err error)
|
2017-08-23 17:45:57 +08:00
|
|
|
|
2018-01-17 00:26:38 +08:00
|
|
|
// DialUDP connects to the given address via the proxy.
|
|
|
|
DialUDP(network, addr string) (pc net.PacketConn, writeTo net.Addr, err error)
|
|
|
|
|
2017-08-23 17:45:57 +08:00
|
|
|
// Get the dialer by dstAddr
|
|
|
|
NextDialer(dstAddr string) Dialer
|
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)
|
|
|
|
)
|
|
|
|
|
2018-06-26 17:00:13 +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-03-24 19:57:46 +08:00
|
|
|
func DialerFromURL(s string, dialer Dialer) (Dialer, error) {
|
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-03-24 19:57:46 +08:00
|
|
|
if dialer == nil {
|
|
|
|
dialer = Direct
|
2017-08-23 16:35:39 +08:00
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|