manager.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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", r.Table, cleanDst, cleanGw)
  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", r.Table, cleanDst, cleanGw)
  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. for _, sr := range m.staticRoutes {
  461. normSrDst := normalizeDst(sr.DstAddress)
  462. found := false
  463. for i, lr := range liveRoutes {
  464. if matchedLive[i] {
  465. continue
  466. }
  467. if normalizeDst(lr.DstAddress) != normSrDst {
  468. continue
  469. }
  470. if lr.RoutingTable != sr.RoutingTable {
  471. continue
  472. }
  473. gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
  474. if !gwMatches && (sdwan.IsSDWANGroup(sr.Interface) || sdwan.IsSDWANGroup(sr.Gateway)) {
  475. targetSDWAN := sr.Interface
  476. if !sdwan.IsSDWANGroup(targetSDWAN) {
  477. targetSDWAN = sr.Gateway
  478. }
  479. if resolved, ok := sdwan.ResolveGroupForRouting(targetSDWAN); ok {
  480. for _, nh := range resolved {
  481. if nh.Interface == lr.Interface || (nh.Gateway != "" && nh.Gateway == lr.Gateway) {
  482. gwMatches = true
  483. break
  484. }
  485. }
  486. }
  487. }
  488. if gwMatches {
  489. matchedLive[i] = true
  490. liveRoutes[i].Comment = sr.Comment
  491. liveRoutes[i].Static = true
  492. liveRoutes[i].Dynamic = false
  493. liveRoutes[i].Protocol = "static"
  494. liveRoutes[i].ID = sr.ID
  495. if sr.Interface != "" {
  496. liveRoutes[i].Interface = sr.Interface
  497. }
  498. if liveRoutes[i].Gateway == "" && sr.Gateway != "" {
  499. liveRoutes[i].Gateway = sr.Gateway
  500. }
  501. if sr.Distance > 0 && liveRoutes[i].Distance == 0 {
  502. liveRoutes[i].Distance = sr.Distance
  503. }
  504. liveRoutes[i].CheckGateway = sr.CheckGateway
  505. liveRoutes[i].CheckTarget = sr.CheckTarget
  506. liveRoutes[i].CheckInterval = sr.CheckInterval
  507. liveRoutes[i].CheckThreshold = sr.CheckThreshold
  508. liveRoutes[i].HealthStatus = sr.HealthStatus
  509. liveRoutes[i].HealthRTT = sr.HealthRTT
  510. liveRoutes[i].HealthLossPct = sr.HealthLossPct
  511. liveRoutes[i].HealthFailCount = sr.HealthFailCount
  512. liveRoutes[i].HealthLastCheck = sr.HealthLastCheck
  513. found = true
  514. break
  515. }
  516. }
  517. if !found {
  518. // Inactive or disabled static route
  519. srCopy := sr
  520. srCopy.Active = false
  521. srCopy.Static = true
  522. srCopy.Dynamic = false
  523. srCopy.Protocol = "static"
  524. liveRoutes = append(liveRoutes, srCopy)
  525. }
  526. }
  527. // Detect Equal-Cost Multi-Path (ECMP) routes
  528. groupCounts := make(map[string]int)
  529. for _, r := range liveRoutes {
  530. if r.Active && !r.Disabled {
  531. key := fmt.Sprintf("%s|%s|%d", normalizeDst(r.DstAddress), r.RoutingTable, r.Distance)
  532. groupCounts[key]++
  533. }
  534. }
  535. for i := range liveRoutes {
  536. key := fmt.Sprintf("%s|%s|%d", normalizeDst(liveRoutes[i].DstAddress), liveRoutes[i].RoutingTable, liveRoutes[i].Distance)
  537. if liveRoutes[i].IsMultiPath || (liveRoutes[i].Active && !liveRoutes[i].Disabled && groupCounts[key] > 1) {
  538. liveRoutes[i].ECMP = true
  539. }
  540. if liveRoutes[i].DstAddress == "224.0.0.0/4" || strings.HasPrefix(liveRoutes[i].DstAddress, "224.") || strings.HasPrefix(liveRoutes[i].DstAddress, "ff") {
  541. liveRoutes[i].Multicast = true
  542. }
  543. }
  544. sort.Slice(liveRoutes, func(i, j int) bool {
  545. if liveRoutes[i].RoutingTable != liveRoutes[j].RoutingTable {
  546. return liveRoutes[i].RoutingTable < liveRoutes[j].RoutingTable
  547. }
  548. if liveRoutes[i].DstAddress != liveRoutes[j].DstAddress {
  549. return liveRoutes[i].DstAddress < liveRoutes[j].DstAddress
  550. }
  551. return liveRoutes[i].Gateway < liveRoutes[j].Gateway
  552. })
  553. return liveRoutes
  554. }
  555. func (m *RoutingManager) SaveRoute(r *RouteItem) (err error) {
  556. if r == nil {
  557. return fmt.Errorf("route cannot be nil")
  558. }
  559. m.mu.Lock()
  560. defer m.mu.Unlock()
  561. before := append([]RouteItem(nil), m.staticRoutes...)
  562. dirty, applied := false, false
  563. defer func() {
  564. if err != nil && dirty {
  565. m.staticRoutes = before
  566. if applied {
  567. _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  568. }
  569. m.applyAll()
  570. _ = m.save()
  571. }
  572. }()
  573. if r.DstAddress == "" {
  574. return fmt.Errorf("destination address is required")
  575. }
  576. if r.DstAddress == "default" {
  577. r.DstAddress = "0.0.0.0/0"
  578. }
  579. if r.RoutingTable == "" {
  580. r.RoutingTable = "main"
  581. }
  582. if _, _, parseErr := net.ParseCIDR(r.DstAddress); parseErr != nil && net.ParseIP(r.DstAddress) == nil {
  583. return fmt.Errorf("invalid destination: %s", r.DstAddress)
  584. }
  585. dirty = true
  586. r.Static = true
  587. origID := r.ID
  588. foundIndex := -1
  589. // 1. Direct ID match in static routes (if not a temporary/kernel route ID)
  590. if r.ID != "" && !strings.HasPrefix(r.ID, "kr-") {
  591. for i, existing := range m.staticRoutes {
  592. if existing.ID == r.ID {
  593. foundIndex = i
  594. break
  595. }
  596. }
  597. }
  598. // 2. Match by OldDstAddress / OldGateway passed from the edit modal
  599. if foundIndex == -1 && r.OldDstAddress != "" {
  600. normOldDst := normalizeDst(r.OldDstAddress)
  601. oldTable := r.OldRoutingTable
  602. if oldTable == "" {
  603. oldTable = "main"
  604. }
  605. for i, existing := range m.staticRoutes {
  606. exTbl := existing.RoutingTable
  607. if exTbl == "" {
  608. exTbl = "main"
  609. }
  610. if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
  611. oldGwMatches := r.OldGateway == "" ||
  612. existing.Gateway == r.OldGateway ||
  613. existing.Interface == r.OldGateway ||
  614. (r.OldInterface != "" && existing.Interface == r.OldInterface)
  615. if oldGwMatches {
  616. foundIndex = i
  617. break
  618. }
  619. }
  620. }
  621. }
  622. // 3. Match by target DstAddress + Table + Gateway/Interface (prevent duplicates on re-save)
  623. if foundIndex == -1 {
  624. normNewDst := normalizeDst(r.DstAddress)
  625. for i, existing := range m.staticRoutes {
  626. exTbl := existing.RoutingTable
  627. if exTbl == "" {
  628. exTbl = "main"
  629. }
  630. if normalizeDst(existing.DstAddress) == normNewDst && exTbl == r.RoutingTable {
  631. gwMatches := (existing.Gateway != "" && existing.Gateway == r.Gateway) ||
  632. (existing.Interface != "" && existing.Interface == r.Interface) ||
  633. (existing.Gateway == "" && r.Gateway == "")
  634. if gwMatches {
  635. foundIndex = i
  636. break
  637. }
  638. }
  639. }
  640. }
  641. // 4. Fallback match: if editing with OldDstAddress but gateway was changed and didn't match oldGw
  642. if foundIndex == -1 && r.OldDstAddress != "" {
  643. normOldDst := normalizeDst(r.OldDstAddress)
  644. oldTable := r.OldRoutingTable
  645. if oldTable == "" {
  646. oldTable = "main"
  647. }
  648. for i, existing := range m.staticRoutes {
  649. exTbl := existing.RoutingTable
  650. if exTbl == "" {
  651. exTbl = "main"
  652. }
  653. if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
  654. foundIndex = i
  655. break
  656. }
  657. }
  658. }
  659. if r.CheckInterval <= 0 {
  660. r.CheckInterval = 5
  661. }
  662. if r.CheckThreshold <= 0 {
  663. r.CheckThreshold = 3
  664. }
  665. if r.CheckGateway == "internet" && strings.TrimSpace(r.CheckTarget) == "" {
  666. r.CheckTarget = "1.1.1.1"
  667. }
  668. if r.CheckGateway != "" && r.CheckGateway != "none" {
  669. if r.HealthStatus == "" {
  670. r.HealthStatus = "checking"
  671. }
  672. } else {
  673. r.CheckGateway = "none"
  674. r.HealthStatus = "none"
  675. }
  676. var oldRouteToClean *RouteItem
  677. if foundIndex >= 0 {
  678. oldExisting := m.staticRoutes[foundIndex]
  679. r.ID = oldExisting.ID // Preserve persistent ID!
  680. if normalizeDst(oldExisting.DstAddress) != normalizeDst(r.DstAddress) ||
  681. oldExisting.RoutingTable != r.RoutingTable ||
  682. oldExisting.Distance != r.Distance ||
  683. oldExisting.Gateway != r.Gateway ||
  684. oldExisting.Interface != r.Interface {
  685. oldCopy := oldExisting
  686. oldRouteToClean = &oldCopy
  687. }
  688. if r.HealthStatus == "checking" && oldExisting.HealthStatus != "" && oldExisting.CheckGateway == r.CheckGateway {
  689. r.HealthStatus = oldExisting.HealthStatus
  690. r.HealthRTT = oldExisting.HealthRTT
  691. r.HealthLossPct = oldExisting.HealthLossPct
  692. r.HealthLastCheck = oldExisting.HealthLastCheck
  693. }
  694. m.staticRoutes[foundIndex] = *r
  695. } else {
  696. if r.ID == "" || strings.HasPrefix(r.ID, "kr-") {
  697. r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  698. }
  699. // If adopting a live kernel route not in staticRoutes, remove it from direct kernel routes
  700. if strings.HasPrefix(origID, "kr-") {
  701. for _, lr := range m.listLiveRoutesLocked() {
  702. if lr.ID == origID {
  703. break
  704. }
  705. }
  706. }
  707. m.staticRoutes = append(m.staticRoutes, *r)
  708. }
  709. if r.OldDstAddress != "" {
  710. oldDist := 0
  711. if r.OldDistance != nil {
  712. oldDist = *r.OldDistance
  713. }
  714. if normalizeDst(r.OldDstAddress) != normalizeDst(r.DstAddress) ||
  715. r.OldRoutingTable != r.RoutingTable ||
  716. oldDist != r.Distance ||
  717. r.OldGateway != r.Gateway ||
  718. r.OldInterface != r.Interface {
  719. oldRouteToClean = &RouteItem{
  720. DstAddress: r.OldDstAddress,
  721. Gateway: r.OldGateway,
  722. RoutingTable: r.OldRoutingTable,
  723. Distance: oldDist,
  724. Interface: r.OldInterface,
  725. }
  726. }
  727. }
  728. for i := range m.staticRoutes {
  729. if m.staticRoutes[i].ID == r.ID {
  730. if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
  731. m.staticRoutes[i].Active = true
  732. } else {
  733. m.staticRoutes[i].Active = false
  734. }
  735. break
  736. }
  737. }
  738. // In-memory deduplication pass on static routes
  739. seenKeys := make(map[string]bool)
  740. var deduped []RouteItem
  741. for _, sr := range m.staticRoutes {
  742. k := fmt.Sprintf("%s|%s|%s|%s|%d", normalizeDst(sr.DstAddress), sr.RoutingTable, sr.Gateway, sr.Interface, sr.Distance)
  743. if !seenKeys[k] {
  744. seenKeys[k] = true
  745. deduped = append(deduped, sr)
  746. }
  747. }
  748. m.staticRoutes = deduped
  749. if saveErr := m.save(); saveErr != nil {
  750. return saveErr
  751. }
  752. // Clean up old route group if destination, routing table, distance, gateway, or interface changed
  753. if oldRouteToClean != nil {
  754. _ = m.syncRouteGroupToKernel(oldRouteToClean.DstAddress, oldRouteToClean.RoutingTable, oldRouteToClean.Distance)
  755. _ = m.deleteDirectKernelRoute(*oldRouteToClean)
  756. }
  757. // Apply updated/new route group to kernel
  758. if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
  759. return err
  760. }
  761. applied = true
  762. return nil
  763. }
  764. func (m *RoutingManager) DeleteRoute(id string) error {
  765. m.mu.Lock()
  766. defer m.mu.Unlock()
  767. before := append([]RouteItem(nil), m.staticRoutes...)
  768. var updated []RouteItem
  769. var target *RouteItem
  770. // 1. Direct ID match in static routes
  771. for _, r := range m.staticRoutes {
  772. if r.ID == id {
  773. targetCopy := r
  774. target = &targetCopy
  775. } else {
  776. updated = append(updated, r)
  777. }
  778. }
  779. // 2. If not found by direct ID, check if it's a live kernel route ID (e.g. kr-...)
  780. if target == nil {
  781. updated = nil
  782. for _, lr := range m.listLiveRoutesLocked() {
  783. if lr.ID == id {
  784. // Check if any static route corresponds to this live route
  785. matchIdx := -1
  786. normLrDst := normalizeDst(lr.DstAddress)
  787. for i, sr := range m.staticRoutes {
  788. gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
  789. if normalizeDst(sr.DstAddress) == normLrDst && sr.RoutingTable == lr.RoutingTable && gwMatches {
  790. matchIdx = i
  791. break
  792. }
  793. }
  794. if matchIdx >= 0 {
  795. targetCopy := m.staticRoutes[matchIdx]
  796. target = &targetCopy
  797. for idx, r := range m.staticRoutes {
  798. if idx != matchIdx {
  799. updated = append(updated, r)
  800. }
  801. }
  802. _ = m.deleteDirectKernelRoute(lr)
  803. break
  804. } else {
  805. // Pure kernel route, not managed in static_routes.json
  806. return m.deleteDirectKernelRoute(lr)
  807. }
  808. }
  809. }
  810. }
  811. if target != nil {
  812. m.staticRoutes = updated
  813. return m.commitManagedRouteChange(before, *target)
  814. }
  815. return fmt.Errorf("route not found")
  816. }
  817. // commitManagedRouteChange is called with the routing manager lock held.
  818. func (m *RoutingManager) commitManagedRouteChange(before []RouteItem, route RouteItem) error {
  819. if err := m.save(); err != nil {
  820. m.staticRoutes = before
  821. return errors.Join(fmt.Errorf("saving route change: %w", err), m.save())
  822. }
  823. if err := m.syncRouteGroupToKernel(route.DstAddress, route.RoutingTable, route.Distance); err != nil {
  824. m.staticRoutes = before
  825. saveErr := m.save()
  826. reapplyErr := m.syncRouteGroupToKernel(route.DstAddress, route.RoutingTable, route.Distance)
  827. if saveErr != nil {
  828. saveErr = fmt.Errorf("restoring stored routes: %w", saveErr)
  829. }
  830. if reapplyErr != nil {
  831. reapplyErr = fmt.Errorf("reapplying previous route: %w", reapplyErr)
  832. }
  833. return errors.Join(fmt.Errorf("applying route change: %w", err), saveErr, reapplyErr)
  834. }
  835. return nil
  836. }
  837. func (m *RoutingManager) SetRouteState(id string, disabled bool) error {
  838. m.mu.Lock()
  839. defer m.mu.Unlock()
  840. for i := range m.staticRoutes {
  841. if m.staticRoutes[i].ID == id {
  842. before := append([]RouteItem(nil), m.staticRoutes...)
  843. m.staticRoutes[i].Disabled = disabled
  844. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  845. m.staticRoutes[i].Active = true
  846. } else if disabled {
  847. m.staticRoutes[i].Active = false
  848. }
  849. return m.commitManagedRouteChange(before, m.staticRoutes[i])
  850. }
  851. }
  852. // If not in staticRoutes, could be a live route ID (kr-...)
  853. for _, lr := range m.listLiveRoutesLocked() {
  854. if lr.ID == id {
  855. // Check if any static route corresponds to this live route
  856. normLrDst := normalizeDst(lr.DstAddress)
  857. for i := range m.staticRoutes {
  858. 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)
  859. if normalizeDst(m.staticRoutes[i].DstAddress) == normLrDst && m.staticRoutes[i].RoutingTable == lr.RoutingTable && gwMatches {
  860. before := append([]RouteItem(nil), m.staticRoutes...)
  861. m.staticRoutes[i].Disabled = disabled
  862. if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
  863. m.staticRoutes[i].Active = true
  864. } else if disabled {
  865. m.staticRoutes[i].Active = false
  866. }
  867. return m.commitManagedRouteChange(before, m.staticRoutes[i])
  868. }
  869. }
  870. // If pure kernel static route, adopt into staticRoutes as disabled
  871. if disabled {
  872. lr.Disabled = true
  873. lr.Static = true
  874. lr.Active = false
  875. lr.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
  876. before := append([]RouteItem(nil), m.staticRoutes...)
  877. m.staticRoutes = append(m.staticRoutes, lr)
  878. if err := m.save(); err != nil {
  879. m.staticRoutes = before
  880. return fmt.Errorf("saving adopted route: %w", err)
  881. }
  882. if err := m.syncRouteGroupToKernel(lr.DstAddress, lr.RoutingTable, lr.Distance); err != nil {
  883. m.staticRoutes = before
  884. return errors.Join(fmt.Errorf("disabling adopted route: %w", err), m.save())
  885. }
  886. return nil
  887. }
  888. }
  889. }
  890. return fmt.Errorf("route not found")
  891. }
  892. func sliceContains(list []string, item string) bool {
  893. for _, s := range list {
  894. if s == item {
  895. return true
  896. }
  897. }
  898. return false
  899. }
  900. func normalizeDst(dst string) string {
  901. dst = strings.TrimSpace(dst)
  902. if dst == "" || dst == "default" || dst == "0.0.0.0/0" {
  903. return "default"
  904. }
  905. if !strings.Contains(dst, "/") && net.ParseIP(dst) != nil {
  906. return dst + "/32"
  907. }
  908. return dst
  909. }
  910. func detectGatewayForInterface(ifaceName string) string {
  911. link, err := netlink.LinkByName(ifaceName)
  912. if err == nil {
  913. routes, err := netlink.RouteList(link, netlink.FAMILY_V4)
  914. if err == nil {
  915. for _, r := range routes {
  916. if (r.Dst == nil || r.Dst.IP.IsUnspecified()) && r.Gw != nil && !r.Gw.IsUnspecified() {
  917. return r.Gw.String()
  918. }
  919. }
  920. for _, r := range routes {
  921. if r.Gw != nil && !r.Gw.IsUnspecified() {
  922. return r.Gw.String()
  923. }
  924. }
  925. }
  926. }
  927. out, err := exec.Command("ip", "route", "show", "dev", ifaceName).CombinedOutput()
  928. if err == nil {
  929. lines := strings.Split(string(out), "\n")
  930. for _, l := range lines {
  931. if strings.Contains(l, "via ") {
  932. fields := strings.Fields(l)
  933. for i, f := range fields {
  934. if f == "via" && i+1 < len(fields) {
  935. gw := fields[i+1]
  936. if net.ParseIP(gw) != nil {
  937. return gw
  938. }
  939. }
  940. }
  941. }
  942. }
  943. }
  944. return ""
  945. }
  946. func (m *RoutingManager) syncRouteGroupToKernel(dstAddress, routingTable string, distance int) error {
  947. normDst := normalizeDst(dstAddress)
  948. tbl := strings.TrimSpace(routingTable)
  949. if tbl == "" {
  950. tbl = "main"
  951. }
  952. var activeRoutes []RouteItem
  953. for _, r := range m.staticRoutes {
  954. rDst := normalizeDst(r.DstAddress)
  955. rTbl := strings.TrimSpace(r.RoutingTable)
  956. if rTbl == "" {
  957. rTbl = "main"
  958. }
  959. if rDst == normDst && rTbl == tbl && r.Distance == distance {
  960. if !r.Disabled && r.Active && r.HealthStatus != "offline" {
  961. activeRoutes = append(activeRoutes, r)
  962. }
  963. }
  964. }
  965. if len(activeRoutes) == 0 {
  966. // Safety guard: if all default routes are marked offline, do NOT delete the default route into a blackout!
  967. // Fallback to keeping all enabled static routes in the group active so recovery traffic and emergency pings can flow.
  968. if normDst == "default" {
  969. var fallbackRoutes []RouteItem
  970. for _, r := range m.staticRoutes {
  971. rDst := normalizeDst(r.DstAddress)
  972. rTbl := strings.TrimSpace(r.RoutingTable)
  973. if rTbl == "" {
  974. rTbl = "main"
  975. }
  976. if rDst == normDst && rTbl == tbl && r.Distance == distance && !r.Disabled {
  977. fallbackRoutes = append(fallbackRoutes, r)
  978. }
  979. }
  980. if len(fallbackRoutes) > 0 {
  981. log.Printf("[RouteManager] All default routes offline in group! Keeping fallback routes active to prevent blackout")
  982. activeRoutes = fallbackRoutes
  983. }
  984. }
  985. }
  986. if len(activeRoutes) == 0 {
  987. // Only touch the requested static route group. Broad fallbacks can delete
  988. // a route from another table, metric, or routing protocol.
  989. for _, routeType := range []string{"", "blackhole"} {
  990. args := []string{"route", "del"}
  991. if routeType != "" {
  992. args = append(args, routeType)
  993. }
  994. args = append(args, normDst, "metric", strconv.Itoa(distance), "table", tbl, "proto", "static")
  995. out, err := exec.Command("ip", args...).CombinedOutput()
  996. missing := strings.Contains(string(out), "No such process") || (tbl == "main" && strings.Contains(string(out), "FIB table does not exist"))
  997. if err != nil && !missing {
  998. return fmt.Errorf("failed to delete static route group (%s): %s: %w", strings.Join(args, " "), strings.TrimSpace(string(out)), err)
  999. }
  1000. }
  1001. return nil
  1002. }
  1003. type expandedNexthop struct {
  1004. Gateway string
  1005. Interface string
  1006. Weight int
  1007. }
  1008. var allNexthops []expandedNexthop
  1009. isBlackhole := false
  1010. for _, r := range activeRoutes {
  1011. gw := strings.TrimSpace(r.Gateway)
  1012. iface := strings.TrimSpace(r.Interface)
  1013. if strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole") {
  1014. isBlackhole = true
  1015. break
  1016. }
  1017. // Check if interface or gateway specifies an SD-WAN virtual group
  1018. targetSDWAN := ""
  1019. if sdwan.IsSDWANGroup(iface) {
  1020. targetSDWAN = iface
  1021. } else if sdwan.IsSDWANGroup(gw) {
  1022. targetSDWAN = gw
  1023. }
  1024. if targetSDWAN != "" {
  1025. resolved, ok := sdwan.ResolveGroupForRouting(targetSDWAN)
  1026. if ok && len(resolved) > 0 {
  1027. for _, nh := range resolved {
  1028. allNexthops = append(allNexthops, expandedNexthop{
  1029. Gateway: nh.Gateway,
  1030. Interface: nh.Interface,
  1031. Weight: nh.Weight,
  1032. })
  1033. }
  1034. continue
  1035. }
  1036. }
  1037. // Standard static route
  1038. if gw != "" && net.ParseIP(gw) == nil && iface == "" {
  1039. iface = gw
  1040. gw = ""
  1041. }
  1042. if gw == "" && iface != "" {
  1043. gw = detectGatewayForInterface(iface)
  1044. }
  1045. allNexthops = append(allNexthops, expandedNexthop{
  1046. Gateway: gw,
  1047. Interface: iface,
  1048. Weight: 1,
  1049. })
  1050. }
  1051. if isBlackhole {
  1052. args := []string{"route", "replace", "blackhole", normDst}
  1053. if distance > 0 {
  1054. args = append(args, "metric", strconv.Itoa(distance))
  1055. }
  1056. if tbl != "main" {
  1057. args = append(args, "table", tbl)
  1058. }
  1059. args = append(args, "proto", "static")
  1060. if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil {
  1061. return fmt.Errorf("failed to apply blackhole route: %s: %w", string(out), err)
  1062. }
  1063. return nil
  1064. }
  1065. if len(allNexthops) == 0 {
  1066. return nil
  1067. }
  1068. if len(allNexthops) == 1 {
  1069. nh := allNexthops[0]
  1070. args := []string{"route", "replace", normDst}
  1071. hasVia := false
  1072. if nh.Gateway != "" && net.ParseIP(nh.Gateway) != nil {
  1073. args = append(args, "via", nh.Gateway)
  1074. hasVia = true
  1075. }
  1076. if nh.Interface != "" {
  1077. args = append(args, "dev", nh.Interface)
  1078. }
  1079. if hasVia && nh.Interface != "" {
  1080. args = append(args, "onlink")
  1081. }
  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. cmd := exec.Command("ip", args...)
  1090. if out, err := cmd.CombinedOutput(); err != nil {
  1091. if sliceContains(args, "onlink") {
  1092. var noOnlinkArgs []string
  1093. for _, a := range args {
  1094. if a != "onlink" {
  1095. noOnlinkArgs = append(noOnlinkArgs, a)
  1096. }
  1097. }
  1098. if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
  1099. return nil
  1100. }
  1101. }
  1102. return fmt.Errorf("failed to apply route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1103. }
  1104. return nil
  1105. }
  1106. // Multiple nexthops: ECMP multipath route
  1107. args := []string{"route", "replace", normDst, "scope", "global"}
  1108. if distance > 0 {
  1109. args = append(args, "metric", strconv.Itoa(distance))
  1110. }
  1111. if tbl != "main" {
  1112. args = append(args, "table", tbl)
  1113. }
  1114. args = append(args, "proto", "static")
  1115. for _, nh := range allNexthops {
  1116. args = append(args, "nexthop")
  1117. hasVia := false
  1118. if nh.Gateway != "" && net.ParseIP(nh.Gateway) != nil {
  1119. args = append(args, "via", nh.Gateway)
  1120. hasVia = true
  1121. }
  1122. if nh.Interface != "" {
  1123. args = append(args, "dev", nh.Interface)
  1124. }
  1125. if hasVia && nh.Interface != "" {
  1126. args = append(args, "onlink")
  1127. }
  1128. w := nh.Weight
  1129. if w <= 0 {
  1130. w = 1
  1131. }
  1132. args = append(args, "weight", strconv.Itoa(w))
  1133. }
  1134. cmd := exec.Command("ip", args...)
  1135. if out, err := cmd.CombinedOutput(); err != nil {
  1136. if sliceContains(args, "onlink") {
  1137. var noOnlinkArgs []string
  1138. for _, a := range args {
  1139. if a != "onlink" {
  1140. noOnlinkArgs = append(noOnlinkArgs, a)
  1141. }
  1142. }
  1143. if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
  1144. return nil
  1145. }
  1146. }
  1147. return fmt.Errorf("failed to apply multipath route (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1148. }
  1149. return nil
  1150. }
  1151. // SyncSDWANRoutes reapplies kernel routes for static routes referencing SD-WAN groups when group state changes.
  1152. func (m *RoutingManager) SyncSDWANRoutes() {
  1153. m.mu.Lock()
  1154. defer m.mu.Unlock()
  1155. type groupKey struct {
  1156. dst string
  1157. table string
  1158. dist int
  1159. }
  1160. seen := make(map[groupKey]bool)
  1161. var groupsToSync []groupKey
  1162. for _, r := range m.staticRoutes {
  1163. if r.Disabled {
  1164. continue
  1165. }
  1166. if sdwan.IsSDWANGroup(r.Interface) || sdwan.IsSDWANGroup(r.Gateway) {
  1167. tbl := strings.TrimSpace(r.RoutingTable)
  1168. if tbl == "" {
  1169. tbl = "main"
  1170. }
  1171. normDst := normalizeDst(r.DstAddress)
  1172. k := groupKey{dst: normDst, table: tbl, dist: r.Distance}
  1173. if !seen[k] {
  1174. seen[k] = true
  1175. groupsToSync = append(groupsToSync, groupKey{dst: r.DstAddress, table: tbl, dist: r.Distance})
  1176. }
  1177. }
  1178. }
  1179. for _, g := range groupsToSync {
  1180. if err := m.syncRouteGroupToKernel(g.dst, g.table, g.dist); err != nil {
  1181. log.Printf("[RouteManager] SD-WAN failover route sync failed for %s (%s metric %d): %v", g.dst, g.table, g.dist, err)
  1182. } else {
  1183. log.Printf("[RouteManager] SD-WAN failover synced route %s (%s metric %d) successfully", g.dst, g.table, g.dist)
  1184. }
  1185. }
  1186. }
  1187. func (m *RoutingManager) applyRouteToKernel(r RouteItem) error {
  1188. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1189. }
  1190. func (m *RoutingManager) removeRouteFromKernel(r RouteItem) error {
  1191. return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
  1192. }
  1193. func (m *RoutingManager) deleteDirectKernelRoute(r RouteItem) error {
  1194. normDst := normalizeDst(r.DstAddress)
  1195. gw := strings.TrimSpace(r.Gateway)
  1196. isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
  1197. var args []string
  1198. if isBlackhole {
  1199. args = []string{"route", "del", "blackhole", normDst}
  1200. } else {
  1201. args = []string{"route", "del", normDst}
  1202. if gw != "" && net.ParseIP(gw) != nil {
  1203. args = append(args, "via", gw)
  1204. }
  1205. iface := strings.TrimSpace(r.Interface)
  1206. if iface != "" {
  1207. args = append(args, "dev", iface)
  1208. }
  1209. }
  1210. if r.RoutingTable != "" && r.RoutingTable != "main" {
  1211. args = append(args, "table", r.RoutingTable)
  1212. }
  1213. if r.Distance > 0 {
  1214. args = append(args, "metric", strconv.Itoa(r.Distance))
  1215. }
  1216. out, err := exec.Command("ip", args...).CombinedOutput()
  1217. if err != nil {
  1218. return fmt.Errorf("failed to delete route (%s): %s: %w", strings.Join(args, " "), strings.TrimSpace(string(out)), err)
  1219. }
  1220. return nil
  1221. }
  1222. // ==================== Policy Rules (/ip route rule) ====================
  1223. func (m *RoutingManager) ListPolicyRules() []PolicyRuleItem {
  1224. m.mu.Lock()
  1225. defer m.mu.Unlock()
  1226. // Query live rules from kernel
  1227. rules, err := netlink.RuleList(netlink.FAMILY_V4)
  1228. if err != nil {
  1229. return m.policyRules
  1230. }
  1231. tableNames := m.getTableMap()
  1232. var res []PolicyRuleItem
  1233. userRulesByPrio := make(map[int]PolicyRuleItem)
  1234. for _, pr := range m.policyRules {
  1235. userRulesByPrio[pr.Priority] = pr
  1236. }
  1237. for _, r := range rules {
  1238. tableName := "main"
  1239. if name, ok := tableNames[r.Table]; ok {
  1240. tableName = name
  1241. } else if r.Table != 254 && r.Table != 0 {
  1242. tableName = strconv.Itoa(r.Table)
  1243. }
  1244. src := ""
  1245. if r.Src != nil {
  1246. src = r.Src.String()
  1247. }
  1248. dst := ""
  1249. if r.Dst != nil {
  1250. dst = r.Dst.String()
  1251. }
  1252. markStr := ""
  1253. if r.Mark > 0 {
  1254. markStr = fmt.Sprintf("0x%x (%d)", r.Mark, r.Mark)
  1255. }
  1256. id := fmt.Sprintf("rule-%d-%d", r.Priority, r.Table)
  1257. comment := ""
  1258. isDefault := false
  1259. isSystem := false
  1260. if r.Priority == 0 || r.Priority == 32766 || r.Priority == 32767 {
  1261. isDefault = true
  1262. isSystem = true
  1263. } else if userRule, ok := userRulesByPrio[r.Priority]; ok {
  1264. if userRule.ID != "" {
  1265. id = userRule.ID
  1266. }
  1267. comment = userRule.Comment
  1268. isDefault = false
  1269. isSystem = false
  1270. } else {
  1271. // System/daemon rule not added by user in debtik (e.g. WireGuard, IPsec)
  1272. isSystem = true
  1273. }
  1274. res = append(res, PolicyRuleItem{
  1275. ID: id,
  1276. Priority: r.Priority,
  1277. SrcAddress: src,
  1278. DstAddress: dst,
  1279. RoutingMark: markStr,
  1280. Table: tableName,
  1281. TableID: r.Table,
  1282. Action: "lookup",
  1283. Comment: comment,
  1284. IsDefault: isDefault,
  1285. IsSystem: isSystem,
  1286. })
  1287. }
  1288. return res
  1289. }
  1290. func (m *RoutingManager) SavePolicyRule(pr PolicyRuleItem) error {
  1291. m.mu.Lock()
  1292. defer m.mu.Unlock()
  1293. if pr.Table == "" {
  1294. pr.Table = "main"
  1295. }
  1296. if pr.ID == "" {
  1297. pr.ID = fmt.Sprintf("prule-%d", time.Now().UnixNano())
  1298. }
  1299. if pr.Priority == 0 {
  1300. pr.Priority = 1000 + len(m.policyRules)*10
  1301. }
  1302. if err := m.applyRuleToKernel(pr); err != nil {
  1303. return err
  1304. }
  1305. m.policyRules = append(m.policyRules, pr)
  1306. return m.save()
  1307. }
  1308. func (m *RoutingManager) DeletePolicyRule(id string) error {
  1309. m.mu.Lock()
  1310. defer m.mu.Unlock()
  1311. var updated []PolicyRuleItem
  1312. var target *PolicyRuleItem
  1313. for _, pr := range m.policyRules {
  1314. if pr.ID == id || fmt.Sprintf("rule-%d-%d", pr.Priority, pr.TableID) == id {
  1315. target = &pr
  1316. } else {
  1317. updated = append(updated, pr)
  1318. }
  1319. }
  1320. if target != nil {
  1321. _ = m.removeRuleFromKernel(*target)
  1322. } else if strings.HasPrefix(id, "rule-") {
  1323. parts := strings.Split(id, "-")
  1324. if len(parts) >= 2 {
  1325. if prio, err := strconv.Atoi(parts[1]); err == nil && prio > 0 {
  1326. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(prio)).Run()
  1327. }
  1328. }
  1329. }
  1330. m.policyRules = updated
  1331. return m.save()
  1332. }
  1333. func (m *RoutingManager) applyRuleToKernel(pr PolicyRuleItem) error {
  1334. args := []string{"rule", "add"}
  1335. if pr.Priority > 0 {
  1336. args = append(args, "pref", strconv.Itoa(pr.Priority))
  1337. }
  1338. if pr.SrcAddress != "" {
  1339. args = append(args, "from", pr.SrcAddress)
  1340. }
  1341. if pr.DstAddress != "" {
  1342. args = append(args, "to", pr.DstAddress)
  1343. }
  1344. if pr.RoutingMark != "" {
  1345. // Clean mark string if it has (hex)
  1346. markClean := pr.RoutingMark
  1347. if strings.Contains(markClean, "(") {
  1348. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1349. }
  1350. args = append(args, "fwmark", markClean)
  1351. }
  1352. if pr.Table != "" {
  1353. args = append(args, "lookup", pr.Table)
  1354. }
  1355. cmd := exec.Command("ip", args...)
  1356. out, err := cmd.CombinedOutput()
  1357. if err != nil {
  1358. return fmt.Errorf("failed to add rule (%s): %s: %w", strings.Join(args, " "), string(out), err)
  1359. }
  1360. return nil
  1361. }
  1362. func (m *RoutingManager) removeRuleFromKernel(pr PolicyRuleItem) error {
  1363. if pr.Priority > 0 {
  1364. _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(pr.Priority)).Run()
  1365. return nil
  1366. }
  1367. args := []string{"rule", "del"}
  1368. if pr.RoutingMark != "" {
  1369. markClean := pr.RoutingMark
  1370. if strings.Contains(markClean, "(") {
  1371. markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
  1372. }
  1373. args = append(args, "fwmark", markClean)
  1374. }
  1375. if pr.Table != "" {
  1376. args = append(args, "lookup", pr.Table)
  1377. }
  1378. _ = exec.Command("ip", args...).Run()
  1379. return nil
  1380. }
  1381. // ==================== Routing Tables ====================
  1382. func (m *RoutingManager) ListTables() []RoutingTableItem {
  1383. m.mu.Lock()
  1384. defer m.mu.Unlock()
  1385. tables := []RoutingTableItem{
  1386. {Name: "main", TableID: 254, Comment: "Default system routing table"},
  1387. {Name: "default", TableID: 253, Comment: "Default fallback table"},
  1388. {Name: "local", TableID: 255, Comment: "Local kernel device table"},
  1389. }
  1390. tables = append(tables, m.customTables...)
  1391. return tables
  1392. }
  1393. func (m *RoutingManager) SaveTable(t RoutingTableItem) error {
  1394. m.mu.Lock()
  1395. defer m.mu.Unlock()
  1396. if t.Name == "" {
  1397. return fmt.Errorf("table name is required")
  1398. }
  1399. if t.TableID == 0 {
  1400. // Auto assign FIB ID starting at 100
  1401. t.TableID = 100 + len(m.customTables)
  1402. }
  1403. for _, existing := range m.customTables {
  1404. if existing.Name == t.Name || existing.TableID == t.TableID {
  1405. return fmt.Errorf("table with name %q or ID %d already exists", t.Name, t.TableID)
  1406. }
  1407. }
  1408. m.customTables = append(m.customTables, t)
  1409. _ = m.save()
  1410. m.syncCustomTablesToSystem()
  1411. return nil
  1412. }
  1413. func (m *RoutingManager) getTableMap() map[int]string {
  1414. tableMap := map[int]string{
  1415. 254: "main",
  1416. 253: "default",
  1417. 255: "local",
  1418. }
  1419. // Read /etc/iproute2/rt_tables
  1420. if f, err := os.Open(RTTableFilePath); err == nil {
  1421. defer f.Close()
  1422. scanner := bufio.NewScanner(f)
  1423. for scanner.Scan() {
  1424. line := strings.TrimSpace(scanner.Text())
  1425. if line == "" || strings.HasPrefix(line, "#") {
  1426. continue
  1427. }
  1428. parts := strings.Fields(line)
  1429. if len(parts) >= 2 {
  1430. if id, err := strconv.Atoi(parts[0]); err == nil {
  1431. tableMap[id] = parts[1]
  1432. }
  1433. }
  1434. }
  1435. }
  1436. for _, t := range m.customTables {
  1437. tableMap[t.TableID] = t.Name
  1438. }
  1439. return tableMap
  1440. }
  1441. func (m *RoutingManager) Stop() {
  1442. if m.stopChan != nil {
  1443. select {
  1444. case <-m.stopChan:
  1445. default:
  1446. close(m.stopChan)
  1447. }
  1448. }
  1449. }
  1450. // RenameInterface updates static routes and policy rules when an interface is renamed.
  1451. func (m *RoutingManager) RenameInterface(oldName, newName string) {
  1452. m.mu.Lock()
  1453. defer m.mu.Unlock()
  1454. changed := false
  1455. for i := range m.staticRoutes {
  1456. if m.staticRoutes[i].Interface == oldName {
  1457. m.staticRoutes[i].Interface = newName
  1458. changed = true
  1459. }
  1460. if m.staticRoutes[i].Gateway == oldName {
  1461. m.staticRoutes[i].Gateway = newName
  1462. changed = true
  1463. }
  1464. }
  1465. if changed {
  1466. _ = m.save()
  1467. }
  1468. }