manager.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  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 normalizeDst(dst string) string {
  848. dst = strings.TrimSpace(dst)
  849. if dst == "" || dst == "default" || dst == "0.0.0.0/0" {
  850. return "default"
  851. }
  852. if !strings.Contains(dst, "/") && net.ParseIP(dst) != nil {
  853. return dst + "/32"
  854. }
  855. return dst
  856. }
  857. func detectGatewayForInterface(ifaceName string) string {
  858. link, err := netlink.LinkByName(ifaceName)
  859. if err == nil {
  860. routes, err := netlink.RouteList(link, netlink.FAMILY_V4)
  861. if err == nil {
  862. for _, r := range routes {
  863. if (r.Dst == nil || r.Dst.IP.IsUnspecified()) && r.Gw != nil && !r.Gw.IsUnspecified() {
  864. return r.Gw.String()
  865. }
  866. }
  867. for _, r := range routes {
  868. if r.Gw != nil && !r.Gw.IsUnspecified() {
  869. return r.Gw.String()
  870. }
  871. }
  872. }
  873. }
  874. out, err := exec.Command("ip", "route", "show", "dev", ifaceName).CombinedOutput()
  875. if err == nil {
  876. lines := strings.Split(string(out), "\n")
  877. for _, l := range lines {
  878. if strings.Contains(l, "via ") {
  879. fields := strings.Fields(l)
  880. for i, f := range fields {
  881. if f == "via" && i+1 < len(fields) {
  882. gw := fields[i+1]
  883. if net.ParseIP(gw) != nil {
  884. return gw
  885. }
  886. }
  887. }
  888. }
  889. }
  890. }
  891. return ""
  892. }
  893. func (m *RoutingManager) syncRouteGroupToKernel(dstAddress, routingTable string, distance int) error {
  894. normDst := normalizeDst(dstAddress)
  895. tbl := strings.TrimSpace(routingTable)
  896. if tbl == "" {
  897. tbl = "main"
  898. }
  899. var activeRoutes []RouteItem
  900. for _, r := range m.staticRoutes {
  901. rDst := normalizeDst(r.DstAddress)
  902. rTbl := strings.TrimSpace(r.RoutingTable)
  903. if rTbl == "" {
  904. rTbl = "main"
  905. }
  906. if rDst == normDst && rTbl == tbl && r.Distance == distance {
  907. if !r.Disabled && r.Active && r.HealthStatus != "offline" {
  908. activeRoutes = append(activeRoutes, r)
  909. }
  910. }
  911. }
  912. if len(activeRoutes) == 0 {
  913. // Safety guard: if all default routes are marked offline, do NOT delete the default route into a blackout!
  914. // Fallback to keeping all enabled static routes in the group active so recovery traffic and emergency pings can flow.
  915. if normDst == "default" {
  916. var fallbackRoutes []RouteItem
  917. for _, r := range m.staticRoutes {
  918. rDst := normalizeDst(r.DstAddress)
  919. rTbl := strings.TrimSpace(r.RoutingTable)
  920. if rTbl == "" {
  921. rTbl = "main"
  922. }
  923. if rDst == normDst && rTbl == tbl && r.Distance == distance && !r.Disabled {
  924. fallbackRoutes = append(fallbackRoutes, r)
  925. }
  926. }
  927. if len(fallbackRoutes) > 0 {
  928. log.Printf("[RouteManager] All default routes offline in group! Keeping fallback routes active to prevent blackout")
  929. activeRoutes = fallbackRoutes
  930. }
  931. }
  932. }
  933. if len(activeRoutes) == 0 {
  934. args := []string{"route", "del", normDst}
  935. if distance > 0 {
  936. args = append(args, "metric", strconv.Itoa(distance))
  937. }
  938. if tbl != "main" {
  939. args = append(args, "table", tbl)
  940. }
  941. args = append(args, "proto", "static")
  942. _ = exec.Command("ip", args...).Run()
  943. // Also delete without proto static in case route protocol differed
  944. fbArgs := []string{"route", "del", normDst}
  945. if distance > 0 {
  946. fbArgs = append(fbArgs, "metric", strconv.Itoa(distance))
  947. }
  948. if tbl != "main" {
  949. fbArgs = append(fbArgs, "table", tbl)
  950. }
  951. _ = exec.Command("ip", fbArgs...).Run()
  952. // Bare fallback
  953. _ = exec.Command("ip", "route", "del", normDst).Run()
  954. // Also delete blackhole route variant if it existed
  955. bhArgs := []string{"route", "del", "blackhole", normDst}
  956. if distance > 0 {
  957. bhArgs = append(bhArgs, "metric", strconv.Itoa(distance))
  958. }
  959. if tbl != "main" {
  960. bhArgs = append(bhArgs, "table", tbl)
  961. }
  962. _ = exec.Command("ip", bhArgs...).Run()
  963. return nil
  964. }
  965. if len(activeRoutes) == 1 {
  966. r := activeRoutes[0]
  967. gw := strings.TrimSpace(r.Gateway)
  968. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  969. var args []string
  970. if isBlackhole {
  971. args = []string{"route", "replace", "blackhole", normDst}
  972. } else {
  973. args = []string{"route", "replace", normDst}
  974. iface := strings.TrimSpace(r.Interface)
  975. if gw != "" {
  976. if net.ParseIP(gw) != nil {
  977. args = append(args, "via", gw)
  978. } else {
  979. // Gateway field contains an interface name
  980. targetDev := gw
  981. if iface == "" {
  982. iface = targetDev
  983. }
  984. if detectedGw := detectGatewayForInterface(targetDev); detectedGw != "" {
  985. args = append(args, "via", detectedGw)
  986. } else {
  987. args = append(args, "dev", targetDev)
  988. }
  989. }
  990. }
  991. if iface != "" && (gw == "" || net.ParseIP(gw) != nil || (gw != "" && detectGatewayForInterface(gw) != "")) {
  992. args = append(args, "dev", iface)
  993. }
  994. if iface != "" && (gw != "" || detectGatewayForInterface(iface) != "") {
  995. args = append(args, "onlink")
  996. }
  997. }
  998. if distance > 0 {
  999. args = append(args, "metric", strconv.Itoa(distance))
  1000. }
  1001. if tbl != "main" {
  1002. args = append(args, "table", tbl)
  1003. }
  1004. args = append(args, "proto", "static")
  1005. cmd := exec.Command("ip", args...)
  1006. if out, err := cmd.CombinedOutput(); err != nil {
  1007. return fmt.Errorf("failed to apply route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1008. }
  1009. return nil
  1010. }
  1011. // Multiple routes: ECMP multipath route
  1012. args := []string{"route", "replace", normDst, "scope", "global"}
  1013. if distance > 0 {
  1014. args = append(args, "metric", strconv.Itoa(distance))
  1015. }
  1016. if tbl != "main" {
  1017. args = append(args, "table", tbl)
  1018. }
  1019. args = append(args, "proto", "static")
  1020. for _, r := range activeRoutes {
  1021. args = append(args, "nexthop")
  1022. gw := strings.TrimSpace(r.Gateway)
  1023. iface := strings.TrimSpace(r.Interface)
  1024. if iface == "" && gw != "" && net.ParseIP(gw) == nil {
  1025. iface = gw
  1026. }
  1027. if gw != "" && net.ParseIP(gw) != nil {
  1028. args = append(args, "via", gw)
  1029. } else if iface != "" {
  1030. if detectedGw := detectGatewayForInterface(iface); detectedGw != "" {
  1031. args = append(args, "via", detectedGw)
  1032. }
  1033. }
  1034. if iface != "" {
  1035. args = append(args, "dev", iface, "onlink")
  1036. }
  1037. args = append(args, "weight", "1")
  1038. }
  1039. cmd := exec.Command("ip", args...)
  1040. if out, err := cmd.CombinedOutput(); err != nil {
  1041. return fmt.Errorf("failed to apply multipath route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1042. }
  1043. return nil
  1044. }
  1045. func (m *RoutingManager) applyRouteToKernel(r RouteItem) error {
  1046. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1047. }
  1048. func (m *RoutingManager) removeRouteFromKernel(r RouteItem) error {
  1049. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1050. }
  1051. func (m *RoutingManager) deleteDirectKernelRoute(r RouteItem) error {
  1052. normDst := normalizeDst(r.DstAddress)
  1053. gw := strings.TrimSpace(r.Gateway)
  1054. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  1055. var args []string
  1056. if isBlackhole {
  1057. args = []string{"route", "del", "blackhole", normDst}
  1058. } else {
  1059. args = []string{"route", "del", normDst}
  1060. if gw != "" && net.ParseIP(gw) != nil {
  1061. args = append(args, "via", gw)
  1062. }
  1063. iface := strings.TrimSpace(r.Interface)
  1064. if iface != "" {
  1065. args = append(args, "dev", iface)
  1066. }
  1067. }
  1068. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1069. args = append(args, "table", r.RoutingTable)
  1070. }
  1071. if r.Distance > 0 {
  1072. args = append(args, "metric", strconv.Itoa(r.Distance))
  1073. }
  1074. cmd := exec.Command("ip", args...)
  1075. if out, err := cmd.CombinedOutput(); err == nil {
  1076. return nil
  1077. } else {
  1078. log.Printf("[RouteManager] direct ip route del (%s): %s (%v), attempting fallback", strings.Join(args, " "), string(out), err)
  1079. }
  1080. if isBlackhole {
  1081. fbBhArgs := []string{"route", "del", "blackhole", normDst}
  1082. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1083. fbBhArgs = append(fbBhArgs, "table", r.RoutingTable)
  1084. }
  1085. if r.Distance > 0 {
  1086. fbBhArgs = append(fbBhArgs, "metric", strconv.Itoa(r.Distance))
  1087. }
  1088. if err := exec.Command("ip", fbBhArgs...).Run(); err == nil {
  1089. return nil
  1090. }
  1091. return exec.Command("ip", "route", "del", "blackhole", normDst).Run()
  1092. }
  1093. fbArgs := []string{"route", "del", normDst}
  1094. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1095. fbArgs = append(fbArgs, "table", r.RoutingTable)
  1096. }
  1097. if r.Distance > 0 {
  1098. fbArgs = append(fbArgs, "metric", strconv.Itoa(r.Distance))
  1099. }
  1100. if err := exec.Command("ip", fbArgs...).Run(); err == nil {
  1101. return nil
  1102. }
  1103. return exec.Command("ip", "route", "del", normDst).Run()
  1104. }
  1105. // ==================== Policy Rules (/ip route rule) ====================
  1106. func (m *RoutingManager) ListPolicyRules() []PolicyRuleItem {
  1107. m.mu.Lock()
  1108. defer m.mu.Unlock()
  1109. // Query live rules from kernel
  1110. rules, err := netlink.RuleList(netlink.FAMILY_V4)
  1111. if err != nil {
  1112. return m.policyRules
  1113. }
  1114. tableNames := m.getTableMap()
  1115. var res []PolicyRuleItem
  1116. userRulesByPrio := make(map[int]PolicyRuleItem)
  1117. for _, pr := range m.policyRules {
  1118. userRulesByPrio[pr.Priority] = pr
  1119. }
  1120. for _, r := range rules {
  1121. tableName := "main"
  1122. if name, ok := tableNames[r.Table]; ok {
  1123. tableName = name
  1124. } else if r.Table != 254 && r.Table != 0 {
  1125. tableName = strconv.Itoa(r.Table)
  1126. }
  1127. src := ""
  1128. if r.Src != nil {
  1129. src = r.Src.String()
  1130. }
  1131. dst := ""
  1132. if r.Dst != nil {
  1133. dst = r.Dst.String()
  1134. }
  1135. markStr := ""
  1136. if r.Mark > 0 {
  1137. markStr = fmt.Sprintf("0x%x (%d)", r.Mark, r.Mark)
  1138. }
  1139. id := fmt.Sprintf("rule-%d-%d", r.Priority, r.Table)
  1140. comment := ""
  1141. isDefault := false
  1142. isSystem := false
  1143. if r.Priority == 0 || r.Priority == 32766 || r.Priority == 32767 {
  1144. isDefault = true
  1145. isSystem = true
  1146. } else if userRule, ok := userRulesByPrio[r.Priority]; ok {
  1147. if userRule.ID != "" {
  1148. id = userRule.ID
  1149. }
  1150. comment = userRule.Comment
  1151. isDefault = false
  1152. isSystem = false
  1153. } else {
  1154. // System/daemon rule not added by user in debtik (e.g. WireGuard, IPsec)
  1155. isSystem = true
  1156. }
  1157. res = append(res, PolicyRuleItem{
  1158. ID: id,
  1159. Priority: r.Priority,
  1160. SrcAddress: src,
  1161. DstAddress: dst,
  1162. RoutingMark: markStr,
  1163. Table: tableName,
  1164. TableID: r.Table,
  1165. Action: "lookup",
  1166. Comment: comment,
  1167. IsDefault: isDefault,
  1168. IsSystem: isSystem,
  1169. })
  1170. }
  1171. return res
  1172. }
  1173. func (m *RoutingManager) SavePolicyRule(pr PolicyRuleItem) error {
  1174. m.mu.Lock()
  1175. defer m.mu.Unlock()
  1176. if pr.Table == "" {
  1177. pr.Table = "main"
  1178. }
  1179. if pr.ID == "" {
  1180. pr.ID = fmt.Sprintf("prule-%d", time.Now().UnixNano())
  1181. }
  1182. if pr.Priority == 0 {
  1183. pr.Priority = 1000 + len(m.policyRules)*10
  1184. }
  1185. if err := m.applyRuleToKernel(pr); err != nil {
  1186. return err
  1187. }
  1188. m.policyRules = append(m.policyRules, pr)
  1189. return m.save()
  1190. }
  1191. func (m *RoutingManager) DeletePolicyRule(id string) error {
  1192. m.mu.Lock()
  1193. defer m.mu.Unlock()
  1194. var updated []PolicyRuleItem
  1195. var target *PolicyRuleItem
  1196. for _, pr := range m.policyRules {
  1197. if pr.ID == id || fmt.Sprintf("rule-%d-%d", pr.Priority, pr.TableID) == id {
  1198. target = &pr
  1199. } else {
  1200. updated = append(updated, pr)
  1201. }
  1202. }
  1203. if target != nil {
  1204. _ = m.removeRuleFromKernel(*target)
  1205. } else if strings.HasPrefix(id, "rule-") {
  1206. parts := strings.Split(id, "-")
  1207. if len(parts) >= 2 {
  1208. if prio, err := strconv.Atoi(parts[1]); err == nil && prio > 0 {
  1209. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(prio)).Run()
  1210. }
  1211. }
  1212. }
  1213. m.policyRules = updated
  1214. return m.save()
  1215. }
  1216. func (m *RoutingManager) applyRuleToKernel(pr PolicyRuleItem) error {
  1217. args := []string{"rule", "add"}
  1218. if pr.Priority > 0 {
  1219. args = append(args, "pref", strconv.Itoa(pr.Priority))
  1220. }
  1221. if pr.SrcAddress != "" {
  1222. args = append(args, "from", pr.SrcAddress)
  1223. }
  1224. if pr.DstAddress != "" {
  1225. args = append(args, "to", pr.DstAddress)
  1226. }
  1227. if pr.RoutingMark != "" {
  1228. // Clean mark string if it has (hex)
  1229. markClean := pr.RoutingMark
  1230. if strings.Contains(markClean, "(") {
  1231. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1232. }
  1233. args = append(args, "fwmark", markClean)
  1234. }
  1235. if pr.Table != "" {
  1236. args = append(args, "lookup", pr.Table)
  1237. }
  1238. cmd := exec.Command("ip", args...)
  1239. out, err := cmd.CombinedOutput()
  1240. if err != nil {
  1241. return fmt.Errorf("failed to add rule (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1242. }
  1243. return nil
  1244. }
  1245. func (m *RoutingManager) removeRuleFromKernel(pr PolicyRuleItem) error {
  1246. if pr.Priority > 0 {
  1247. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(pr.Priority)).Run()
  1248. return nil
  1249. }
  1250. args := []string{"rule", "del"}
  1251. if pr.RoutingMark != "" {
  1252. markClean := pr.RoutingMark
  1253. if strings.Contains(markClean, "(") {
  1254. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1255. }
  1256. args = append(args, "fwmark", markClean)
  1257. }
  1258. if pr.Table != "" {
  1259. args = append(args, "lookup", pr.Table)
  1260. }
  1261. _ = exec.Command("ip", args...).Run()
  1262. return nil
  1263. }
  1264. // ==================== Routing Tables ====================
  1265. func (m *RoutingManager) ListTables() []RoutingTableItem {
  1266. m.mu.Lock()
  1267. defer m.mu.Unlock()
  1268. tables := []RoutingTableItem{
  1269. {Name: "main", TableID: 254, Comment: "Default system routing table"},
  1270. {Name: "default", TableID: 253, Comment: "Default fallback table"},
  1271. {Name: "local", TableID: 255, Comment: "Local kernel device table"},
  1272. }
  1273. tables = append(tables, m.customTables...)
  1274. return tables
  1275. }
  1276. func (m *RoutingManager) SaveTable(t RoutingTableItem) error {
  1277. m.mu.Lock()
  1278. defer m.mu.Unlock()
  1279. if t.Name == "" {
  1280. return fmt.Errorf("table name is required")
  1281. }
  1282. if t.TableID == 0 {
  1283. // Auto assign FIB ID starting at 100
  1284. t.TableID = 100 + len(m.customTables)
  1285. }
  1286. for _, existing := range m.customTables {
  1287. if existing.Name == t.Name || existing.TableID == t.TableID {
  1288. return fmt.Errorf("table with name %q or ID %d already exists", t.Name, t.TableID)
  1289. }
  1290. }
  1291. m.customTables = append(m.customTables, t)
  1292. _ = m.save()
  1293. m.syncCustomTablesToSystem()
  1294. return nil
  1295. }
  1296. func (m *RoutingManager) getTableMap() map[int]string {
  1297. tableMap := map[int]string{
  1298. 254: "main",
  1299. 253: "default",
  1300. 255: "local",
  1301. }
  1302. // Read /etc/iproute2/rt_tables
  1303. if f, err := os.Open(RTTableFilePath); err == nil {
  1304. defer f.Close()
  1305. scanner := bufio.NewScanner(f)
  1306. for scanner.Scan() {
  1307. line := strings.TrimSpace(scanner.Text())
  1308. if line == "" || strings.HasPrefix(line, "#") {
  1309. continue
  1310. }
  1311. parts := strings.Fields(line)
  1312. if len(parts) >= 2 {
  1313. if id, err := strconv.Atoi(parts[0]); err == nil {
  1314. tableMap[id] = parts[1]
  1315. }
  1316. }
  1317. }
  1318. }
  1319. for _, t := range m.customTables {
  1320. tableMap[t.TableID] = t.Name
  1321. }
  1322. return tableMap
  1323. }
  1324. func (m *RoutingManager) Stop() {
  1325. if m.stopChan != nil {
  1326. select {
  1327. case <-m.stopChan:
  1328. default:
  1329. close(m.stopChan)
  1330. }
  1331. }
  1332. }
  1333. // RenameInterface updates static routes and policy rules when an interface is renamed.
  1334. func (m *RoutingManager) RenameInterface(oldName, newName string) {
  1335. m.mu.Lock()
  1336. defer m.mu.Unlock()
  1337. changed := false
  1338. for i := range m.staticRoutes {
  1339. if m.staticRoutes[i].Interface == oldName {
  1340. m.staticRoutes[i].Interface = newName
  1341. changed = true
  1342. }
  1343. if m.staticRoutes[i].Gateway == oldName {
  1344. m.staticRoutes[i].Gateway = newName
  1345. changed = true
  1346. }
  1347. }
  1348. if changed {
  1349. _ = m.save()
  1350. }
  1351. }