manager.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. const (
  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. m.mu.Lock()
  535. defer m.mu.Unlock()
  536. before := append([]RouteItem(nil), m.staticRoutes...)
  537. dirty, applied := false, false
  538. defer func() {
  539. if err != nil && dirty {
  540. m.staticRoutes = before
  541. if applied {
  542. _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  543. }
  544. m.applyAll()
  545. _ = m.save()
  546. }
  547. }()
  548. if r.DstAddress == "" {
  549. return fmt.Errorf("destination address is required")
  550. }
  551. if r.DstAddress == "default" {
  552. r.DstAddress = "0.0.0.0/0"
  553. }
  554. if r.RoutingTable == "" {
  555. r.RoutingTable = "main"
  556. }
  557. if _, _, parseErr := net.ParseCIDR(r.DstAddress); parseErr != nil && net.ParseIP(r.DstAddress) == nil {
  558. return fmt.Errorf("invalid destination: %s", r.DstAddress)
  559. }
  560. dirty = true
  561. r.Static = true
  562. origID := r.ID
  563. foundIndex := -1
  564. // 1. Direct ID match in static routes (if not a temporary/kernel route ID)
  565. if r.ID != "" && !strings.HasPrefix(r.ID, "kr-") {
  566. for i, existing := range m.staticRoutes {
  567. if existing.ID == r.ID {
  568. foundIndex = i
  569. break
  570. }
  571. }
  572. }
  573. // 2. Match by OldDstAddress / OldGateway passed from the edit modal
  574. if foundIndex == -1 && r.OldDstAddress != "" {
  575. normOldDst := normalizeDst(r.OldDstAddress)
  576. oldTable := r.OldRoutingTable
  577. if oldTable == "" {
  578. oldTable = "main"
  579. }
  580. for i, existing := range m.staticRoutes {
  581. exTbl := existing.RoutingTable
  582. if exTbl == "" {
  583. exTbl = "main"
  584. }
  585. if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
  586. oldGwMatches := r.OldGateway == "" ||
  587. existing.Gateway == r.OldGateway ||
  588. existing.Interface == r.OldGateway ||
  589. (r.OldInterface != "" && existing.Interface == r.OldInterface)
  590. if oldGwMatches {
  591. foundIndex = i
  592. break
  593. }
  594. }
  595. }
  596. }
  597. // 3. Match by target DstAddress + Table + Gateway/Interface (prevent duplicates on re-save)
  598. if foundIndex == -1 {
  599. normNewDst := normalizeDst(r.DstAddress)
  600. for i, existing := range m.staticRoutes {
  601. exTbl := existing.RoutingTable
  602. if exTbl == "" {
  603. exTbl = "main"
  604. }
  605. if normalizeDst(existing.DstAddress) == normNewDst && exTbl == r.RoutingTable {
  606. gwMatches := (existing.Gateway != "" && existing.Gateway == r.Gateway) ||
  607. (existing.Interface != "" && existing.Interface == r.Interface) ||
  608. (existing.Gateway == "" && r.Gateway == "")
  609. if gwMatches {
  610. foundIndex = i
  611. break
  612. }
  613. }
  614. }
  615. }
  616. if r.CheckInterval <= 0 {
  617. r.CheckInterval = 5
  618. }
  619. if r.CheckThreshold <= 0 {
  620. r.CheckThreshold = 3
  621. }
  622. if r.CheckGateway == "internet" && strings.TrimSpace(r.CheckTarget) == "" {
  623. r.CheckTarget = "1.1.1.1"
  624. }
  625. if r.CheckGateway != "" && r.CheckGateway != "none" {
  626. if r.HealthStatus == "" {
  627. r.HealthStatus = "checking"
  628. }
  629. } else {
  630. r.CheckGateway = "none"
  631. r.HealthStatus = "none"
  632. }
  633. var oldRouteToClean *RouteItem
  634. if foundIndex >= 0 {
  635. oldExisting := m.staticRoutes[foundIndex]
  636. r.ID = oldExisting.ID // Preserve persistent ID!
  637. if normalizeDst(oldExisting.DstAddress) != normalizeDst(r.DstAddress) ||
  638. oldExisting.RoutingTable != r.RoutingTable ||
  639. oldExisting.Distance != r.Distance {
  640. oldCopy := oldExisting
  641. oldRouteToClean = &oldCopy
  642. }
  643. if r.HealthStatus == "checking" && oldExisting.HealthStatus != "" && oldExisting.CheckGateway == r.CheckGateway {
  644. r.HealthStatus = oldExisting.HealthStatus
  645. r.HealthRTT = oldExisting.HealthRTT
  646. r.HealthLossPct = oldExisting.HealthLossPct
  647. r.HealthLastCheck = oldExisting.HealthLastCheck
  648. }
  649. m.staticRoutes[foundIndex] = r
  650. } else {
  651. if r.ID == "" || strings.HasPrefix(r.ID, "kr-") {
  652. r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  653. }
  654. // If adopting a live kernel route not in staticRoutes, remove it from direct kernel routes
  655. if strings.HasPrefix(origID, "kr-") {
  656. for _, lr := range m.listLiveRoutesLocked() {
  657. if lr.ID == origID {
  658. _ = m.deleteDirectKernelRoute(lr)
  659. break
  660. }
  661. }
  662. }
  663. m.staticRoutes = append(m.staticRoutes, r)
  664. }
  665. if r.OldDstAddress != "" {
  666. oldDist := 0
  667. if r.OldDistance != nil {
  668. oldDist = *r.OldDistance
  669. }
  670. if normalizeDst(r.OldDstAddress) != normalizeDst(r.DstAddress) || r.OldRoutingTable != r.RoutingTable || oldDist != r.Distance {
  671. oldRouteToClean = &RouteItem{
  672. DstAddress: r.OldDstAddress,
  673. Gateway: r.OldGateway,
  674. RoutingTable: r.OldRoutingTable,
  675. Distance: oldDist,
  676. Interface: r.OldInterface,
  677. }
  678. }
  679. }
  680. for i := range m.staticRoutes {
  681. if m.staticRoutes[i].ID == r.ID {
  682. if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
  683. m.staticRoutes[i].Active = true
  684. } else {
  685. m.staticRoutes[i].Active = false
  686. }
  687. break
  688. }
  689. }
  690. if saveErr := m.save(); saveErr != nil {
  691. return saveErr
  692. }
  693. // Clean up old route group if destination, routing table or distance changed
  694. if oldRouteToClean != nil {
  695. _ = m.syncRouteGroupToKernel(oldRouteToClean.DstAddress, oldRouteToClean.RoutingTable, oldRouteToClean.Distance)
  696. }
  697. // Apply updated/new route group to kernel
  698. if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
  699. return err
  700. }
  701. applied = true
  702. return nil
  703. }
  704. func (m *RoutingManager) DeleteRoute(id string) error {
  705. m.mu.Lock()
  706. defer m.mu.Unlock()
  707. var updated []RouteItem
  708. var target *RouteItem
  709. // 1. Direct ID match in static routes
  710. for _, r := range m.staticRoutes {
  711. if r.ID == id {
  712. targetCopy := r
  713. target = &targetCopy
  714. } else {
  715. updated = append(updated, r)
  716. }
  717. }
  718. // 2. If not found by direct ID, check if it's a live kernel route ID (e.g. kr-...)
  719. if target == nil {
  720. for _, lr := range m.listLiveRoutesLocked() {
  721. if lr.ID == id {
  722. // Check if any static route corresponds to this live route
  723. matchIdx := -1
  724. normLrDst := normalizeDst(lr.DstAddress)
  725. for i, sr := range m.staticRoutes {
  726. gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
  727. if normalizeDst(sr.DstAddress) == normLrDst && sr.RoutingTable == lr.RoutingTable && gwMatches {
  728. matchIdx = i
  729. break
  730. }
  731. }
  732. if matchIdx >= 0 {
  733. targetCopy := m.staticRoutes[matchIdx]
  734. target = &targetCopy
  735. for idx, r := range m.staticRoutes {
  736. if idx != matchIdx {
  737. updated = append(updated, r)
  738. }
  739. }
  740. break
  741. } else {
  742. // Pure kernel route, not managed in static_routes.json
  743. return m.deleteDirectKernelRoute(lr)
  744. }
  745. }
  746. }
  747. }
  748. if target != nil {
  749. m.staticRoutes = updated
  750. _ = m.save()
  751. _ = m.syncRouteGroupToKernel(target.DstAddress, target.RoutingTable, target.Distance)
  752. return nil
  753. }
  754. return fmt.Errorf("route not found")
  755. }
  756. func (m *RoutingManager) SetRouteState(id string, disabled bool) error {
  757. m.mu.Lock()
  758. defer m.mu.Unlock()
  759. for i := range m.staticRoutes {
  760. if m.staticRoutes[i].ID == id {
  761. m.staticRoutes[i].Disabled = disabled
  762. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  763. m.staticRoutes[i].Active = true
  764. } else if disabled {
  765. m.staticRoutes[i].Active = false
  766. }
  767. _ = m.save()
  768. _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
  769. return nil
  770. }
  771. }
  772. // If not in staticRoutes, could be a live route ID (kr-...)
  773. for _, lr := range m.listLiveRoutesLocked() {
  774. if lr.ID == id {
  775. // Check if any static route corresponds to this live route
  776. normLrDst := normalizeDst(lr.DstAddress)
  777. for i := range m.staticRoutes {
  778. 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)
  779. if normalizeDst(m.staticRoutes[i].DstAddress) == normLrDst && m.staticRoutes[i].RoutingTable == lr.RoutingTable && gwMatches {
  780. m.staticRoutes[i].Disabled = disabled
  781. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  782. m.staticRoutes[i].Active = true
  783. } else if disabled {
  784. m.staticRoutes[i].Active = false
  785. }
  786. _ = m.save()
  787. _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
  788. return nil
  789. }
  790. }
  791. // If pure kernel static route, adopt into staticRoutes as disabled
  792. if disabled {
  793. lr.Disabled = true
  794. lr.Static = true
  795. lr.Active = false
  796. lr.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  797. m.staticRoutes = append(m.staticRoutes, lr)
  798. _ = m.save()
  799. _ = m.syncRouteGroupToKernel(lr.DstAddress, lr.RoutingTable, lr.Distance)
  800. return nil
  801. }
  802. }
  803. }
  804. return fmt.Errorf("route not found")
  805. }
  806. func normalizeDst(dst string) string {
  807. dst = strings.TrimSpace(dst)
  808. if dst == "" || dst == "default" || dst == "0.0.0.0/0" {
  809. return "default"
  810. }
  811. if !strings.Contains(dst, "/") && net.ParseIP(dst) != nil {
  812. return dst + "/32"
  813. }
  814. return dst
  815. }
  816. func (m *RoutingManager) syncRouteGroupToKernel(dstAddress, routingTable string, distance int) error {
  817. normDst := normalizeDst(dstAddress)
  818. tbl := strings.TrimSpace(routingTable)
  819. if tbl == "" {
  820. tbl = "main"
  821. }
  822. var activeRoutes []RouteItem
  823. for _, r := range m.staticRoutes {
  824. rDst := normalizeDst(r.DstAddress)
  825. rTbl := strings.TrimSpace(r.RoutingTable)
  826. if rTbl == "" {
  827. rTbl = "main"
  828. }
  829. if rDst == normDst && rTbl == tbl && r.Distance == distance {
  830. if !r.Disabled && r.Active && r.HealthStatus != "offline" {
  831. activeRoutes = append(activeRoutes, r)
  832. }
  833. }
  834. }
  835. if len(activeRoutes) == 0 {
  836. // Safety guard: if all default routes are marked offline, do NOT delete the default route into a blackout!
  837. // Fallback to keeping all enabled static routes in the group active so recovery traffic and emergency pings can flow.
  838. if normDst == "default" {
  839. var fallbackRoutes []RouteItem
  840. for _, r := range m.staticRoutes {
  841. rDst := normalizeDst(r.DstAddress)
  842. rTbl := strings.TrimSpace(r.RoutingTable)
  843. if rTbl == "" {
  844. rTbl = "main"
  845. }
  846. if rDst == normDst && rTbl == tbl && r.Distance == distance && !r.Disabled {
  847. fallbackRoutes = append(fallbackRoutes, r)
  848. }
  849. }
  850. if len(fallbackRoutes) > 0 {
  851. log.Printf("[RouteManager] All default routes offline in group! Keeping fallback routes active to prevent blackout")
  852. activeRoutes = fallbackRoutes
  853. }
  854. }
  855. }
  856. if len(activeRoutes) == 0 {
  857. args := []string{"route", "del", normDst}
  858. if distance > 0 {
  859. args = append(args, "metric", strconv.Itoa(distance))
  860. }
  861. if tbl != "main" {
  862. args = append(args, "table", tbl)
  863. }
  864. args = append(args, "proto", "static")
  865. _ = exec.Command("ip", args...).Run()
  866. // Also delete without proto static in case route protocol differed
  867. fbArgs := []string{"route", "del", normDst}
  868. if distance > 0 {
  869. fbArgs = append(fbArgs, "metric", strconv.Itoa(distance))
  870. }
  871. if tbl != "main" {
  872. fbArgs = append(fbArgs, "table", tbl)
  873. }
  874. _ = exec.Command("ip", fbArgs...).Run()
  875. // Bare fallback
  876. _ = exec.Command("ip", "route", "del", normDst).Run()
  877. // Also delete blackhole route variant if it existed
  878. bhArgs := []string{"route", "del", "blackhole", normDst}
  879. if distance > 0 {
  880. bhArgs = append(bhArgs, "metric", strconv.Itoa(distance))
  881. }
  882. if tbl != "main" {
  883. bhArgs = append(bhArgs, "table", tbl)
  884. }
  885. _ = exec.Command("ip", bhArgs...).Run()
  886. return nil
  887. }
  888. if len(activeRoutes) == 1 {
  889. r := activeRoutes[0]
  890. gw := strings.TrimSpace(r.Gateway)
  891. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  892. var args []string
  893. if isBlackhole {
  894. args = []string{"route", "replace", "blackhole", normDst}
  895. } else {
  896. args = []string{"route", "replace", normDst}
  897. if gw != "" {
  898. if net.ParseIP(gw) != nil {
  899. args = append(args, "via", gw)
  900. } else {
  901. args = append(args, "dev", gw)
  902. }
  903. }
  904. iface := strings.TrimSpace(r.Interface)
  905. if iface != "" && gw != iface && (gw == "" || net.ParseIP(gw) != nil) {
  906. args = append(args, "dev", iface)
  907. }
  908. if gw != "" && iface != "" && net.ParseIP(gw) != nil {
  909. args = append(args, "onlink")
  910. }
  911. }
  912. if distance > 0 {
  913. args = append(args, "metric", strconv.Itoa(distance))
  914. }
  915. if tbl != "main" {
  916. args = append(args, "table", tbl)
  917. }
  918. args = append(args, "proto", "static")
  919. cmd := exec.Command("ip", args...)
  920. if out, err := cmd.CombinedOutput(); err != nil {
  921. return fmt.Errorf("failed to apply route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  922. }
  923. return nil
  924. }
  925. // Multiple routes: ECMP multipath route
  926. args := []string{"route", "replace", normDst, "scope", "global"}
  927. if distance > 0 {
  928. args = append(args, "metric", strconv.Itoa(distance))
  929. }
  930. if tbl != "main" {
  931. args = append(args, "table", tbl)
  932. }
  933. args = append(args, "proto", "static")
  934. for _, r := range activeRoutes {
  935. args = append(args, "nexthop")
  936. gw := strings.TrimSpace(r.Gateway)
  937. if gw != "" && net.ParseIP(gw) != nil {
  938. args = append(args, "via", gw)
  939. }
  940. iface := strings.TrimSpace(r.Interface)
  941. if iface == "" && gw != "" && net.ParseIP(gw) == nil {
  942. iface = gw
  943. }
  944. if iface != "" {
  945. args = append(args, "dev", iface)
  946. }
  947. if gw != "" && iface != "" && net.ParseIP(gw) != nil {
  948. args = append(args, "onlink")
  949. }
  950. args = append(args, "weight", "1")
  951. }
  952. cmd := exec.Command("ip", args...)
  953. if out, err := cmd.CombinedOutput(); err != nil {
  954. return fmt.Errorf("failed to apply multipath route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  955. }
  956. return nil
  957. }
  958. func (m *RoutingManager) applyRouteToKernel(r RouteItem) error {
  959. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  960. }
  961. func (m *RoutingManager) removeRouteFromKernel(r RouteItem) error {
  962. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  963. }
  964. func (m *RoutingManager) deleteDirectKernelRoute(r RouteItem) error {
  965. normDst := normalizeDst(r.DstAddress)
  966. args := []string{"route", "del", normDst}
  967. gw := strings.TrimSpace(r.Gateway)
  968. if gw != "" && net.ParseIP(gw) != nil {
  969. args = append(args, "via", gw)
  970. }
  971. iface := strings.TrimSpace(r.Interface)
  972. if iface != "" {
  973. args = append(args, "dev", iface)
  974. }
  975. if r.RoutingTable != "" && r.RoutingTable != "main" {
  976. args = append(args, "table", r.RoutingTable)
  977. }
  978. if r.Distance > 0 {
  979. args = append(args, "metric", strconv.Itoa(r.Distance))
  980. }
  981. cmd := exec.Command("ip", args...)
  982. if out, err := cmd.CombinedOutput(); err == nil {
  983. return nil
  984. } else {
  985. log.Printf("[RouteManager] direct ip route del (%s): %s (%v), attempting fallback", strings.Join(args, " "), string(out), err)
  986. }
  987. fbArgs := []string{"route", "del", normDst}
  988. if r.RoutingTable != "" && r.RoutingTable != "main" {
  989. fbArgs = append(fbArgs, "table", r.RoutingTable)
  990. }
  991. if r.Distance > 0 {
  992. fbArgs = append(fbArgs, "metric", strconv.Itoa(r.Distance))
  993. }
  994. if err := exec.Command("ip", fbArgs...).Run(); err == nil {
  995. return nil
  996. }
  997. return exec.Command("ip", "route", "del", normDst).Run()
  998. }
  999. // ==================== Policy Rules (/ip route rule) ====================
  1000. func (m *RoutingManager) ListPolicyRules() []PolicyRuleItem {
  1001. m.mu.Lock()
  1002. defer m.mu.Unlock()
  1003. // Query live rules from kernel
  1004. rules, err := netlink.RuleList(netlink.FAMILY_V4)
  1005. if err != nil {
  1006. return m.policyRules
  1007. }
  1008. tableNames := m.getTableMap()
  1009. var res []PolicyRuleItem
  1010. userRulesByPrio := make(map[int]PolicyRuleItem)
  1011. for _, pr := range m.policyRules {
  1012. userRulesByPrio[pr.Priority] = pr
  1013. }
  1014. for _, r := range rules {
  1015. tableName := "main"
  1016. if name, ok := tableNames[r.Table]; ok {
  1017. tableName = name
  1018. } else if r.Table != 254 && r.Table != 0 {
  1019. tableName = strconv.Itoa(r.Table)
  1020. }
  1021. src := ""
  1022. if r.Src != nil {
  1023. src = r.Src.String()
  1024. }
  1025. dst := ""
  1026. if r.Dst != nil {
  1027. dst = r.Dst.String()
  1028. }
  1029. markStr := ""
  1030. if r.Mark > 0 {
  1031. markStr = fmt.Sprintf("0x%x (%d)", r.Mark, r.Mark)
  1032. }
  1033. id := fmt.Sprintf("rule-%d-%d", r.Priority, r.Table)
  1034. comment := ""
  1035. isDefault := false
  1036. isSystem := false
  1037. if r.Priority == 0 || r.Priority == 32766 || r.Priority == 32767 {
  1038. isDefault = true
  1039. isSystem = true
  1040. } else if userRule, ok := userRulesByPrio[r.Priority]; ok {
  1041. if userRule.ID != "" {
  1042. id = userRule.ID
  1043. }
  1044. comment = userRule.Comment
  1045. isDefault = false
  1046. isSystem = false
  1047. } else {
  1048. // System/daemon rule not added by user in debtik (e.g. WireGuard, IPsec)
  1049. isSystem = true
  1050. }
  1051. res = append(res, PolicyRuleItem{
  1052. ID: id,
  1053. Priority: r.Priority,
  1054. SrcAddress: src,
  1055. DstAddress: dst,
  1056. RoutingMark: markStr,
  1057. Table: tableName,
  1058. TableID: r.Table,
  1059. Action: "lookup",
  1060. Comment: comment,
  1061. IsDefault: isDefault,
  1062. IsSystem: isSystem,
  1063. })
  1064. }
  1065. return res
  1066. }
  1067. func (m *RoutingManager) SavePolicyRule(pr PolicyRuleItem) error {
  1068. m.mu.Lock()
  1069. defer m.mu.Unlock()
  1070. if pr.Table == "" {
  1071. pr.Table = "main"
  1072. }
  1073. if pr.ID == "" {
  1074. pr.ID = fmt.Sprintf("prule-%d", time.Now().UnixNano())
  1075. }
  1076. if pr.Priority == 0 {
  1077. pr.Priority = 1000 + len(m.policyRules)*10
  1078. }
  1079. if err := m.applyRuleToKernel(pr); err != nil {
  1080. return err
  1081. }
  1082. m.policyRules = append(m.policyRules, pr)
  1083. return m.save()
  1084. }
  1085. func (m *RoutingManager) DeletePolicyRule(id string) error {
  1086. m.mu.Lock()
  1087. defer m.mu.Unlock()
  1088. var updated []PolicyRuleItem
  1089. var target *PolicyRuleItem
  1090. for _, pr := range m.policyRules {
  1091. if pr.ID == id || fmt.Sprintf("rule-%d-%d", pr.Priority, pr.TableID) == id {
  1092. target = &pr
  1093. } else {
  1094. updated = append(updated, pr)
  1095. }
  1096. }
  1097. if target != nil {
  1098. _ = m.removeRuleFromKernel(*target)
  1099. } else if strings.HasPrefix(id, "rule-") {
  1100. parts := strings.Split(id, "-")
  1101. if len(parts) >= 2 {
  1102. if prio, err := strconv.Atoi(parts[1]); err == nil && prio > 0 {
  1103. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(prio)).Run()
  1104. }
  1105. }
  1106. }
  1107. m.policyRules = updated
  1108. return m.save()
  1109. }
  1110. func (m *RoutingManager) applyRuleToKernel(pr PolicyRuleItem) error {
  1111. args := []string{"rule", "add"}
  1112. if pr.Priority > 0 {
  1113. args = append(args, "pref", strconv.Itoa(pr.Priority))
  1114. }
  1115. if pr.SrcAddress != "" {
  1116. args = append(args, "from", pr.SrcAddress)
  1117. }
  1118. if pr.DstAddress != "" {
  1119. args = append(args, "to", pr.DstAddress)
  1120. }
  1121. if pr.RoutingMark != "" {
  1122. // Clean mark string if it has (hex)
  1123. markClean := pr.RoutingMark
  1124. if strings.Contains(markClean, "(") {
  1125. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1126. }
  1127. args = append(args, "fwmark", markClean)
  1128. }
  1129. if pr.Table != "" {
  1130. args = append(args, "lookup", pr.Table)
  1131. }
  1132. cmd := exec.Command("ip", args...)
  1133. out, err := cmd.CombinedOutput()
  1134. if err != nil {
  1135. return fmt.Errorf("failed to add rule (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1136. }
  1137. return nil
  1138. }
  1139. func (m *RoutingManager) removeRuleFromKernel(pr PolicyRuleItem) error {
  1140. if pr.Priority > 0 {
  1141. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(pr.Priority)).Run()
  1142. return nil
  1143. }
  1144. args := []string{"rule", "del"}
  1145. if pr.RoutingMark != "" {
  1146. markClean := pr.RoutingMark
  1147. if strings.Contains(markClean, "(") {
  1148. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1149. }
  1150. args = append(args, "fwmark", markClean)
  1151. }
  1152. if pr.Table != "" {
  1153. args = append(args, "lookup", pr.Table)
  1154. }
  1155. _ = exec.Command("ip", args...).Run()
  1156. return nil
  1157. }
  1158. // ==================== Routing Tables ====================
  1159. func (m *RoutingManager) ListTables() []RoutingTableItem {
  1160. m.mu.Lock()
  1161. defer m.mu.Unlock()
  1162. tables := []RoutingTableItem{
  1163. {Name: "main", TableID: 254, Comment: "Default system routing table"},
  1164. {Name: "default", TableID: 253, Comment: "Default fallback table"},
  1165. {Name: "local", TableID: 255, Comment: "Local kernel device table"},
  1166. }
  1167. tables = append(tables, m.customTables...)
  1168. return tables
  1169. }
  1170. func (m *RoutingManager) SaveTable(t RoutingTableItem) error {
  1171. m.mu.Lock()
  1172. defer m.mu.Unlock()
  1173. if t.Name == "" {
  1174. return fmt.Errorf("table name is required")
  1175. }
  1176. if t.TableID == 0 {
  1177. // Auto assign FIB ID starting at 100
  1178. t.TableID = 100 + len(m.customTables)
  1179. }
  1180. for _, existing := range m.customTables {
  1181. if existing.Name == t.Name || existing.TableID == t.TableID {
  1182. return fmt.Errorf("table with name %q or ID %d already exists", t.Name, t.TableID)
  1183. }
  1184. }
  1185. m.customTables = append(m.customTables, t)
  1186. _ = m.save()
  1187. m.syncCustomTablesToSystem()
  1188. return nil
  1189. }
  1190. func (m *RoutingManager) getTableMap() map[int]string {
  1191. tableMap := map[int]string{
  1192. 254: "main",
  1193. 253: "default",
  1194. 255: "local",
  1195. }
  1196. // Read /etc/iproute2/rt_tables
  1197. if f, err := os.Open(RTTableFilePath); err == nil {
  1198. defer f.Close()
  1199. scanner := bufio.NewScanner(f)
  1200. for scanner.Scan() {
  1201. line := strings.TrimSpace(scanner.Text())
  1202. if line == "" || strings.HasPrefix(line, "#") {
  1203. continue
  1204. }
  1205. parts := strings.Fields(line)
  1206. if len(parts) >= 2 {
  1207. if id, err := strconv.Atoi(parts[0]); err == nil {
  1208. tableMap[id] = parts[1]
  1209. }
  1210. }
  1211. }
  1212. }
  1213. for _, t := range m.customTables {
  1214. tableMap[t.TableID] = t.Name
  1215. }
  1216. return tableMap
  1217. }
  1218. func (m *RoutingManager) Stop() {
  1219. if m.stopChan != nil {
  1220. select {
  1221. case <-m.stopChan:
  1222. default:
  1223. close(m.stopChan)
  1224. }
  1225. }
  1226. }
  1227. // RenameInterface updates static routes and policy rules when an interface is renamed.
  1228. func (m *RoutingManager) RenameInterface(oldName, newName string) {
  1229. m.mu.Lock()
  1230. defer m.mu.Unlock()
  1231. changed := false
  1232. for i := range m.staticRoutes {
  1233. if m.staticRoutes[i].Interface == oldName {
  1234. m.staticRoutes[i].Interface = newName
  1235. changed = true
  1236. }
  1237. if m.staticRoutes[i].Gateway == oldName {
  1238. m.staticRoutes[i].Gateway = newName
  1239. changed = true
  1240. }
  1241. }
  1242. if changed {
  1243. _ = m.save()
  1244. }
  1245. }