manager.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. package routing
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/vishvananda/netlink"
  17. )
  18. var (
  19. StaticRoutesStorePath = "/etc/debtik/routing/static_routes.json"
  20. PolicyRulesStorePath = "/etc/debtik/routing/policy_rules.json"
  21. CustomTablesStorePath = "/etc/debtik/routing/custom_tables.json"
  22. RTTableFilePath = "/etc/iproute2/rt_tables"
  23. )
  24. type RoutingManager struct {
  25. mu sync.Mutex
  26. staticRoutes []RouteItem
  27. policyRules []PolicyRuleItem
  28. customTables []RoutingTableItem
  29. stopChan chan struct{}
  30. }
  31. func NewRoutingManager() *RoutingManager {
  32. m := &RoutingManager{
  33. staticRoutes: make([]RouteItem, 0),
  34. policyRules: make([]PolicyRuleItem, 0),
  35. customTables: make([]RoutingTableItem, 0),
  36. stopChan: make(chan struct{}),
  37. }
  38. m.initRTTableFile()
  39. m.load()
  40. m.syncCustomTablesToSystem()
  41. m.applyAll()
  42. m.startHealthCheckWorker()
  43. m.startRouteSyncWorker()
  44. return m
  45. }
  46. func (m *RoutingManager) initRTTableFile() {
  47. _ = os.MkdirAll(filepath.Dir(RTTableFilePath), 0755)
  48. if _, err := os.Stat(RTTableFilePath); os.IsNotExist(err) {
  49. // Copy from /usr/share/iproute2/rt_tables or seed default
  50. content, err := os.ReadFile("/usr/share/iproute2/rt_tables")
  51. if err == nil {
  52. _ = os.WriteFile(RTTableFilePath, content, 0644)
  53. } else {
  54. defaultContent := "# reserved values\n255\tlocal\n254\tmain\n253\tdefault\n0\tunspec\n"
  55. _ = os.WriteFile(RTTableFilePath, []byte(defaultContent), 0644)
  56. }
  57. }
  58. }
  59. func (m *RoutingManager) load() {
  60. if data, err := os.ReadFile(StaticRoutesStorePath); err == nil {
  61. _ = json.Unmarshal(data, &m.staticRoutes)
  62. }
  63. if data, err := os.ReadFile(PolicyRulesStorePath); err == nil {
  64. _ = json.Unmarshal(data, &m.policyRules)
  65. }
  66. if data, err := os.ReadFile(CustomTablesStorePath); err == nil {
  67. _ = json.Unmarshal(data, &m.customTables)
  68. }
  69. // Deduplicate static routes: if duplicates exist, keep the latest entry
  70. seenIDs := make(map[string]bool)
  71. seenKeys := make(map[string]bool)
  72. var dedupedRev []RouteItem
  73. hasDups := false
  74. // Traverse from end to start so latest updates take precedence
  75. for i := len(m.staticRoutes) - 1; i >= 0; i-- {
  76. r := m.staticRoutes[i]
  77. if r.ID == "" {
  78. r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  79. }
  80. normDst := normalizeDst(r.DstAddress)
  81. tbl := r.RoutingTable
  82. if tbl == "" {
  83. tbl = "main"
  84. }
  85. gw := strings.TrimSpace(r.Gateway)
  86. iface := strings.TrimSpace(r.Interface)
  87. routeKey := fmt.Sprintf("%s|%s|%s|%s|%d", normDst, tbl, gw, iface, r.Distance)
  88. if seenIDs[r.ID] || seenKeys[routeKey] {
  89. log.Printf("[RouteManager] Pruning duplicate static route on load: ID=%s dst=%s gw=%s iface=%s", r.ID, r.DstAddress, r.Gateway, r.Interface)
  90. hasDups = true
  91. continue
  92. }
  93. seenIDs[r.ID] = true
  94. seenKeys[routeKey] = true
  95. dedupedRev = append(dedupedRev, r)
  96. }
  97. // Reverse back to original order
  98. var deduped []RouteItem
  99. for i := len(dedupedRev) - 1; i >= 0; i-- {
  100. deduped = append(deduped, dedupedRev[i])
  101. }
  102. if hasDups {
  103. m.staticRoutes = deduped
  104. _ = m.save()
  105. }
  106. for i := range m.staticRoutes {
  107. if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
  108. m.staticRoutes[i].Active = true
  109. }
  110. }
  111. }
  112. func (m *RoutingManager) save() error {
  113. _ = os.MkdirAll("/etc/debtik/routing", 0755)
  114. if data, err := json.MarshalIndent(m.staticRoutes, "", " "); err != nil {
  115. return err
  116. } else if err = os.WriteFile(StaticRoutesStorePath, data, 0600); err != nil {
  117. return err
  118. }
  119. if data, err := json.MarshalIndent(m.policyRules, "", " "); err != nil {
  120. return err
  121. } else if err = os.WriteFile(PolicyRulesStorePath, data, 0600); err != nil {
  122. return err
  123. }
  124. if data, err := json.MarshalIndent(m.customTables, "", " "); err != nil {
  125. return err
  126. } else if err = os.WriteFile(CustomTablesStorePath, data, 0600); err != nil {
  127. return err
  128. }
  129. return nil
  130. }
  131. func (m *RoutingManager) syncCustomTablesToSystem() {
  132. content, _ := os.ReadFile(RTTableFilePath)
  133. str := string(content)
  134. var sb strings.Builder
  135. sb.WriteString(str)
  136. for _, t := range m.customTables {
  137. check := fmt.Sprintf("\t%s", t.Name)
  138. if !strings.Contains(str, check) {
  139. sb.WriteString(fmt.Sprintf("%d\t%s\n", t.TableID, t.Name))
  140. }
  141. }
  142. _ = os.WriteFile(RTTableFilePath, []byte(sb.String()), 0644)
  143. }
  144. func (m *RoutingManager) cleanRogueDefaultRoutes() {
  145. hasManagedDefault := false
  146. for _, r := range m.staticRoutes {
  147. if normalizeDst(r.DstAddress) == "default" && !r.Disabled {
  148. hasManagedDefault = true
  149. break
  150. }
  151. }
  152. if !hasManagedDefault {
  153. return
  154. }
  155. routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  156. if err != nil {
  157. return
  158. }
  159. links, _ := netlink.LinkList()
  160. linkMap := make(map[int]string)
  161. for _, l := range links {
  162. linkMap[l.Attrs().Index] = l.Attrs().Name
  163. }
  164. for _, r := range routes {
  165. if (r.Table == 254 || r.Table == 0) && r.Dst == nil && len(r.MultiPath) == 0 {
  166. gw := ""
  167. if r.Gw != nil {
  168. gw = r.Gw.String()
  169. }
  170. ifName := linkMap[r.LinkIndex]
  171. // If priority is 0 (unmetered route from dhclient or boot) and protocol != RTPROT_STATIC:
  172. if r.Priority == 0 && int(r.Protocol) != 4 {
  173. log.Printf("[RouteManager] Removing rogue unmanaged default route: via %s dev %s proto %d", gw, ifName, r.Protocol)
  174. _ = netlink.RouteDel(&r)
  175. }
  176. }
  177. }
  178. }
  179. func (m *RoutingManager) getTableIDByName(name string) int {
  180. name = strings.TrimSpace(name)
  181. if name == "" || name == "main" {
  182. return 254
  183. }
  184. if name == "default" {
  185. return 253
  186. }
  187. if name == "local" {
  188. return 255
  189. }
  190. for id, n := range m.getTableMap() {
  191. if strings.EqualFold(n, name) {
  192. return id
  193. }
  194. }
  195. if id, err := strconv.Atoi(name); err == nil {
  196. return id
  197. }
  198. return 254
  199. }
  200. func (m *RoutingManager) startRouteSyncWorker() {
  201. ticker := time.NewTicker(3 * time.Second)
  202. go func() {
  203. for {
  204. select {
  205. case <-m.stopChan:
  206. ticker.Stop()
  207. return
  208. case <-ticker.C:
  209. m.syncAllRoutesWorker()
  210. }
  211. }
  212. }()
  213. }
  214. func (m *RoutingManager) syncAllRoutesWorker() {
  215. m.mu.Lock()
  216. defer m.mu.Unlock()
  217. // Unmanaged routes belong to DHCP, the host or other routing daemons.
  218. liveRoutes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  219. if err != nil {
  220. return
  221. }
  222. type groupKey struct {
  223. dst string
  224. table int
  225. dist int
  226. }
  227. kernelRouteGroups := make(map[groupKey]bool)
  228. for _, lr := range liveRoutes {
  229. dst := "default"
  230. if lr.Dst != nil {
  231. dst = lr.Dst.String()
  232. }
  233. tbl := lr.Table
  234. if tbl == 0 {
  235. tbl = 254
  236. }
  237. k := groupKey{dst: normalizeDst(dst), table: tbl, dist: lr.Priority}
  238. kernelRouteGroups[k] = true
  239. }
  240. seen := make(map[groupKey]bool)
  241. for _, r := range m.staticRoutes {
  242. if r.Disabled || r.HealthStatus == "offline" {
  243. continue
  244. }
  245. normDst := normalizeDst(r.DstAddress)
  246. tableID := m.getTableIDByName(r.RoutingTable)
  247. k := groupKey{dst: normDst, table: tableID, dist: r.Distance}
  248. if !seen[k] {
  249. seen[k] = true
  250. if !kernelRouteGroups[k] {
  251. log.Printf("[RouteSync] Missing kernel route %s table %s (id %d) metric %d -> Restoring", normDst, r.RoutingTable, tableID, r.Distance)
  252. if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
  253. log.Printf("route synchronization failed: %v", err)
  254. }
  255. }
  256. }
  257. }
  258. }
  259. func (m *RoutingManager) applyAll() {
  260. // Unmanaged routes belong to DHCP, the host or other routing daemons.
  261. // Apply all static routes grouped by (dst, table, distance) for ECMP
  262. type groupKey struct {
  263. dst string
  264. table string
  265. dist int
  266. }
  267. seen := make(map[groupKey]bool)
  268. for _, r := range m.staticRoutes {
  269. normDst := normalizeDst(r.DstAddress)
  270. tbl := strings.TrimSpace(r.RoutingTable)
  271. if tbl == "" {
  272. tbl = "main"
  273. }
  274. k := groupKey{dst: normDst, table: tbl, dist: r.Distance}
  275. if !seen[k] {
  276. seen[k] = true
  277. _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  278. }
  279. }
  280. // Apply policy rules
  281. for _, pr := range m.policyRules {
  282. _ = m.applyRuleToKernel(pr)
  283. }
  284. }
  285. // ==================== Routes (/ip route) ====================
  286. func isDynamicProtocol(proto netlink.RouteProtocol) bool {
  287. switch int(proto) {
  288. case 11, // RTPROT_ZEBRA
  289. 12, // RTPROT_BIRD
  290. 16, // RTPROT_DHCP
  291. 42, // RTPROT_BABEL
  292. 186, // RTPROT_BGP
  293. 187, // RTPROT_ISIS
  294. 188, // RTPROT_OSPF
  295. 189, // RTPROT_RIP
  296. 192: // RTPROT_EIGRP
  297. return true
  298. default:
  299. return false
  300. }
  301. }
  302. func getRouteProtocolName(proto netlink.RouteProtocol, priority int, isDirect bool, isMulticast bool) string {
  303. if isMulticast {
  304. return "multicast"
  305. }
  306. switch int(proto) {
  307. case 16:
  308. return "dhcp"
  309. case 4:
  310. return "static"
  311. case 186:
  312. return "bgp"
  313. case 188:
  314. return "ospf"
  315. case 189:
  316. return "rip"
  317. case 11:
  318. return "zebra"
  319. case 42:
  320. return "babel"
  321. case 12: // RTPROT_BIRD
  322. if priority == 20 {
  323. return "bgp"
  324. } else if priority == 200 {
  325. return "ibgp"
  326. } else if priority == 110 {
  327. return "ospf"
  328. } else if priority == 120 {
  329. return "rip"
  330. }
  331. return "bgp"
  332. case 2:
  333. return "connected"
  334. case 3:
  335. return "boot"
  336. default:
  337. if isDirect {
  338. return "connected"
  339. }
  340. if priority == 20 {
  341. return "bgp"
  342. } else if priority == 200 {
  343. return "ibgp"
  344. } else if priority == 110 {
  345. return "ospf"
  346. } else if priority == 120 {
  347. return "rip"
  348. }
  349. return "static"
  350. }
  351. }
  352. func (m *RoutingManager) listLiveRoutesLocked() []RouteItem {
  353. tableNames := m.getTableMap()
  354. links, _ := netlink.LinkList()
  355. linkMap := make(map[int]string)
  356. for _, l := range links {
  357. linkMap[l.Attrs().Index] = l.Attrs().Name
  358. }
  359. var liveRoutes []RouteItem
  360. routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  361. if err == nil {
  362. for _, r := range routes {
  363. dst := "0.0.0.0/0"
  364. if r.Dst != nil {
  365. dst = r.Dst.String()
  366. }
  367. gw := ""
  368. if r.Gw != nil {
  369. gw = r.Gw.String()
  370. }
  371. tableName := "main"
  372. if name, ok := tableNames[r.Table]; ok {
  373. tableName = name
  374. } else if r.Table != 254 && r.Table != 0 {
  375. tableName = strconv.Itoa(r.Table)
  376. }
  377. isDyn := isDynamicProtocol(r.Protocol)
  378. isDirect := (r.Scope == netlink.SCOPE_LINK || r.Protocol == netlink.RouteProtocol(2)) && !isDyn && r.Protocol != 4
  379. isStatic := !isDirect && !isDyn
  380. isMulticast := r.Type == 5 || strings.HasPrefix(dst, "224.") || strings.HasPrefix(dst, "ff") || dst == "224.0.0.0/4"
  381. protoName := getRouteProtocolName(r.Protocol, r.Priority, isDirect, isMulticast)
  382. if len(r.MultiPath) > 0 {
  383. for _, nh := range r.MultiPath {
  384. nhGw := ""
  385. if nh.Gw != nil {
  386. nhGw = nh.Gw.String()
  387. }
  388. nhIfName := linkMap[nh.LinkIndex]
  389. cleanDst := strings.ReplaceAll(dst, "/", "_")
  390. cleanGw := nhGw
  391. if cleanGw == "" {
  392. cleanGw = nhIfName
  393. }
  394. routeID := fmt.Sprintf("kr-%d-%s-%s", r.Table, cleanDst, cleanGw)
  395. liveRoutes = append(liveRoutes, RouteItem{
  396. ID: routeID,
  397. DstAddress: dst,
  398. Gateway: nhGw,
  399. Interface: nhIfName,
  400. Distance: r.Priority,
  401. Protocol: protoName,
  402. RoutingTable: tableName,
  403. TableID: r.Table,
  404. Active: true,
  405. Connect: isDirect,
  406. Dynamic: isDyn,
  407. Static: isStatic,
  408. ECMP: true,
  409. IsMultiPath: true,
  410. Multicast: isMulticast,
  411. Disabled: false,
  412. })
  413. }
  414. continue
  415. }
  416. ifName := linkMap[r.LinkIndex]
  417. act := "lookup"
  418. if r.Type == 6 { // RTN_BLACKHOLE
  419. gw = "blackhole"
  420. act = "blackhole"
  421. }
  422. cleanDst := strings.ReplaceAll(dst, "/", "_")
  423. cleanGw := gw
  424. if cleanGw == "" {
  425. cleanGw = ifName
  426. }
  427. routeID := fmt.Sprintf("kr-%d-%s-%s", r.Table, cleanDst, cleanGw)
  428. liveRoutes = append(liveRoutes, RouteItem{
  429. ID: routeID,
  430. DstAddress: dst,
  431. Gateway: gw,
  432. Action: act,
  433. Interface: ifName,
  434. Distance: r.Priority,
  435. Protocol: protoName,
  436. RoutingTable: tableName,
  437. TableID: r.Table,
  438. Active: true,
  439. Connect: isDirect,
  440. Dynamic: isDyn,
  441. Static: isStatic,
  442. Multicast: isMulticast,
  443. Disabled: false,
  444. })
  445. }
  446. }
  447. return liveRoutes
  448. }
  449. func (m *RoutingManager) ListRoutes() []RouteItem {
  450. m.mu.Lock()
  451. defer m.mu.Unlock()
  452. liveRoutes := m.listLiveRoutesLocked()
  453. // Merge static routes that might be disabled or have custom metadata
  454. matchedLive := make(map[int]bool)
  455. for _, sr := range m.staticRoutes {
  456. normSrDst := normalizeDst(sr.DstAddress)
  457. found := false
  458. for i, lr := range liveRoutes {
  459. if matchedLive[i] {
  460. continue
  461. }
  462. if normalizeDst(lr.DstAddress) != normSrDst {
  463. continue
  464. }
  465. if lr.RoutingTable != sr.RoutingTable {
  466. continue
  467. }
  468. gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
  469. if gwMatches {
  470. matchedLive[i] = true
  471. liveRoutes[i].Comment = sr.Comment
  472. liveRoutes[i].Static = true
  473. liveRoutes[i].Dynamic = false
  474. liveRoutes[i].Protocol = "static"
  475. liveRoutes[i].ID = sr.ID
  476. if liveRoutes[i].Gateway == "" && sr.Gateway != "" {
  477. liveRoutes[i].Gateway = sr.Gateway
  478. }
  479. if sr.Distance > 0 && liveRoutes[i].Distance == 0 {
  480. liveRoutes[i].Distance = sr.Distance
  481. }
  482. liveRoutes[i].CheckGateway = sr.CheckGateway
  483. liveRoutes[i].CheckTarget = sr.CheckTarget
  484. liveRoutes[i].CheckInterval = sr.CheckInterval
  485. liveRoutes[i].CheckThreshold = sr.CheckThreshold
  486. liveRoutes[i].HealthStatus = sr.HealthStatus
  487. liveRoutes[i].HealthRTT = sr.HealthRTT
  488. liveRoutes[i].HealthLossPct = sr.HealthLossPct
  489. liveRoutes[i].HealthFailCount = sr.HealthFailCount
  490. liveRoutes[i].HealthLastCheck = sr.HealthLastCheck
  491. found = true
  492. break
  493. }
  494. }
  495. if !found {
  496. // Inactive or disabled static route
  497. srCopy := sr
  498. srCopy.Active = false
  499. srCopy.Static = true
  500. srCopy.Dynamic = false
  501. srCopy.Protocol = "static"
  502. liveRoutes = append(liveRoutes, srCopy)
  503. }
  504. }
  505. // Detect Equal-Cost Multi-Path (ECMP) routes
  506. groupCounts := make(map[string]int)
  507. for _, r := range liveRoutes {
  508. if r.Active && !r.Disabled {
  509. key := fmt.Sprintf("%s|%s|%d", normalizeDst(r.DstAddress), r.RoutingTable, r.Distance)
  510. groupCounts[key]++
  511. }
  512. }
  513. for i := range liveRoutes {
  514. key := fmt.Sprintf("%s|%s|%d", normalizeDst(liveRoutes[i].DstAddress), liveRoutes[i].RoutingTable, liveRoutes[i].Distance)
  515. if liveRoutes[i].IsMultiPath || (liveRoutes[i].Active && !liveRoutes[i].Disabled && groupCounts[key] > 1) {
  516. liveRoutes[i].ECMP = true
  517. }
  518. if liveRoutes[i].DstAddress == "224.0.0.0/4" || strings.HasPrefix(liveRoutes[i].DstAddress, "224.") || strings.HasPrefix(liveRoutes[i].DstAddress, "ff") {
  519. liveRoutes[i].Multicast = true
  520. }
  521. }
  522. sort.Slice(liveRoutes, func(i, j int) bool {
  523. if liveRoutes[i].RoutingTable != liveRoutes[j].RoutingTable {
  524. return liveRoutes[i].RoutingTable < liveRoutes[j].RoutingTable
  525. }
  526. if liveRoutes[i].DstAddress != liveRoutes[j].DstAddress {
  527. return liveRoutes[i].DstAddress < liveRoutes[j].DstAddress
  528. }
  529. return liveRoutes[i].Gateway < liveRoutes[j].Gateway
  530. })
  531. return liveRoutes
  532. }
  533. func (m *RoutingManager) SaveRoute(r *RouteItem) (err error) {
  534. if r == nil {
  535. return fmt.Errorf("route cannot be nil")
  536. }
  537. m.mu.Lock()
  538. defer m.mu.Unlock()
  539. before := append([]RouteItem(nil), m.staticRoutes...)
  540. dirty, applied := false, false
  541. defer func() {
  542. if err != nil && dirty {
  543. m.staticRoutes = before
  544. if applied {
  545. _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  546. }
  547. m.applyAll()
  548. _ = m.save()
  549. }
  550. }()
  551. if r.DstAddress == "" {
  552. return fmt.Errorf("destination address is required")
  553. }
  554. if r.DstAddress == "default" {
  555. r.DstAddress = "0.0.0.0/0"
  556. }
  557. if r.RoutingTable == "" {
  558. r.RoutingTable = "main"
  559. }
  560. if _, _, parseErr := net.ParseCIDR(r.DstAddress); parseErr != nil && net.ParseIP(r.DstAddress) == nil {
  561. return fmt.Errorf("invalid destination: %s", r.DstAddress)
  562. }
  563. dirty = true
  564. r.Static = true
  565. origID := r.ID
  566. foundIndex := -1
  567. // 1. Direct ID match in static routes (if not a temporary/kernel route ID)
  568. if r.ID != "" && !strings.HasPrefix(r.ID, "kr-") {
  569. for i, existing := range m.staticRoutes {
  570. if existing.ID == r.ID {
  571. foundIndex = i
  572. break
  573. }
  574. }
  575. }
  576. // 2. Match by OldDstAddress / OldGateway passed from the edit modal
  577. if foundIndex == -1 && r.OldDstAddress != "" {
  578. normOldDst := normalizeDst(r.OldDstAddress)
  579. oldTable := r.OldRoutingTable
  580. if oldTable == "" {
  581. oldTable = "main"
  582. }
  583. for i, existing := range m.staticRoutes {
  584. exTbl := existing.RoutingTable
  585. if exTbl == "" {
  586. exTbl = "main"
  587. }
  588. if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
  589. oldGwMatches := r.OldGateway == "" ||
  590. existing.Gateway == r.OldGateway ||
  591. existing.Interface == r.OldGateway ||
  592. (r.OldInterface != "" && existing.Interface == r.OldInterface)
  593. if oldGwMatches {
  594. foundIndex = i
  595. break
  596. }
  597. }
  598. }
  599. }
  600. // 3. Match by target DstAddress + Table + Gateway/Interface (prevent duplicates on re-save)
  601. if foundIndex == -1 {
  602. normNewDst := normalizeDst(r.DstAddress)
  603. for i, existing := range m.staticRoutes {
  604. exTbl := existing.RoutingTable
  605. if exTbl == "" {
  606. exTbl = "main"
  607. }
  608. if normalizeDst(existing.DstAddress) == normNewDst && exTbl == r.RoutingTable {
  609. gwMatches := (existing.Gateway != "" && existing.Gateway == r.Gateway) ||
  610. (existing.Interface != "" && existing.Interface == r.Interface) ||
  611. (existing.Gateway == "" && r.Gateway == "")
  612. if gwMatches {
  613. foundIndex = i
  614. break
  615. }
  616. }
  617. }
  618. }
  619. // 4. Fallback match: if editing with OldDstAddress but gateway was changed and didn't match oldGw
  620. if foundIndex == -1 && r.OldDstAddress != "" {
  621. normOldDst := normalizeDst(r.OldDstAddress)
  622. oldTable := r.OldRoutingTable
  623. if oldTable == "" {
  624. oldTable = "main"
  625. }
  626. for i, existing := range m.staticRoutes {
  627. exTbl := existing.RoutingTable
  628. if exTbl == "" {
  629. exTbl = "main"
  630. }
  631. if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
  632. foundIndex = i
  633. break
  634. }
  635. }
  636. }
  637. if r.CheckInterval <= 0 {
  638. r.CheckInterval = 5
  639. }
  640. if r.CheckThreshold <= 0 {
  641. r.CheckThreshold = 3
  642. }
  643. if r.CheckGateway == "internet" && strings.TrimSpace(r.CheckTarget) == "" {
  644. r.CheckTarget = "1.1.1.1"
  645. }
  646. if r.CheckGateway != "" && r.CheckGateway != "none" {
  647. if r.HealthStatus == "" {
  648. r.HealthStatus = "checking"
  649. }
  650. } else {
  651. r.CheckGateway = "none"
  652. r.HealthStatus = "none"
  653. }
  654. var oldRouteToClean *RouteItem
  655. if foundIndex >= 0 {
  656. oldExisting := m.staticRoutes[foundIndex]
  657. r.ID = oldExisting.ID // Preserve persistent ID!
  658. if normalizeDst(oldExisting.DstAddress) != normalizeDst(r.DstAddress) ||
  659. oldExisting.RoutingTable != r.RoutingTable ||
  660. oldExisting.Distance != r.Distance ||
  661. oldExisting.Gateway != r.Gateway ||
  662. oldExisting.Interface != r.Interface {
  663. oldCopy := oldExisting
  664. oldRouteToClean = &oldCopy
  665. }
  666. if r.HealthStatus == "checking" && oldExisting.HealthStatus != "" && oldExisting.CheckGateway == r.CheckGateway {
  667. r.HealthStatus = oldExisting.HealthStatus
  668. r.HealthRTT = oldExisting.HealthRTT
  669. r.HealthLossPct = oldExisting.HealthLossPct
  670. r.HealthLastCheck = oldExisting.HealthLastCheck
  671. }
  672. m.staticRoutes[foundIndex] = *r
  673. } else {
  674. if r.ID == "" || strings.HasPrefix(r.ID, "kr-") {
  675. r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  676. }
  677. // If adopting a live kernel route not in staticRoutes, remove it from direct kernel routes
  678. if strings.HasPrefix(origID, "kr-") {
  679. for _, lr := range m.listLiveRoutesLocked() {
  680. if lr.ID == origID {
  681. _ = m.deleteDirectKernelRoute(lr)
  682. break
  683. }
  684. }
  685. }
  686. m.staticRoutes = append(m.staticRoutes, *r)
  687. }
  688. if r.OldDstAddress != "" {
  689. oldDist := 0
  690. if r.OldDistance != nil {
  691. oldDist = *r.OldDistance
  692. }
  693. if normalizeDst(r.OldDstAddress) != normalizeDst(r.DstAddress) ||
  694. r.OldRoutingTable != r.RoutingTable ||
  695. oldDist != r.Distance ||
  696. r.OldGateway != r.Gateway ||
  697. r.OldInterface != r.Interface {
  698. oldRouteToClean = &RouteItem{
  699. DstAddress: r.OldDstAddress,
  700. Gateway: r.OldGateway,
  701. RoutingTable: r.OldRoutingTable,
  702. Distance: oldDist,
  703. Interface: r.OldInterface,
  704. }
  705. }
  706. }
  707. for i := range m.staticRoutes {
  708. if m.staticRoutes[i].ID == r.ID {
  709. if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
  710. m.staticRoutes[i].Active = true
  711. } else {
  712. m.staticRoutes[i].Active = false
  713. }
  714. break
  715. }
  716. }
  717. // In-memory deduplication pass on static routes
  718. seenKeys := make(map[string]bool)
  719. var deduped []RouteItem
  720. for _, sr := range m.staticRoutes {
  721. k := fmt.Sprintf("%s|%s|%s|%s|%d", normalizeDst(sr.DstAddress), sr.RoutingTable, sr.Gateway, sr.Interface, sr.Distance)
  722. if !seenKeys[k] {
  723. seenKeys[k] = true
  724. deduped = append(deduped, sr)
  725. }
  726. }
  727. m.staticRoutes = deduped
  728. if saveErr := m.save(); saveErr != nil {
  729. return saveErr
  730. }
  731. // Clean up old route group if destination, routing table, distance, gateway, or interface changed
  732. if oldRouteToClean != nil {
  733. _ = m.syncRouteGroupToKernel(oldRouteToClean.DstAddress, oldRouteToClean.RoutingTable, oldRouteToClean.Distance)
  734. _ = m.deleteDirectKernelRoute(*oldRouteToClean)
  735. }
  736. // Apply updated/new route group to kernel
  737. if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
  738. return err
  739. }
  740. applied = true
  741. return nil
  742. }
  743. func (m *RoutingManager) DeleteRoute(id string) error {
  744. m.mu.Lock()
  745. defer m.mu.Unlock()
  746. var updated []RouteItem
  747. var target *RouteItem
  748. // 1. Direct ID match in static routes
  749. for _, r := range m.staticRoutes {
  750. if r.ID == id {
  751. targetCopy := r
  752. target = &targetCopy
  753. } else {
  754. updated = append(updated, r)
  755. }
  756. }
  757. // 2. If not found by direct ID, check if it's a live kernel route ID (e.g. kr-...)
  758. if target == nil {
  759. for _, lr := range m.listLiveRoutesLocked() {
  760. if lr.ID == id {
  761. // Check if any static route corresponds to this live route
  762. matchIdx := -1
  763. normLrDst := normalizeDst(lr.DstAddress)
  764. for i, sr := range m.staticRoutes {
  765. gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
  766. if normalizeDst(sr.DstAddress) == normLrDst && sr.RoutingTable == lr.RoutingTable && gwMatches {
  767. matchIdx = i
  768. break
  769. }
  770. }
  771. if matchIdx >= 0 {
  772. targetCopy := m.staticRoutes[matchIdx]
  773. target = &targetCopy
  774. for idx, r := range m.staticRoutes {
  775. if idx != matchIdx {
  776. updated = append(updated, r)
  777. }
  778. }
  779. _ = m.deleteDirectKernelRoute(lr)
  780. break
  781. } else {
  782. // Pure kernel route, not managed in static_routes.json
  783. return m.deleteDirectKernelRoute(lr)
  784. }
  785. }
  786. }
  787. }
  788. if target != nil {
  789. m.staticRoutes = updated
  790. _ = m.save()
  791. _ = m.syncRouteGroupToKernel(target.DstAddress, target.RoutingTable, target.Distance)
  792. _ = m.deleteDirectKernelRoute(*target)
  793. return nil
  794. }
  795. return fmt.Errorf("route not found")
  796. }
  797. func (m *RoutingManager) SetRouteState(id string, disabled bool) error {
  798. m.mu.Lock()
  799. defer m.mu.Unlock()
  800. for i := range m.staticRoutes {
  801. if m.staticRoutes[i].ID == id {
  802. m.staticRoutes[i].Disabled = disabled
  803. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  804. m.staticRoutes[i].Active = true
  805. } else if disabled {
  806. m.staticRoutes[i].Active = false
  807. }
  808. _ = m.save()
  809. _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
  810. return nil
  811. }
  812. }
  813. // If not in staticRoutes, could be a live route ID (kr-...)
  814. for _, lr := range m.listLiveRoutesLocked() {
  815. if lr.ID == id {
  816. // Check if any static route corresponds to this live route
  817. normLrDst := normalizeDst(lr.DstAddress)
  818. for i := range m.staticRoutes {
  819. gwMatches := m.staticRoutes[i].Gateway == "" || lr.Gateway == m.staticRoutes[i].Gateway || lr.Interface == m.staticRoutes[i].Gateway || (m.staticRoutes[i].Interface != "" && lr.Interface == m.staticRoutes[i].Interface)
  820. if normalizeDst(m.staticRoutes[i].DstAddress) == normLrDst && m.staticRoutes[i].RoutingTable == lr.RoutingTable && gwMatches {
  821. m.staticRoutes[i].Disabled = disabled
  822. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  823. m.staticRoutes[i].Active = true
  824. } else if disabled {
  825. m.staticRoutes[i].Active = false
  826. }
  827. _ = m.save()
  828. _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
  829. return nil
  830. }
  831. }
  832. // If pure kernel static route, adopt into staticRoutes as disabled
  833. if disabled {
  834. lr.Disabled = true
  835. lr.Static = true
  836. lr.Active = false
  837. lr.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  838. m.staticRoutes = append(m.staticRoutes, lr)
  839. _ = m.save()
  840. _ = m.syncRouteGroupToKernel(lr.DstAddress, lr.RoutingTable, lr.Distance)
  841. return nil
  842. }
  843. }
  844. }
  845. return fmt.Errorf("route not found")
  846. }
  847. func sliceContains(list []string, item string) bool {
  848. for _, s := range list {
  849. if s == item {
  850. return true
  851. }
  852. }
  853. return false
  854. }
  855. func normalizeDst(dst string) string {
  856. dst = strings.TrimSpace(dst)
  857. if dst == "" || dst == "default" || dst == "0.0.0.0/0" {
  858. return "default"
  859. }
  860. if !strings.Contains(dst, "/") && net.ParseIP(dst) != nil {
  861. return dst + "/32"
  862. }
  863. return dst
  864. }
  865. func detectGatewayForInterface(ifaceName string) string {
  866. link, err := netlink.LinkByName(ifaceName)
  867. if err == nil {
  868. routes, err := netlink.RouteList(link, netlink.FAMILY_V4)
  869. if err == nil {
  870. for _, r := range routes {
  871. if (r.Dst == nil || r.Dst.IP.IsUnspecified()) && r.Gw != nil && !r.Gw.IsUnspecified() {
  872. return r.Gw.String()
  873. }
  874. }
  875. for _, r := range routes {
  876. if r.Gw != nil && !r.Gw.IsUnspecified() {
  877. return r.Gw.String()
  878. }
  879. }
  880. }
  881. }
  882. out, err := exec.Command("ip", "route", "show", "dev", ifaceName).CombinedOutput()
  883. if err == nil {
  884. lines := strings.Split(string(out), "\n")
  885. for _, l := range lines {
  886. if strings.Contains(l, "via ") {
  887. fields := strings.Fields(l)
  888. for i, f := range fields {
  889. if f == "via" && i+1 < len(fields) {
  890. gw := fields[i+1]
  891. if net.ParseIP(gw) != nil {
  892. return gw
  893. }
  894. }
  895. }
  896. }
  897. }
  898. }
  899. return ""
  900. }
  901. func (m *RoutingManager) syncRouteGroupToKernel(dstAddress, routingTable string, distance int) error {
  902. normDst := normalizeDst(dstAddress)
  903. tbl := strings.TrimSpace(routingTable)
  904. if tbl == "" {
  905. tbl = "main"
  906. }
  907. var activeRoutes []RouteItem
  908. for _, r := range m.staticRoutes {
  909. rDst := normalizeDst(r.DstAddress)
  910. rTbl := strings.TrimSpace(r.RoutingTable)
  911. if rTbl == "" {
  912. rTbl = "main"
  913. }
  914. if rDst == normDst && rTbl == tbl && r.Distance == distance {
  915. if !r.Disabled && r.Active && r.HealthStatus != "offline" {
  916. activeRoutes = append(activeRoutes, r)
  917. }
  918. }
  919. }
  920. if len(activeRoutes) == 0 {
  921. // Safety guard: if all default routes are marked offline, do NOT delete the default route into a blackout!
  922. // Fallback to keeping all enabled static routes in the group active so recovery traffic and emergency pings can flow.
  923. if normDst == "default" {
  924. var fallbackRoutes []RouteItem
  925. for _, r := range m.staticRoutes {
  926. rDst := normalizeDst(r.DstAddress)
  927. rTbl := strings.TrimSpace(r.RoutingTable)
  928. if rTbl == "" {
  929. rTbl = "main"
  930. }
  931. if rDst == normDst && rTbl == tbl && r.Distance == distance && !r.Disabled {
  932. fallbackRoutes = append(fallbackRoutes, r)
  933. }
  934. }
  935. if len(fallbackRoutes) > 0 {
  936. log.Printf("[RouteManager] All default routes offline in group! Keeping fallback routes active to prevent blackout")
  937. activeRoutes = fallbackRoutes
  938. }
  939. }
  940. }
  941. if len(activeRoutes) == 0 {
  942. args := []string{"route", "del", normDst}
  943. if distance > 0 {
  944. args = append(args, "metric", strconv.Itoa(distance))
  945. }
  946. if tbl != "main" {
  947. args = append(args, "table", tbl)
  948. }
  949. args = append(args, "proto", "static")
  950. _ = exec.Command("ip", args...).Run()
  951. // Also delete without proto static in case route protocol differed
  952. fbArgs := []string{"route", "del", normDst}
  953. if distance > 0 {
  954. fbArgs = append(fbArgs, "metric", strconv.Itoa(distance))
  955. }
  956. if tbl != "main" {
  957. fbArgs = append(fbArgs, "table", tbl)
  958. }
  959. _ = exec.Command("ip", fbArgs...).Run()
  960. // Bare fallback
  961. _ = exec.Command("ip", "route", "del", normDst).Run()
  962. // Also delete blackhole route variant if it existed
  963. bhArgs := []string{"route", "del", "blackhole", normDst}
  964. if distance > 0 {
  965. bhArgs = append(bhArgs, "metric", strconv.Itoa(distance))
  966. }
  967. if tbl != "main" {
  968. bhArgs = append(bhArgs, "table", tbl)
  969. }
  970. _ = exec.Command("ip", bhArgs...).Run()
  971. return nil
  972. }
  973. if len(activeRoutes) == 1 {
  974. r := activeRoutes[0]
  975. gw := strings.TrimSpace(r.Gateway)
  976. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  977. var args []string
  978. if isBlackhole {
  979. args = []string{"route", "replace", "blackhole", normDst}
  980. } else {
  981. args = []string{"route", "replace", normDst}
  982. iface := strings.TrimSpace(r.Interface)
  983. hasVia := false
  984. if gw != "" {
  985. if net.ParseIP(gw) != nil {
  986. args = append(args, "via", gw)
  987. hasVia = true
  988. } else {
  989. // Gateway field contains an interface name
  990. targetDev := gw
  991. if iface == "" {
  992. iface = targetDev
  993. }
  994. if detectedGw := detectGatewayForInterface(targetDev); detectedGw != "" {
  995. args = append(args, "via", detectedGw)
  996. hasVia = true
  997. } else {
  998. args = append(args, "dev", targetDev)
  999. }
  1000. }
  1001. }
  1002. if iface != "" && (gw == "" || net.ParseIP(gw) != nil || (gw != "" && detectGatewayForInterface(gw) != "")) {
  1003. args = append(args, "dev", iface)
  1004. }
  1005. if hasVia && iface != "" {
  1006. args = append(args, "onlink")
  1007. }
  1008. }
  1009. if distance > 0 {
  1010. args = append(args, "metric", strconv.Itoa(distance))
  1011. }
  1012. if tbl != "main" {
  1013. args = append(args, "table", tbl)
  1014. }
  1015. args = append(args, "proto", "static")
  1016. cmd := exec.Command("ip", args...)
  1017. if out, err := cmd.CombinedOutput(); err != nil {
  1018. if sliceContains(args, "onlink") {
  1019. var noOnlinkArgs []string
  1020. for _, a := range args {
  1021. if a != "onlink" {
  1022. noOnlinkArgs = append(noOnlinkArgs, a)
  1023. }
  1024. }
  1025. if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
  1026. return nil
  1027. }
  1028. }
  1029. return fmt.Errorf("failed to apply route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1030. }
  1031. return nil
  1032. }
  1033. // Multiple routes: ECMP multipath route
  1034. args := []string{"route", "replace", normDst, "scope", "global"}
  1035. if distance > 0 {
  1036. args = append(args, "metric", strconv.Itoa(distance))
  1037. }
  1038. if tbl != "main" {
  1039. args = append(args, "table", tbl)
  1040. }
  1041. args = append(args, "proto", "static")
  1042. for _, r := range activeRoutes {
  1043. args = append(args, "nexthop")
  1044. gw := strings.TrimSpace(r.Gateway)
  1045. iface := strings.TrimSpace(r.Interface)
  1046. if iface == "" && gw != "" && net.ParseIP(gw) == nil {
  1047. iface = gw
  1048. }
  1049. hasVia := false
  1050. if gw != "" && net.ParseIP(gw) != nil {
  1051. args = append(args, "via", gw)
  1052. hasVia = true
  1053. } else if iface != "" {
  1054. if detectedGw := detectGatewayForInterface(iface); detectedGw != "" {
  1055. args = append(args, "via", detectedGw)
  1056. hasVia = true
  1057. }
  1058. }
  1059. if iface != "" {
  1060. args = append(args, "dev", iface)
  1061. }
  1062. if hasVia && iface != "" {
  1063. args = append(args, "onlink")
  1064. }
  1065. args = append(args, "weight", "1")
  1066. }
  1067. cmd := exec.Command("ip", args...)
  1068. if out, err := cmd.CombinedOutput(); err != nil {
  1069. if sliceContains(args, "onlink") {
  1070. var noOnlinkArgs []string
  1071. for _, a := range args {
  1072. if a != "onlink" {
  1073. noOnlinkArgs = append(noOnlinkArgs, a)
  1074. }
  1075. }
  1076. if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
  1077. return nil
  1078. }
  1079. }
  1080. return fmt.Errorf("failed to apply multipath route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1081. }
  1082. return nil
  1083. }
  1084. func (m *RoutingManager) applyRouteToKernel(r RouteItem) error {
  1085. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1086. }
  1087. func (m *RoutingManager) removeRouteFromKernel(r RouteItem) error {
  1088. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1089. }
  1090. func (m *RoutingManager) deleteDirectKernelRoute(r RouteItem) error {
  1091. normDst := normalizeDst(r.DstAddress)
  1092. gw := strings.TrimSpace(r.Gateway)
  1093. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  1094. var args []string
  1095. if isBlackhole {
  1096. args = []string{"route", "del", "blackhole", normDst}
  1097. } else {
  1098. args = []string{"route", "del", normDst}
  1099. if gw != "" && net.ParseIP(gw) != nil {
  1100. args = append(args, "via", gw)
  1101. }
  1102. iface := strings.TrimSpace(r.Interface)
  1103. if iface != "" {
  1104. args = append(args, "dev", iface)
  1105. }
  1106. }
  1107. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1108. args = append(args, "table", r.RoutingTable)
  1109. }
  1110. if r.Distance > 0 {
  1111. args = append(args, "metric", strconv.Itoa(r.Distance))
  1112. }
  1113. cmd := exec.Command("ip", args...)
  1114. if out, err := cmd.CombinedOutput(); err == nil {
  1115. return nil
  1116. } else {
  1117. log.Printf("[RouteManager] direct ip route del (%s): %s (%v), attempting fallback", strings.Join(args, " "), string(out), err)
  1118. }
  1119. if isBlackhole {
  1120. fbBhArgs := []string{"route", "del", "blackhole", normDst}
  1121. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1122. fbBhArgs = append(fbBhArgs, "table", r.RoutingTable)
  1123. }
  1124. if r.Distance > 0 {
  1125. fbBhArgs = append(fbBhArgs, "metric", strconv.Itoa(r.Distance))
  1126. }
  1127. if err := exec.Command("ip", fbBhArgs...).Run(); err == nil {
  1128. return nil
  1129. }
  1130. return exec.Command("ip", "route", "del", "blackhole", normDst).Run()
  1131. }
  1132. fbArgs := []string{"route", "del", normDst}
  1133. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1134. fbArgs = append(fbArgs, "table", r.RoutingTable)
  1135. }
  1136. if r.Distance > 0 {
  1137. fbArgs = append(fbArgs, "metric", strconv.Itoa(r.Distance))
  1138. }
  1139. if err := exec.Command("ip", fbArgs...).Run(); err == nil {
  1140. return nil
  1141. }
  1142. return exec.Command("ip", "route", "del", normDst).Run()
  1143. }
  1144. // ==================== Policy Rules (/ip route rule) ====================
  1145. func (m *RoutingManager) ListPolicyRules() []PolicyRuleItem {
  1146. m.mu.Lock()
  1147. defer m.mu.Unlock()
  1148. // Query live rules from kernel
  1149. rules, err := netlink.RuleList(netlink.FAMILY_V4)
  1150. if err != nil {
  1151. return m.policyRules
  1152. }
  1153. tableNames := m.getTableMap()
  1154. var res []PolicyRuleItem
  1155. userRulesByPrio := make(map[int]PolicyRuleItem)
  1156. for _, pr := range m.policyRules {
  1157. userRulesByPrio[pr.Priority] = pr
  1158. }
  1159. for _, r := range rules {
  1160. tableName := "main"
  1161. if name, ok := tableNames[r.Table]; ok {
  1162. tableName = name
  1163. } else if r.Table != 254 && r.Table != 0 {
  1164. tableName = strconv.Itoa(r.Table)
  1165. }
  1166. src := ""
  1167. if r.Src != nil {
  1168. src = r.Src.String()
  1169. }
  1170. dst := ""
  1171. if r.Dst != nil {
  1172. dst = r.Dst.String()
  1173. }
  1174. markStr := ""
  1175. if r.Mark > 0 {
  1176. markStr = fmt.Sprintf("0x%x (%d)", r.Mark, r.Mark)
  1177. }
  1178. id := fmt.Sprintf("rule-%d-%d", r.Priority, r.Table)
  1179. comment := ""
  1180. isDefault := false
  1181. isSystem := false
  1182. if r.Priority == 0 || r.Priority == 32766 || r.Priority == 32767 {
  1183. isDefault = true
  1184. isSystem = true
  1185. } else if userRule, ok := userRulesByPrio[r.Priority]; ok {
  1186. if userRule.ID != "" {
  1187. id = userRule.ID
  1188. }
  1189. comment = userRule.Comment
  1190. isDefault = false
  1191. isSystem = false
  1192. } else {
  1193. // System/daemon rule not added by user in debtik (e.g. WireGuard, IPsec)
  1194. isSystem = true
  1195. }
  1196. res = append(res, PolicyRuleItem{
  1197. ID: id,
  1198. Priority: r.Priority,
  1199. SrcAddress: src,
  1200. DstAddress: dst,
  1201. RoutingMark: markStr,
  1202. Table: tableName,
  1203. TableID: r.Table,
  1204. Action: "lookup",
  1205. Comment: comment,
  1206. IsDefault: isDefault,
  1207. IsSystem: isSystem,
  1208. })
  1209. }
  1210. return res
  1211. }
  1212. func (m *RoutingManager) SavePolicyRule(pr PolicyRuleItem) error {
  1213. m.mu.Lock()
  1214. defer m.mu.Unlock()
  1215. if pr.Table == "" {
  1216. pr.Table = "main"
  1217. }
  1218. if pr.ID == "" {
  1219. pr.ID = fmt.Sprintf("prule-%d", time.Now().UnixNano())
  1220. }
  1221. if pr.Priority == 0 {
  1222. pr.Priority = 1000 + len(m.policyRules)*10
  1223. }
  1224. if err := m.applyRuleToKernel(pr); err != nil {
  1225. return err
  1226. }
  1227. m.policyRules = append(m.policyRules, pr)
  1228. return m.save()
  1229. }
  1230. func (m *RoutingManager) DeletePolicyRule(id string) error {
  1231. m.mu.Lock()
  1232. defer m.mu.Unlock()
  1233. var updated []PolicyRuleItem
  1234. var target *PolicyRuleItem
  1235. for _, pr := range m.policyRules {
  1236. if pr.ID == id || fmt.Sprintf("rule-%d-%d", pr.Priority, pr.TableID) == id {
  1237. target = &pr
  1238. } else {
  1239. updated = append(updated, pr)
  1240. }
  1241. }
  1242. if target != nil {
  1243. _ = m.removeRuleFromKernel(*target)
  1244. } else if strings.HasPrefix(id, "rule-") {
  1245. parts := strings.Split(id, "-")
  1246. if len(parts) >= 2 {
  1247. if prio, err := strconv.Atoi(parts[1]); err == nil && prio > 0 {
  1248. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(prio)).Run()
  1249. }
  1250. }
  1251. }
  1252. m.policyRules = updated
  1253. return m.save()
  1254. }
  1255. func (m *RoutingManager) applyRuleToKernel(pr PolicyRuleItem) error {
  1256. args := []string{"rule", "add"}
  1257. if pr.Priority > 0 {
  1258. args = append(args, "pref", strconv.Itoa(pr.Priority))
  1259. }
  1260. if pr.SrcAddress != "" {
  1261. args = append(args, "from", pr.SrcAddress)
  1262. }
  1263. if pr.DstAddress != "" {
  1264. args = append(args, "to", pr.DstAddress)
  1265. }
  1266. if pr.RoutingMark != "" {
  1267. // Clean mark string if it has (hex)
  1268. markClean := pr.RoutingMark
  1269. if strings.Contains(markClean, "(") {
  1270. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1271. }
  1272. args = append(args, "fwmark", markClean)
  1273. }
  1274. if pr.Table != "" {
  1275. args = append(args, "lookup", pr.Table)
  1276. }
  1277. cmd := exec.Command("ip", args...)
  1278. out, err := cmd.CombinedOutput()
  1279. if err != nil {
  1280. return fmt.Errorf("failed to add rule (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1281. }
  1282. return nil
  1283. }
  1284. func (m *RoutingManager) removeRuleFromKernel(pr PolicyRuleItem) error {
  1285. if pr.Priority > 0 {
  1286. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(pr.Priority)).Run()
  1287. return nil
  1288. }
  1289. args := []string{"rule", "del"}
  1290. if pr.RoutingMark != "" {
  1291. markClean := pr.RoutingMark
  1292. if strings.Contains(markClean, "(") {
  1293. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1294. }
  1295. args = append(args, "fwmark", markClean)
  1296. }
  1297. if pr.Table != "" {
  1298. args = append(args, "lookup", pr.Table)
  1299. }
  1300. _ = exec.Command("ip", args...).Run()
  1301. return nil
  1302. }
  1303. // ==================== Routing Tables ====================
  1304. func (m *RoutingManager) ListTables() []RoutingTableItem {
  1305. m.mu.Lock()
  1306. defer m.mu.Unlock()
  1307. tables := []RoutingTableItem{
  1308. {Name: "main", TableID: 254, Comment: "Default system routing table"},
  1309. {Name: "default", TableID: 253, Comment: "Default fallback table"},
  1310. {Name: "local", TableID: 255, Comment: "Local kernel device table"},
  1311. }
  1312. tables = append(tables, m.customTables...)
  1313. return tables
  1314. }
  1315. func (m *RoutingManager) SaveTable(t RoutingTableItem) error {
  1316. m.mu.Lock()
  1317. defer m.mu.Unlock()
  1318. if t.Name == "" {
  1319. return fmt.Errorf("table name is required")
  1320. }
  1321. if t.TableID == 0 {
  1322. // Auto assign FIB ID starting at 100
  1323. t.TableID = 100 + len(m.customTables)
  1324. }
  1325. for _, existing := range m.customTables {
  1326. if existing.Name == t.Name || existing.TableID == t.TableID {
  1327. return fmt.Errorf("table with name %q or ID %d already exists", t.Name, t.TableID)
  1328. }
  1329. }
  1330. m.customTables = append(m.customTables, t)
  1331. _ = m.save()
  1332. m.syncCustomTablesToSystem()
  1333. return nil
  1334. }
  1335. func (m *RoutingManager) getTableMap() map[int]string {
  1336. tableMap := map[int]string{
  1337. 254: "main",
  1338. 253: "default",
  1339. 255: "local",
  1340. }
  1341. // Read /etc/iproute2/rt_tables
  1342. if f, err := os.Open(RTTableFilePath); err == nil {
  1343. defer f.Close()
  1344. scanner := bufio.NewScanner(f)
  1345. for scanner.Scan() {
  1346. line := strings.TrimSpace(scanner.Text())
  1347. if line == "" || strings.HasPrefix(line, "#") {
  1348. continue
  1349. }
  1350. parts := strings.Fields(line)
  1351. if len(parts) >= 2 {
  1352. if id, err := strconv.Atoi(parts[0]); err == nil {
  1353. tableMap[id] = parts[1]
  1354. }
  1355. }
  1356. }
  1357. }
  1358. for _, t := range m.customTables {
  1359. tableMap[t.TableID] = t.Name
  1360. }
  1361. return tableMap
  1362. }
  1363. func (m *RoutingManager) Stop() {
  1364. if m.stopChan != nil {
  1365. select {
  1366. case <-m.stopChan:
  1367. default:
  1368. close(m.stopChan)
  1369. }
  1370. }
  1371. }
  1372. // RenameInterface updates static routes and policy rules when an interface is renamed.
  1373. func (m *RoutingManager) RenameInterface(oldName, newName string) {
  1374. m.mu.Lock()
  1375. defer m.mu.Unlock()
  1376. changed := false
  1377. for i := range m.staticRoutes {
  1378. if m.staticRoutes[i].Interface == oldName {
  1379. m.staticRoutes[i].Interface = newName
  1380. changed = true
  1381. }
  1382. if m.staticRoutes[i].Gateway == oldName {
  1383. m.staticRoutes[i].Gateway = newName
  1384. changed = true
  1385. }
  1386. }
  1387. if changed {
  1388. _ = m.save()
  1389. }
  1390. }