manager.go 37 KB

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