From 27cd92b4b13a4fb3772ef27a804d313c399639ce Mon Sep 17 00:00:00 2001 From: Kr328 <39107975+Kr328@users.noreply.github.com> Date: Tue, 31 Mar 2020 23:21:02 +0800 Subject: [PATCH] recycle dns udp packet --- core/src/main/golang/bridge/init.go | 17 ++----- core/src/main/golang/bridge/profiles.go | 4 +- core/src/main/golang/config/fetch.go | 4 +- core/src/main/golang/config/patch.go | 7 --- core/src/main/golang/tun/dns.go | 4 +- core/src/main/golang/tun/tun.go | 48 +++++++++++++++++-- .../java/com/github/kr328/clash/core/Clash.kt | 4 +- .../github/kr328/clash/service/TunService.kt | 3 +- 8 files changed, 58 insertions(+), 33 deletions(-) diff --git a/core/src/main/golang/bridge/init.go b/core/src/main/golang/bridge/init.go index 0c0ffbc..c94cf79 100644 --- a/core/src/main/golang/bridge/init.go +++ b/core/src/main/golang/bridge/init.go @@ -1,13 +1,12 @@ package bridge import ( - "sync" - "github.com/Dreamacro/clash/component/mmdb" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/tunnel" "github.com/kr328/cfa/config" + "sync" ) var ( @@ -19,15 +18,13 @@ type LogCallback interface { OnLogEvent(level, payload string) } -func LoadMMDB(data []byte) { - dataClone := make([]byte, len(data)) - copy(dataClone, data) +func InitCore(geoipDatabase[] byte, homeDir string, version string) { + dataClone := make([]byte, len(geoipDatabase)) + copy(dataClone, geoipDatabase) mmdb.LoadFromBytes(dataClone) -} - -func SetHome(homeDir string) { C.SetHomeDir(homeDir) + config.ApplicationVersion = version } func Reset() { @@ -35,10 +32,6 @@ func Reset() { tunnel.DefaultManager.ResetStatistic() } -func SetApplicationVersion(version string) { - config.ApplicationVersion = version -} - func SetLogCallback(callback LogCallback) { logSubscribe.Do(func() { go func() { diff --git a/core/src/main/golang/bridge/profiles.go b/core/src/main/golang/bridge/profiles.go index 345f8fa..2a4de81 100644 --- a/core/src/main/golang/bridge/profiles.go +++ b/core/src/main/golang/bridge/profiles.go @@ -30,13 +30,13 @@ func LoadProfileFile(path, baseDir string, callback DoneCallback) { func DownloadProfileAndCheck(url, output, baseDir string, callback DoneCallback) { go func() { - call(config.DownloadRemote(url, output, baseDir), callback) + call(config.PullRemote(url, output, baseDir), callback) }() } func ReadProfileAndCheck(fd int, output, baseDir string, callback DoneCallback) { go func() { - call(config.DownloadLocal(fd, output, baseDir), callback) + call(config.PullLocal(fd, output, baseDir), callback) }() } diff --git a/core/src/main/golang/config/fetch.go b/core/src/main/golang/config/fetch.go index b917acf..733571b 100644 --- a/core/src/main/golang/config/fetch.go +++ b/core/src/main/golang/config/fetch.go @@ -79,7 +79,7 @@ func fetchLocal(fd int) ([]byte, error) { return ioutil.ReadAll(file) } -func DownloadRemote(url, output, baseDir string) error { +func PullRemote(url, output, baseDir string) error { data, err := fetchRemote(url) if err != nil { return err @@ -88,7 +88,7 @@ func DownloadRemote(url, output, baseDir string) error { return save(data, output, baseDir) } -func DownloadLocal(fd int, output, baseDir string) error { +func PullLocal(fd int, output, baseDir string) error { data, err := fetchLocal(fd) if err != nil { return err diff --git a/core/src/main/golang/config/patch.go b/core/src/main/golang/config/patch.go index 4313314..2613775 100644 --- a/core/src/main/golang/config/patch.go +++ b/core/src/main/golang/config/patch.go @@ -1,7 +1,6 @@ package config import ( - "fmt" "github.com/Dreamacro/clash/component/fakeip" "github.com/Dreamacro/clash/config" "net/url" @@ -21,12 +20,6 @@ func patchRawConfig(rawConfig *config.RawConfig) { rawConfig.ExternalUI = "" rawConfig.ExternalController = "" - if len(rawConfig.Rule) != 0 { - rawConfig.Rule = append([]string{fmt.Sprintf("IP-CIDR,%s,REJECT,no-resolve", tunAddress)}, rawConfig.Rule...) - } else { - rawConfig.RuleOld = append([]string{fmt.Sprintf("IP-CIDR,%s,REJECT,no-resolve", tunAddress)}, rawConfig.RuleOld...) - } - if d := DnsPatch; d != nil { rawConfig.DNS = *d } else if d := OptionalDnsPatch; d != nil { diff --git a/core/src/main/golang/tun/dns.go b/core/src/main/golang/tun/dns.go index 7bf1e9f..a73320e 100644 --- a/core/src/main/golang/tun/dns.go +++ b/core/src/main/golang/tun/dns.go @@ -98,7 +98,7 @@ func hijackTCPDNS(conn net.Conn, endpoint *binding.Endpoint) bool { return true } -func hijackDNS(payload []byte, endpoint *binding.Endpoint, sender redirect.UDPSender) bool { +func hijackDNS(payload []byte, endpoint *binding.Endpoint, sender redirect.UDPSender, recycle func([]byte)) bool { if endpoint.Target.Port != 53 { return false } @@ -118,6 +118,8 @@ func hijackDNS(payload []byte, endpoint *binding.Endpoint, sender redirect.UDPSe endpoint: endpoint, sender: sender, }, msg) + + recycle(payload) }() return true diff --git a/core/src/main/golang/tun/tun.go b/core/src/main/golang/tun/tun.go index 7cd5eca..3cbc4a6 100644 --- a/core/src/main/golang/tun/tun.go +++ b/core/src/main/golang/tun/tun.go @@ -1,6 +1,7 @@ package tun import ( + "errors" adapters "github.com/Dreamacro/clash/adapters/inbound" "github.com/Dreamacro/clash/component/socks5" C "github.com/Dreamacro/clash/constant" @@ -16,6 +17,10 @@ import ( "github.com/Dreamacro/clash/log" ) +const ( + maxUdpPacketSize = 65535 +) + var adapter *tun2socket.Tun2Socket var mutex sync.Mutex @@ -26,14 +31,42 @@ func StartTunDevice(fd, mtu int, gateway, mirror, dnsAddress string) error { if adapter != nil { adapter.Close() adapter = nil + + log.Infoln("Android tun stopped") + } + + gatewayIP, gatewayNet, err := net.ParseCIDR(gateway) + mirrorIP := net.ParseIP(mirror) + + if err != nil || mirrorIP == nil || !gatewayNet.Contains(mirrorIP) { + return errors.New("invalid gateway or mirror") + } + + udpPool := sync.Pool{New: func() interface{} { + return make([]byte, maxUdpPacketSize) + }} + udpRecycle := func(bytes []byte) { + if cap(bytes) == maxUdpPacketSize { + udpPool.Put(bytes[:maxUdpPacketSize]) + } } file := os.NewFile(uintptr(fd), "/dev/tun") _ = syscall.SetNonblock(fd, true) - adapter = tun2socket.NewTun2Socket(file, mtu, net.ParseIP(gateway).To4(), net.ParseIP(mirror).To4()) + adapter = tun2socket.NewTun2Socket(file, mtu, gatewayIP, mirrorIP.To4()) + adapter.SetAllocator(func(length int) []byte { + if length <= maxUdpPacketSize { + return udpPool.Get().([]byte)[:length] + } + return make([]byte, length) + }) adapter.SetTCPHandler(func(conn net.Conn, endpoint *binding.Endpoint) { + if gatewayNet.Contains(endpoint.Target.IP) { + return + } + if hijackTCPDNS(conn, endpoint) { return } @@ -47,7 +80,12 @@ func StartTunDevice(fd, mtu int, gateway, mirror, dnsAddress string) error { tunnel.Add(adapters.NewSocket(addr, conn, C.SOCKS, C.TCP)) }) adapter.SetUDPHandler(func(payload []byte, endpoint *binding.Endpoint, sender redirect.UDPSender) { - if hijackDNS(payload, endpoint, sender) { + if gatewayNet.Contains(endpoint.Target.IP) { + udpRecycle(payload) + return + } + + if hijackDNS(payload, endpoint, sender, udpRecycle) { return } @@ -82,7 +120,7 @@ func StopTunDevice() { if adapter != nil { adapter.Close() adapter = nil - } - log.Infoln("Android tun stopped") -} \ No newline at end of file + log.Infoln("Android tun stopped") + } +} diff --git a/core/src/main/java/com/github/kr328/clash/core/Clash.kt b/core/src/main/java/com/github/kr328/clash/core/Clash.kt index b2aad7e..c9cec9a 100644 --- a/core/src/main/java/com/github/kr328/clash/core/Clash.kt +++ b/core/src/main/java/com/github/kr328/clash/core/Clash.kt @@ -29,9 +29,7 @@ object Clash { val bytes = context.assets.open("Country.mmdb") .use(InputStream::readBytes) - Bridge.loadMMDB(bytes) - Bridge.setHome(context.cacheDir.absolutePath) - Bridge.setApplicationVersion(BuildConfig.VERSION_NAME) + Bridge.initCore(bytes, context.cacheDir.absolutePath, BuildConfig.VERSION_NAME) Bridge.reset() } diff --git a/service/src/main/java/com/github/kr328/clash/service/TunService.kt b/service/src/main/java/com/github/kr328/clash/service/TunService.kt index 321d43b..f31ac3f 100644 --- a/service/src/main/java/com/github/kr328/clash/service/TunService.kt +++ b/service/src/main/java/com/github/kr328/clash/service/TunService.kt @@ -9,6 +9,7 @@ import com.github.kr328.clash.service.settings.ServiceSettings import com.github.kr328.clash.service.util.asSocketAddressText import com.github.kr328.clash.service.util.broadcastNetworkChanged import kotlinx.coroutines.* +import kotlin.time.Duration class TunService : VpnService(), CoroutineScope by MainScope() { companion object { @@ -48,7 +49,7 @@ class TunService : VpnService(), CoroutineScope by MainScope() { Clash.setDnsOverrideEnabled(settings.get(ServiceSettings.OVERRIDE_DNS)) Clash.startTunDevice(fd.detachFd(), VPN_MTU, - PRIVATE_VLAN4_CLIENT, PRIVATE_VLAN4_MIRROR, + "$PRIVATE_VLAN4_CLIENT/$PRIVATE_VLAN4_SUBNET", PRIVATE_VLAN4_MIRROR, dnsAddress, this::protect, this::stopSelf)