From 3373b62b02282982d4646548e36383ea45d33615 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Thu, 3 Nov 2022 12:58:21 +0800 Subject: [PATCH] fix: try to support android hotspot when using tun --- listener/sing_tun/server.go | 5 ++++- listener/sing_tun/server_android.go | 26 ++++++++++++++++++++++++++ listener/sing_tun/server_notandroid.go | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/listener/sing_tun/server.go b/listener/sing_tun/server.go index f1327b33..83d38e28 100644 --- a/listener/sing_tun/server.go +++ b/listener/sing_tun/server.go @@ -203,11 +203,14 @@ func New(options config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.P if err != nil { return } - err = l.tunStack.Start() + err = l.tunStack.Start() if err != nil { return } + + l.openAndroidHotspot(tunOptions) + log.Infoln("[TUN] Tun adapter listening at: %s(%s,%s), mtu: %d, auto route: %v, ip stack: %s", tunName, tunOptions.Inet4Address, tunOptions.Inet6Address, tunMTU, options.AutoRoute, options.Stack) return diff --git a/listener/sing_tun/server_android.go b/listener/sing_tun/server_android.go index e9d36f66..f8befe6e 100644 --- a/listener/sing_tun/server_android.go +++ b/listener/sing_tun/server_android.go @@ -1,7 +1,11 @@ package sing_tun import ( + "github.com/Dreamacro/clash/log" + "github.com/sagernet/netlink" tun "github.com/sagernet/sing-tun" + "golang.org/x/sys/unix" + "runtime" ) func (l *Listener) buildAndroidRules(tunOptions *tun.Options) error { @@ -21,3 +25,25 @@ func (l *Listener) buildAndroidRules(tunOptions *tun.Options) error { func (h *ListenerHandler) OnPackagesUpdated(packages int, sharedUsers int) { return } + +func (l *Listener) openAndroidHotspot(tunOptions tun.Options) { + if runtime.GOOS == "android" && tunOptions.AutoRoute { + priority := 9000 + if len(tunOptions.ExcludedRanges()) > 0 { + priority++ + } + if tunOptions.InterfaceMonitor.AndroidVPNEnabled() { + priority++ + } + it := netlink.NewRule() + it.Priority = priority + it.IifName = tunOptions.Name + it.Table = 254 //main + it.Family = unix.AF_INET + it.SuppressPrefixlen = 0 + err := netlink.RuleAdd(it) + if err != nil { + log.Warnln("[TUN] add AndroidHotspot rule error") + } + } +} diff --git a/listener/sing_tun/server_notandroid.go b/listener/sing_tun/server_notandroid.go index f621c71e..6db98989 100644 --- a/listener/sing_tun/server_notandroid.go +++ b/listener/sing_tun/server_notandroid.go @@ -9,3 +9,4 @@ import ( func (l *Listener) buildAndroidRules(tunOptions *tun.Options) error { return nil } +func (l *Listener) openAndroidHotspot(tunOptions tun.Options) {}