manager.go 44 KB

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