clash/tunnel/tunnel.go

344 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
2021-06-10 06:05:56 +00:00
"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/adapter/provider"
2019-10-11 12:11:18 +00:00
"github.com/Dreamacro/clash/component/nat"
"github.com/Dreamacro/clash/component/resolver"
2018-06-10 14:50:03 +00:00
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/context"
2018-11-21 05:47:46 +00:00
"github.com/Dreamacro/clash/log"
"github.com/Dreamacro/clash/tunnel/statistic"
2018-06-10 14:50:03 +00:00
)
var (
tcpQueue = make(chan C.ConnContext, 200)
2020-10-20 09:44:39 +00:00
udpQueue = make(chan *inbound.PacketAdapter, 200)
natTable = nat.New()
rules []C.Rule
proxies = make(map[string]C.Proxy)
providers map[string]provider.ProxyProvider
configMux sync.RWMutex
// Outbound Rule
mode = Rule
// default timeout for UDP session
udpTimeout = 60 * time.Second
)
func init() {
go process()
2018-06-10 14:50:03 +00:00
}
2021-06-13 09:23:10 +00:00
// TCPIn return fan-in queue
func TCPIn() chan<- C.ConnContext {
return tcpQueue
}
2021-06-13 09:23:10 +00:00
// UDPIn return fan-in udp queue
func UDPIn() chan<- *inbound.PacketAdapter {
return udpQueue
2018-06-10 14:50:03 +00:00
}
2018-11-21 05:47:46 +00:00
// Rules return all rules
func Rules() []C.Rule {
return rules
2018-06-18 03:31:49 +00:00
}
2018-11-21 05:47:46 +00:00
// UpdateRules handle update rules
func UpdateRules(newRules []C.Rule) {
configMux.Lock()
rules = newRules
configMux.Unlock()
2018-11-21 05:47:46 +00:00
}
// Proxies return all proxies
func Proxies() map[string]C.Proxy {
return proxies
2018-11-21 05:47:46 +00:00
}
2019-12-08 04:17:24 +00:00
// Providers return all compatible providers
func Providers() map[string]provider.ProxyProvider {
return providers
2019-12-08 04:17:24 +00:00
}
2018-11-21 05:47:46 +00:00
// UpdateProxies handle update proxies
func UpdateProxies(newProxies map[string]C.Proxy, newProviders map[string]provider.ProxyProvider) {
configMux.Lock()
proxies = newProxies
providers = newProviders
configMux.Unlock()
}
2018-11-21 05:47:46 +00:00
// Mode return current mode
func Mode() TunnelMode {
return mode
2018-11-21 05:47:46 +00:00
}
// SetMode change the mode of tunnel
func SetMode(m TunnelMode) {
mode = m
}
// processUDP starts a loop to handle udp packet
func processUDP() {
2020-10-20 09:44:39 +00:00
queue := udpQueue
for conn := range queue {
handleUDPConn(conn)
}
}
func process() {
numUDPWorkers := 4
if runtime.NumCPU() > numUDPWorkers {
numUDPWorkers = runtime.NumCPU()
}
for i := 0; i < numUDPWorkers; i++ {
go processUDP()
}
2019-10-11 12:11:18 +00:00
2020-10-20 09:44:39 +00:00
queue := tcpQueue
for conn := range queue {
go handleTCPConn(conn)
2018-06-10 14:50:03 +00:00
}
}
func needLookupIP(metadata *C.Metadata) bool {
return resolver.MappingEnabled() && metadata.Host == "" && metadata.DstIP != nil
2019-02-11 07:44:42 +00:00
}
func preHandleMetadata(metadata *C.Metadata) error {
// handle IP string on host
if ip := net.ParseIP(metadata.Host); ip != nil {
metadata.DstIP = ip
2021-03-10 04:11:45 +00:00
metadata.Host = ""
if ip.To4() != nil {
metadata.AddrType = C.AtypIPv4
} else {
metadata.AddrType = C.AtypIPv6
}
}
2019-05-02 16:05:14 +00:00
// preprocess enhanced-mode metadata
if needLookupIP(metadata) {
host, exist := resolver.FindHostByIP(metadata.DstIP)
2018-12-05 13:13:29 +00:00
if exist {
metadata.Host = host
metadata.AddrType = C.AtypDomainName
if resolver.FakeIPEnabled() {
2019-05-09 13:00:29 +00:00
metadata.DstIP = nil
2020-04-27 13:28:24 +00:00
} else if node := resolver.DefaultHosts.Search(host); node != nil {
// redir-host should lookup the hosts
metadata.DstIP = node.Data.(net.IP)
2019-05-02 16:05:14 +00:00
}
} else if resolver.IsFakeIP(metadata.DstIP) {
return fmt.Errorf("fake DNS record %s missing", metadata.DstIP)
2018-12-05 13:13:29 +00:00
}
}
return nil
}
func resolveMetadata(ctx C.PlainContext, metadata *C.Metadata) (proxy C.Proxy, rule C.Rule, err error) {
switch mode {
2018-11-21 05:47:46 +00:00
case Direct:
proxy = proxies["DIRECT"]
2018-11-21 05:47:46 +00:00
case Global:
proxy = proxies["GLOBAL"]
// Rule
default:
proxy, rule, err = match(metadata)
}
return
2019-10-11 12:11:18 +00:00
}
2019-02-02 12:47:38 +00:00
func 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-10-28 13:26:50 +00:00
// make a fAddr if request ip is fakeip
2020-03-10 12:36:24 +00:00
var fAddr net.Addr
if resolver.IsExistFakeIP(metadata.DstIP) {
2020-03-10 12:36:24 +00:00
fAddr = metadata.UDPAddr()
}
if err := preHandleMetadata(metadata); err != nil {
log.Debugln("[Metadata PreHandle] error: %s", err)
return
2020-01-31 11:26:33 +00:00
}
2020-01-31 06:43:54 +00:00
key := packet.LocalAddr().String()
2020-10-28 13:26:50 +00:00
handle := func() bool {
pc := natTable.Get(key)
if pc != nil {
handleUDPToRemote(packet, pc, metadata)
return true
}
return false
}
if handle() {
2019-10-11 12:11:18 +00:00
return
}
lockKey := key + "-lock"
2020-10-28 13:26:50 +00:00
cond, loaded := natTable.GetOrCreateLock(lockKey)
2019-10-11 12:11:18 +00:00
go func() {
2020-10-28 13:26:50 +00:00
if loaded {
cond.L.Lock()
cond.Wait()
handle()
cond.L.Unlock()
return
}
2019-10-11 12:11:18 +00:00
2020-10-28 13:26:50 +00:00
defer func() {
natTable.Delete(lockKey)
2020-10-28 13:26:50 +00:00
cond.Broadcast()
}()
ctx := context.NewPacketConnContext(metadata)
proxy, rule, err := resolveMetadata(ctx, metadata)
2020-10-28 13:26:50 +00:00
if err != nil {
log.Warnln("[UDP] Parse metadata failed: %s", err.Error())
return
2019-04-24 02:29:29 +00:00
}
2020-10-28 13:26:50 +00:00
rawPc, err := proxy.DialUDP(metadata)
if err != nil {
if rule == nil {
log.Warnln("[UDP] dial %s to %s error: %s", proxy.Name(), metadata.String(), err.Error())
} else {
log.Warnln("[UDP] dial %s (match %s/%s) to %s error: %s", proxy.Name(), rule.RuleType().String(), rule.Payload(), metadata.String(), err.Error())
}
2020-10-28 13:26:50 +00:00
return
}
ctx.InjectPacketConn(rawPc)
pc := statistic.NewUDPTracker(rawPc, statistic.DefaultManager, metadata, rule)
2020-10-28 13:26:50 +00:00
switch true {
case rule != nil:
log.Infoln("[UDP] %s --> %v match %s(%s) using %s", metadata.SourceAddress(), metadata.String(), rule.RuleType().String(), rule.Payload(), rawPc.Chains().String())
case mode == Global:
log.Infoln("[UDP] %s --> %v using GLOBAL", metadata.SourceAddress(), metadata.String())
case 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())
}
2020-10-28 13:26:50 +00:00
go handleUDPToLocal(packet.UDPPacket, pc, key, fAddr)
natTable.Set(key, pc)
handle()
2019-10-11 12:11:18 +00:00
}()
}
func handleTCPConn(ctx C.ConnContext) {
defer ctx.Conn().Close()
2019-10-11 12:11:18 +00:00
metadata := ctx.Metadata()
2019-10-11 12:11:18 +00:00
if !metadata.Valid() {
log.Warnln("[Metadata] not valid: %#v", metadata)
return
2019-04-23 15:29:36 +00:00
}
if err := preHandleMetadata(metadata); err != nil {
log.Debugln("[Metadata PreHandle] error: %s", err)
return
}
proxy, rule, err := resolveMetadata(ctx, metadata)
2019-10-11 12:11:18 +00:00
if err != nil {
log.Warnln("[Metadata] parse failed: %s", err.Error())
2019-10-11 12:11:18 +00:00
return
}
remoteConn, err := proxy.Dial(metadata)
2018-06-10 14:50:03 +00:00
if err != nil {
if rule == nil {
log.Warnln("[TCP] dial %s to %s error: %s", proxy.Name(), metadata.String(), err.Error())
} else {
log.Warnln("[TCP] dial %s (match %s/%s) to %s error: %s", proxy.Name(), rule.RuleType().String(), rule.Payload(), metadata.String(), err.Error())
}
2018-06-10 14:50:03 +00:00
return
}
remoteConn = statistic.NewTCPTracker(remoteConn, statistic.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:
2020-07-18 11:22:09 +00:00
log.Infoln("[TCP] %s --> %v match %s(%s) using %s", metadata.SourceAddress(), metadata.String(), rule.RuleType().String(), rule.Payload(), remoteConn.Chains().String())
case mode == Global:
2020-01-31 06:58:54 +00:00
log.Infoln("[TCP] %s --> %v using GLOBAL", metadata.SourceAddress(), metadata.String())
case mode == Direct:
2020-01-31 06:58:54 +00:00
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 c := ctx.(type) {
case *context.HTTPContext:
handleHTTP(c, remoteConn)
default:
handleSocket(ctx, remoteConn)
}
2018-06-10 14:50:03 +00:00
}
func shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
2020-07-27 05:47:00 +00:00
return rule.ShouldResolveIP() && metadata.Host != "" && metadata.DstIP == nil
2019-02-02 12:47:38 +00:00
}
func match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
configMux.RLock()
defer configMux.RUnlock()
2018-06-14 16:49:52 +00:00
var resolved bool
2019-09-11 09:00:55 +00:00
if node := resolver.DefaultHosts.Search(metadata.Host); node != nil {
2019-09-11 09:00:55 +00:00
ip := node.Data.(net.IP)
metadata.DstIP = ip
2019-09-11 09:00:55 +00:00
resolved = true
}
for _, rule := range rules {
if !resolved && shouldResolveIP(rule, metadata) {
ip, err := resolver.ResolveIP(metadata.Host)
2019-02-02 12:47:38 +00:00
if err != nil {
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) {
adapter, ok := proxies[rule.Adapter()]
2019-04-23 15:29:36 +00:00
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() {
2021-04-05 05:31:10 +00:00
log.Debugln("%s 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 proxies["DIRECT"], nil, nil
2018-06-10 14:50:03 +00:00
}