clash/tunnel/tunnel.go

342 lines
8.1 KiB
Go
Raw Normal View History

2018-06-10 14:50:03 +00:00
package tunnel
import (
2019-02-02 12:47:38 +00:00
"fmt"
2018-12-05 13:13:29 +00:00
"net"
"runtime"
2018-06-10 14:50:03 +00:00
"sync"
2018-06-16 13:34:13 +00:00
"time"
2018-06-10 14:50:03 +00:00
2019-12-08 04:17:24 +00:00
"github.com/Dreamacro/clash/adapters/inbound"
"github.com/Dreamacro/clash/adapters/provider"
2019-10-11 12:11:18 +00:00
"github.com/Dreamacro/clash/component/nat"
2018-06-10 14:50:03 +00:00
C "github.com/Dreamacro/clash/constant"
2018-12-05 13:13:29 +00:00
"github.com/Dreamacro/clash/dns"
2018-11-21 05:47:46 +00:00
"github.com/Dreamacro/clash/log"
2018-06-10 14:50:03 +00:00
2019-02-02 12:47:38 +00:00
channels "gopkg.in/eapache/channels.v1"
2018-06-10 14:50:03 +00:00
)
var (
tunnel *Tunnel
once sync.Once
2019-10-11 12:11:18 +00:00
// default timeout for UDP session
udpTimeout = 60 * time.Second
2018-06-10 14:50:03 +00:00
)
2019-04-23 15:29:36 +00:00
// Tunnel handle relay inbound proxy and outbound proxy
2018-06-10 14:50:03 +00:00
type Tunnel struct {
2019-10-11 12:11:18 +00:00
tcpQueue *channels.InfiniteChannel
udpQueue *channels.InfiniteChannel
natTable *nat.Table
rules []C.Rule
proxies map[string]C.Proxy
2019-12-08 04:17:24 +00:00
providers map[string]provider.ProxyProvider
configMux sync.RWMutex
// experimental features
ignoreResolveFail bool
// Outbound Rule
2018-11-21 05:47:46 +00:00
mode Mode
2018-06-10 14:50:03 +00:00
}
// Add request to queue
2018-06-10 14:50:03 +00:00
func (t *Tunnel) Add(req C.ServerAdapter) {
t.tcpQueue.In() <- req
}
// AddPacket add udp Packet to queue
func (t *Tunnel) AddPacket(packet *inbound.PacketAdapter) {
t.udpQueue.In() <- packet
2018-06-10 14:50:03 +00:00
}
2018-11-21 05:47:46 +00:00
// Rules return all rules
func (t *Tunnel) Rules() []C.Rule {
return t.rules
2018-06-18 03:31:49 +00:00
}
2018-11-21 05:47:46 +00:00
// UpdateRules handle update rules
func (t *Tunnel) UpdateRules(rules []C.Rule) {
t.configMux.Lock()
2018-11-21 05:47:46 +00:00
t.rules = rules
t.configMux.Unlock()
2018-11-21 05:47:46 +00:00
}
// Proxies return all proxies
func (t *Tunnel) Proxies() map[string]C.Proxy {
return t.proxies
}
2019-12-08 04:17:24 +00:00
// Providers return all compatible providers
func (t *Tunnel) Providers() map[string]provider.ProxyProvider {
return t.providers
}
2018-11-21 05:47:46 +00:00
// UpdateProxies handle update proxies
2019-12-08 04:17:24 +00:00
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy, providers map[string]provider.ProxyProvider) {
t.configMux.Lock()
2018-11-21 05:47:46 +00:00
t.proxies = proxies
2019-12-08 04:17:24 +00:00
t.providers = providers
t.configMux.Unlock()
}
// UpdateExperimental handle update experimental config
func (t *Tunnel) UpdateExperimental(ignoreResolveFail bool) {
t.configMux.Lock()
t.ignoreResolveFail = ignoreResolveFail
t.configMux.Unlock()
2018-11-21 05:47:46 +00:00
}
// Mode return current mode
func (t *Tunnel) Mode() Mode {
return t.mode
}
// SetMode change the mode of tunnel
func (t *Tunnel) SetMode(mode Mode) {
t.mode = mode
2018-06-10 14:50:03 +00:00
}
// processUDP starts a loop to handle udp packet
func (t *Tunnel) processUDP() {
queue := t.udpQueue.Out()
for elm := range queue {
conn := elm.(*inbound.PacketAdapter)
t.handleUDPConn(conn)
}
}
2018-06-10 14:50:03 +00:00
func (t *Tunnel) process() {
numUDPWorkers := 4
if runtime.NumCPU() > numUDPWorkers {
numUDPWorkers = runtime.NumCPU()
}
for i := 0; i < numUDPWorkers; i++ {
go t.processUDP()
}
2019-10-11 12:11:18 +00:00
queue := t.tcpQueue.Out()
for elm := range queue {
2018-06-10 14:50:03 +00:00
conn := elm.(C.ServerAdapter)
2019-10-11 12:11:18 +00:00
go t.handleTCPConn(conn)
2018-06-10 14:50:03 +00:00
}
}
2018-12-05 13:13:29 +00:00
func (t *Tunnel) resolveIP(host string) (net.IP, error) {
return dns.ResolveIP(host)
2018-12-05 13:13:29 +00:00
}
2019-02-11 09:20:42 +00:00
func (t *Tunnel) needLookupIP(metadata *C.Metadata) bool {
return dns.DefaultResolver != nil && (dns.DefaultResolver.IsMapping() || dns.DefaultResolver.FakeIPEnabled()) && metadata.Host == "" && metadata.DstIP != nil
2019-02-11 07:44:42 +00:00
}
2019-10-11 12:11:18 +00:00
func (t *Tunnel) resolveMetadata(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
// handle host equal IP string
if ip := net.ParseIP(metadata.Host); ip != nil {
metadata.DstIP = ip
}
2019-05-02 16:05:14 +00:00
// preprocess enhanced-mode metadata
2019-02-11 09:20:42 +00:00
if t.needLookupIP(metadata) {
host, exist := dns.DefaultResolver.IPToHost(metadata.DstIP)
2018-12-05 13:13:29 +00:00
if exist {
metadata.Host = host
metadata.AddrType = C.AtypDomainName
if dns.DefaultResolver.FakeIPEnabled() {
2019-05-09 13:00:29 +00:00
metadata.DstIP = nil
2019-05-02 16:05:14 +00:00
}
2018-12-05 13:13:29 +00:00
}
}
var proxy C.Proxy
var rule C.Rule
switch t.mode {
2018-11-21 05:47:46 +00:00
case Direct:
2018-07-18 13:50:16 +00:00
proxy = t.proxies["DIRECT"]
2018-11-21 05:47:46 +00:00
case Global:
proxy = t.proxies["GLOBAL"]
// Rule
default:
2019-02-02 12:47:38 +00:00
var err error
proxy, rule, err = t.match(metadata)
2019-02-02 12:47:38 +00:00
if err != nil {
2019-10-11 12:11:18 +00:00
return nil, nil, err
2019-02-02 12:47:38 +00:00
}
}
2019-10-11 12:11:18 +00:00
return proxy, rule, nil
}
2019-02-02 12:47:38 +00:00
func (t *Tunnel) handleUDPConn(packet *inbound.PacketAdapter) {
metadata := packet.Metadata()
2019-10-11 12:11:18 +00:00
if !metadata.Valid() {
log.Warnln("[Metadata] not valid: %#v", metadata)
return
}
2020-01-31 06:43:54 +00:00
key := packet.LocalAddr().String()
2019-10-11 12:11:18 +00:00
2020-01-31 06:43:54 +00:00
pc := t.natTable.Get(key)
addr := metadata.UDPAddr()
2019-10-11 12:11:18 +00:00
if pc != nil {
t.handleUDPToRemote(packet, pc, addr)
2019-10-11 12:11:18 +00:00
return
}
lockKey := key + "-lock"
wg, loaded := t.natTable.GetOrCreateLock(lockKey)
2019-10-11 12:11:18 +00:00
go func() {
if !loaded {
wg.Add(1)
proxy, rule, err := t.resolveMetadata(metadata)
if err != nil {
log.Warnln("[UDP] Parse metadata failed: %s", err.Error())
2019-10-11 12:11:18 +00:00
t.natTable.Delete(lockKey)
wg.Done()
return
}
2020-01-31 06:43:54 +00:00
rawPc, err := proxy.DialUDP(metadata)
2019-10-11 12:11:18 +00:00
if err != nil {
log.Warnln("[UDP] dial %s error: %s", proxy.Name(), err.Error())
2019-10-11 12:11:18 +00:00
t.natTable.Delete(lockKey)
wg.Done()
return
}
pc = newUDPTracker(rawPc, DefaultManager, metadata, rule)
2019-10-11 12:11:18 +00:00
2020-01-31 06:58:54 +00:00
switch true {
case rule != nil:
log.Infoln("[UDP] %s --> %v match %s using %s", metadata.SourceAddress(), metadata.String(), rule.RuleType().String(), rawPc.Chains().String())
case t.mode == Global:
log.Infoln("[UDP] %s --> %v using GLOBAL", metadata.SourceAddress(), metadata.String())
case t.mode == Direct:
log.Infoln("[UDP] %s --> %v using DIRECT", metadata.SourceAddress(), metadata.String())
default:
log.Infoln("[UDP] %s --> %v doesn't match any rule using DIRECT", metadata.SourceAddress(), metadata.String())
2019-10-11 12:11:18 +00:00
}
2020-01-31 06:43:54 +00:00
t.natTable.Set(key, pc)
2019-10-11 12:11:18 +00:00
t.natTable.Delete(lockKey)
wg.Done()
2020-01-31 06:43:54 +00:00
go t.handleUDPToLocal(packet.UDPPacket, pc, key)
2019-04-24 02:29:29 +00:00
}
2019-10-11 12:11:18 +00:00
wg.Wait()
2020-01-31 06:43:54 +00:00
pc := t.natTable.Get(key)
2019-10-11 12:11:18 +00:00
if pc != nil {
t.handleUDPToRemote(packet, pc, addr)
}
2019-10-11 12:11:18 +00:00
}()
}
2019-10-11 12:11:18 +00:00
func (t *Tunnel) handleTCPConn(localConn C.ServerAdapter) {
defer localConn.Close()
metadata := localConn.Metadata()
if !metadata.Valid() {
log.Warnln("[Metadata] not valid: %#v", metadata)
return
2019-04-23 15:29:36 +00:00
}
2019-10-11 12:11:18 +00:00
proxy, rule, err := t.resolveMetadata(metadata)
if err != nil {
log.Warnln("Parse metadata failed: %v", err)
return
}
remoteConn, err := proxy.Dial(metadata)
2018-06-10 14:50:03 +00:00
if err != nil {
2019-08-10 12:14:24 +00:00
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
2018-06-10 14:50:03 +00:00
return
}
remoteConn = newTCPTracker(remoteConn, DefaultManager, metadata, rule)
defer remoteConn.Close()
2018-06-10 14:50:03 +00:00
2020-01-31 06:58:54 +00:00
switch true {
case rule != nil:
log.Infoln("[TCP] %s --> %v match %s using %s", metadata.SourceAddress(), metadata.String(), rule.RuleType().String(), remoteConn.Chains().String())
case t.mode == Global:
log.Infoln("[TCP] %s --> %v using GLOBAL", metadata.SourceAddress(), metadata.String())
case t.mode == Direct:
log.Infoln("[TCP] %s --> %v using DIRECT", metadata.SourceAddress(), metadata.String())
default:
log.Infoln("[TCP] %s --> %v doesn't match any rule using DIRECT", metadata.SourceAddress(), metadata.String())
}
switch adapter := localConn.(type) {
2019-12-08 04:17:24 +00:00
case *inbound.HTTPAdapter:
t.handleHTTP(adapter, remoteConn)
2019-12-08 04:17:24 +00:00
case *inbound.SocketAdapter:
t.handleSocket(adapter, remoteConn)
}
2018-06-10 14:50:03 +00:00
}
2019-02-02 12:47:38 +00:00
func (t *Tunnel) shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
return !rule.NoResolveIP() && metadata.Host != "" && metadata.DstIP == nil
2019-02-02 12:47:38 +00:00
}
func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
t.configMux.RLock()
defer t.configMux.RUnlock()
2018-06-14 16:49:52 +00:00
var resolved bool
2019-09-11 09:00:55 +00:00
if node := dns.DefaultHosts.Search(metadata.Host); node != nil {
ip := node.Data.(net.IP)
metadata.DstIP = ip
2019-09-11 09:00:55 +00:00
resolved = true
}
2018-06-10 14:50:03 +00:00
for _, rule := range t.rules {
if !resolved && t.shouldResolveIP(rule, metadata) {
2019-02-02 12:47:38 +00:00
ip, err := t.resolveIP(metadata.Host)
if err != nil {
if !t.ignoreResolveFail {
return nil, nil, fmt.Errorf("[DNS] resolve %s error: %s", metadata.Host, err.Error())
}
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
} else {
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
metadata.DstIP = ip
2019-02-02 12:47:38 +00:00
}
resolved = true
2019-02-02 12:47:38 +00:00
}
if rule.Match(metadata) {
2019-04-23 15:29:36 +00:00
adapter, ok := t.proxies[rule.Adapter()]
if !ok {
continue
2018-06-10 14:50:03 +00:00
}
2019-04-23 15:29:36 +00:00
if metadata.NetWork == C.UDP && !adapter.SupportUDP() {
log.Debugln("%v UDP is not supported", adapter.Name())
2019-04-23 15:29:36 +00:00
continue
}
return adapter, rule, nil
2018-06-10 14:50:03 +00:00
}
}
return t.proxies["DIRECT"], nil, nil
2018-06-10 14:50:03 +00:00
}
func newTunnel() *Tunnel {
return &Tunnel{
tcpQueue: channels.NewInfiniteChannel(),
udpQueue: channels.NewInfiniteChannel(),
natTable: nat.New(),
proxies: make(map[string]C.Proxy),
mode: Rule,
2018-06-10 14:50:03 +00:00
}
}
// Instance return singleton instance of Tunnel
func Instance() *Tunnel {
2018-06-10 14:50:03 +00:00
once.Do(func() {
tunnel = newTunnel()
2018-11-21 05:47:46 +00:00
go tunnel.process()
2018-06-10 14:50:03 +00:00
})
return tunnel
}