From c77993eed3b7c349429dc65807fd91adb3c1b7e0 Mon Sep 17 00:00:00 2001 From: adlyq <2833154405@qq.com> Date: Sat, 23 Apr 2022 17:31:16 +0800 Subject: [PATCH] refactor: tidy auto-route code --- listener/tun/ipstack/commons/router_linux.go | 28 +++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/listener/tun/ipstack/commons/router_linux.go b/listener/tun/ipstack/commons/router_linux.go index 1259ab75..ff6f8ec7 100644 --- a/listener/tun/ipstack/commons/router_linux.go +++ b/listener/tun/ipstack/commons/router_linux.go @@ -48,22 +48,11 @@ func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { return err } } - _, err := cmd.ExecCmd(fmt.Sprintf("ip rule add from 0.0.0.0 iif lo uidrange 0-4294967294 lookup %d pref 9000", tableId)) - if err != nil { - log.Warnln("%s", err) - } - _, err = cmd.ExecCmd(fmt.Sprintf("ip rule add from %s iif lo uidrange 0-4294967294 lookup %d pref 9001", linkIP, tableId)) - if err != nil { - log.Warnln("%s", err) - } - _, err = cmd.ExecCmd(fmt.Sprintf("ip rule add from all iif %s lookup main suppress_prefixlength 0 pref 9002", interfaceName)) - if err != nil { - log.Warnln("%s", err) - } - _, err = cmd.ExecCmd(fmt.Sprintf("ip rule add not from all iif lo lookup %d pref 9003", tableId)) - if err != nil { - log.Warnln("%s", err) - } + execAddRuleCmd(fmt.Sprintf("from 0.0.0.0 iif lo uidrange 0-4294967294 lookup %d pref 9000", tableId)) + execAddRuleCmd(fmt.Sprintf("from %s iif lo uidrange 0-4294967294 lookup %d pref 9001", linkIP, tableId)) + execAddRuleCmd(fmt.Sprintf("from all iif %s lookup main suppress_prefixlength 0 pref 9002", interfaceName)) + execAddRuleCmd(fmt.Sprintf("not from all iif lo lookup %d pref 9003", tableId)) + } else { for _, route := range defaultRoutes { if err := execRouterCmd("add", route, interfaceName, linkIP.String(), "main"); err != nil { @@ -77,6 +66,13 @@ func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { return nil } +func execAddRuleCmd(rule string) { + _, err := cmd.ExecCmd("ip rule add " + rule) + if err != nil { + log.Warnln("%s", err) + } +} + func execRouterCmd(action, route, interfaceName, linkIP, table string) error { cmdStr := fmt.Sprintf("ip route %s %s dev %s proto kernel scope link src %s table %s", action, route, interfaceName, linkIP, table)