| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643 |
- package routing
- import (
- "bufio"
- "encoding/json"
- "fmt"
- "log"
- "net"
- "os"
- "os/exec"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "debtik/internal/sdwan"
- "github.com/vishvananda/netlink"
- )
- var (
- StaticRoutesStorePath = "/etc/debtik/routing/static_routes.json"
- PolicyRulesStorePath = "/etc/debtik/routing/policy_rules.json"
- CustomTablesStorePath = "/etc/debtik/routing/custom_tables.json"
- RTTableFilePath = "/etc/iproute2/rt_tables"
- )
- type RoutingManager struct {
- mu sync.Mutex
- staticRoutes []RouteItem
- policyRules []PolicyRuleItem
- customTables []RoutingTableItem
- stopChan chan struct{}
- }
- func NewRoutingManager() *RoutingManager {
- m := &RoutingManager{
- staticRoutes: make([]RouteItem, 0),
- policyRules: make([]PolicyRuleItem, 0),
- customTables: make([]RoutingTableItem, 0),
- stopChan: make(chan struct{}),
- }
- m.initRTTableFile()
- m.load()
- m.syncCustomTablesToSystem()
- m.applyAll()
- m.startHealthCheckWorker()
- m.startRouteSyncWorker()
- sdwan.RegisterStateChangeCallback(func() {
- m.SyncSDWANRoutes()
- })
- return m
- }
- func (m *RoutingManager) initRTTableFile() {
- _ = os.MkdirAll(filepath.Dir(RTTableFilePath), 0755)
- if _, err := os.Stat(RTTableFilePath); os.IsNotExist(err) {
- // Copy from /usr/share/iproute2/rt_tables or seed default
- content, err := os.ReadFile("/usr/share/iproute2/rt_tables")
- if err == nil {
- _ = os.WriteFile(RTTableFilePath, content, 0644)
- } else {
- defaultContent := "# reserved values\n255\tlocal\n254\tmain\n253\tdefault\n0\tunspec\n"
- _ = os.WriteFile(RTTableFilePath, []byte(defaultContent), 0644)
- }
- }
- }
- func (m *RoutingManager) load() {
- if data, err := os.ReadFile(StaticRoutesStorePath); err == nil {
- _ = json.Unmarshal(data, &m.staticRoutes)
- }
- if data, err := os.ReadFile(PolicyRulesStorePath); err == nil {
- _ = json.Unmarshal(data, &m.policyRules)
- }
- if data, err := os.ReadFile(CustomTablesStorePath); err == nil {
- _ = json.Unmarshal(data, &m.customTables)
- }
- // Deduplicate static routes: if duplicates exist, keep the latest entry
- seenIDs := make(map[string]bool)
- seenKeys := make(map[string]bool)
- var dedupedRev []RouteItem
- hasDups := false
- // Traverse from end to start so latest updates take precedence
- for i := len(m.staticRoutes) - 1; i >= 0; i-- {
- r := m.staticRoutes[i]
- if r.ID == "" {
- r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
- }
- normDst := normalizeDst(r.DstAddress)
- tbl := r.RoutingTable
- if tbl == "" {
- tbl = "main"
- }
- gw := strings.TrimSpace(r.Gateway)
- iface := strings.TrimSpace(r.Interface)
- routeKey := fmt.Sprintf("%s|%s|%s|%s|%d", normDst, tbl, gw, iface, r.Distance)
- if seenIDs[r.ID] || seenKeys[routeKey] {
- 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)
- hasDups = true
- continue
- }
- seenIDs[r.ID] = true
- seenKeys[routeKey] = true
- dedupedRev = append(dedupedRev, r)
- }
- // Reverse back to original order
- var deduped []RouteItem
- for i := len(dedupedRev) - 1; i >= 0; i-- {
- deduped = append(deduped, dedupedRev[i])
- }
- if hasDups {
- m.staticRoutes = deduped
- _ = m.save()
- }
- for i := range m.staticRoutes {
- if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
- m.staticRoutes[i].Active = true
- }
- }
- }
- func (m *RoutingManager) save() error {
- _ = os.MkdirAll("/etc/debtik/routing", 0755)
- if data, err := json.MarshalIndent(m.staticRoutes, "", " "); err != nil {
- return err
- } else if err = os.WriteFile(StaticRoutesStorePath, data, 0600); err != nil {
- return err
- }
- if data, err := json.MarshalIndent(m.policyRules, "", " "); err != nil {
- return err
- } else if err = os.WriteFile(PolicyRulesStorePath, data, 0600); err != nil {
- return err
- }
- if data, err := json.MarshalIndent(m.customTables, "", " "); err != nil {
- return err
- } else if err = os.WriteFile(CustomTablesStorePath, data, 0600); err != nil {
- return err
- }
- return nil
- }
- func (m *RoutingManager) syncCustomTablesToSystem() {
- content, _ := os.ReadFile(RTTableFilePath)
- str := string(content)
- var sb strings.Builder
- sb.WriteString(str)
- for _, t := range m.customTables {
- check := fmt.Sprintf("\t%s", t.Name)
- if !strings.Contains(str, check) {
- sb.WriteString(fmt.Sprintf("%d\t%s\n", t.TableID, t.Name))
- }
- }
- _ = os.WriteFile(RTTableFilePath, []byte(sb.String()), 0644)
- }
- func (m *RoutingManager) cleanRogueDefaultRoutes() {
- hasManagedDefault := false
- for _, r := range m.staticRoutes {
- if normalizeDst(r.DstAddress) == "default" && !r.Disabled {
- hasManagedDefault = true
- break
- }
- }
- if !hasManagedDefault {
- return
- }
- routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
- if err != nil {
- return
- }
- links, _ := netlink.LinkList()
- linkMap := make(map[int]string)
- for _, l := range links {
- linkMap[l.Attrs().Index] = l.Attrs().Name
- }
- for _, r := range routes {
- if (r.Table == 254 || r.Table == 0) && r.Dst == nil && len(r.MultiPath) == 0 {
- gw := ""
- if r.Gw != nil {
- gw = r.Gw.String()
- }
- ifName := linkMap[r.LinkIndex]
- // If priority is 0 (unmetered route from dhclient or boot) and protocol != RTPROT_STATIC:
- if r.Priority == 0 && int(r.Protocol) != 4 {
- log.Printf("[RouteManager] Removing rogue unmanaged default route: via %s dev %s proto %d", gw, ifName, r.Protocol)
- _ = netlink.RouteDel(&r)
- }
- }
- }
- }
- func (m *RoutingManager) getTableIDByName(name string) int {
- name = strings.TrimSpace(name)
- if name == "" || name == "main" {
- return 254
- }
- if name == "default" {
- return 253
- }
- if name == "local" {
- return 255
- }
- for id, n := range m.getTableMap() {
- if strings.EqualFold(n, name) {
- return id
- }
- }
- if id, err := strconv.Atoi(name); err == nil {
- return id
- }
- return 254
- }
- func (m *RoutingManager) startRouteSyncWorker() {
- ticker := time.NewTicker(3 * time.Second)
- go func() {
- for {
- select {
- case <-m.stopChan:
- ticker.Stop()
- return
- case <-ticker.C:
- m.syncAllRoutesWorker()
- }
- }
- }()
- }
- func (m *RoutingManager) syncAllRoutesWorker() {
- m.mu.Lock()
- defer m.mu.Unlock()
- // Unmanaged routes belong to DHCP, the host or other routing daemons.
- liveRoutes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
- if err != nil {
- return
- }
- type groupKey struct {
- dst string
- table int
- dist int
- }
- kernelRouteGroups := make(map[groupKey]bool)
- for _, lr := range liveRoutes {
- dst := "default"
- if lr.Dst != nil {
- dst = lr.Dst.String()
- }
- tbl := lr.Table
- if tbl == 0 {
- tbl = 254
- }
- k := groupKey{dst: normalizeDst(dst), table: tbl, dist: lr.Priority}
- kernelRouteGroups[k] = true
- }
- seen := make(map[groupKey]bool)
- for _, r := range m.staticRoutes {
- if r.Disabled || r.HealthStatus == "offline" {
- continue
- }
- normDst := normalizeDst(r.DstAddress)
- tableID := m.getTableIDByName(r.RoutingTable)
- k := groupKey{dst: normDst, table: tableID, dist: r.Distance}
- if !seen[k] {
- seen[k] = true
- if !kernelRouteGroups[k] {
- log.Printf("[RouteSync] Missing kernel route %s table %s (id %d) metric %d -> Restoring", normDst, r.RoutingTable, tableID, r.Distance)
- if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
- log.Printf("route synchronization failed: %v", err)
- }
- }
- }
- }
- }
- func (m *RoutingManager) applyAll() {
- // Unmanaged routes belong to DHCP, the host or other routing daemons.
- // Apply all static routes grouped by (dst, table, distance) for ECMP
- type groupKey struct {
- dst string
- table string
- dist int
- }
- seen := make(map[groupKey]bool)
- for _, r := range m.staticRoutes {
- normDst := normalizeDst(r.DstAddress)
- tbl := strings.TrimSpace(r.RoutingTable)
- if tbl == "" {
- tbl = "main"
- }
- k := groupKey{dst: normDst, table: tbl, dist: r.Distance}
- if !seen[k] {
- seen[k] = true
- _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
- }
- }
- // Apply policy rules
- for _, pr := range m.policyRules {
- _ = m.applyRuleToKernel(pr)
- }
- }
- // ==================== Routes (/ip route) ====================
- func isDynamicProtocol(proto netlink.RouteProtocol) bool {
- switch int(proto) {
- case 11, // RTPROT_ZEBRA
- 12, // RTPROT_BIRD
- 16, // RTPROT_DHCP
- 42, // RTPROT_BABEL
- 186, // RTPROT_BGP
- 187, // RTPROT_ISIS
- 188, // RTPROT_OSPF
- 189, // RTPROT_RIP
- 192: // RTPROT_EIGRP
- return true
- default:
- return false
- }
- }
- func getRouteProtocolName(proto netlink.RouteProtocol, priority int, isDirect bool, isMulticast bool) string {
- if isMulticast {
- return "multicast"
- }
- switch int(proto) {
- case 16:
- return "dhcp"
- case 4:
- return "static"
- case 186:
- return "bgp"
- case 188:
- return "ospf"
- case 189:
- return "rip"
- case 11:
- return "zebra"
- case 42:
- return "babel"
- case 12: // RTPROT_BIRD
- if priority == 20 {
- return "bgp"
- } else if priority == 200 {
- return "ibgp"
- } else if priority == 110 {
- return "ospf"
- } else if priority == 120 {
- return "rip"
- }
- return "bgp"
- case 2:
- return "connected"
- case 3:
- return "boot"
- default:
- if isDirect {
- return "connected"
- }
- if priority == 20 {
- return "bgp"
- } else if priority == 200 {
- return "ibgp"
- } else if priority == 110 {
- return "ospf"
- } else if priority == 120 {
- return "rip"
- }
- return "static"
- }
- }
- func (m *RoutingManager) listLiveRoutesLocked() []RouteItem {
- tableNames := m.getTableMap()
- links, _ := netlink.LinkList()
- linkMap := make(map[int]string)
- for _, l := range links {
- linkMap[l.Attrs().Index] = l.Attrs().Name
- }
- var liveRoutes []RouteItem
- routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
- if err == nil {
- for _, r := range routes {
- dst := "0.0.0.0/0"
- if r.Dst != nil {
- dst = r.Dst.String()
- }
- gw := ""
- if r.Gw != nil {
- gw = r.Gw.String()
- }
- tableName := "main"
- if name, ok := tableNames[r.Table]; ok {
- tableName = name
- } else if r.Table != 254 && r.Table != 0 {
- tableName = strconv.Itoa(r.Table)
- }
- isDyn := isDynamicProtocol(r.Protocol)
- isDirect := (r.Scope == netlink.SCOPE_LINK || r.Protocol == netlink.RouteProtocol(2)) && !isDyn && r.Protocol != 4
- isStatic := !isDirect && !isDyn
- isMulticast := r.Type == 5 || strings.HasPrefix(dst, "224.") || strings.HasPrefix(dst, "ff") || dst == "224.0.0.0/4"
- protoName := getRouteProtocolName(r.Protocol, r.Priority, isDirect, isMulticast)
- if len(r.MultiPath) > 0 {
- for _, nh := range r.MultiPath {
- nhGw := ""
- if nh.Gw != nil {
- nhGw = nh.Gw.String()
- }
- nhIfName := linkMap[nh.LinkIndex]
- cleanDst := strings.ReplaceAll(dst, "/", "_")
- cleanGw := nhGw
- if cleanGw == "" {
- cleanGw = nhIfName
- }
- routeID := fmt.Sprintf("kr-%d-%s-%s", r.Table, cleanDst, cleanGw)
- liveRoutes = append(liveRoutes, RouteItem{
- ID: routeID,
- DstAddress: dst,
- Gateway: nhGw,
- Interface: nhIfName,
- Distance: r.Priority,
- Protocol: protoName,
- RoutingTable: tableName,
- TableID: r.Table,
- Active: true,
- Connect: isDirect,
- Dynamic: isDyn,
- Static: isStatic,
- ECMP: true,
- IsMultiPath: true,
- Multicast: isMulticast,
- Disabled: false,
- })
- }
- continue
- }
- ifName := linkMap[r.LinkIndex]
- act := "lookup"
- if r.Type == 6 { // RTN_BLACKHOLE
- gw = "blackhole"
- act = "blackhole"
- }
- cleanDst := strings.ReplaceAll(dst, "/", "_")
- cleanGw := gw
- if cleanGw == "" {
- cleanGw = ifName
- }
- routeID := fmt.Sprintf("kr-%d-%s-%s", r.Table, cleanDst, cleanGw)
- liveRoutes = append(liveRoutes, RouteItem{
- ID: routeID,
- DstAddress: dst,
- Gateway: gw,
- Action: act,
- Interface: ifName,
- Distance: r.Priority,
- Protocol: protoName,
- RoutingTable: tableName,
- TableID: r.Table,
- Active: true,
- Connect: isDirect,
- Dynamic: isDyn,
- Static: isStatic,
- Multicast: isMulticast,
- Disabled: false,
- })
- }
- }
- return liveRoutes
- }
- func (m *RoutingManager) ListRoutes() []RouteItem {
- m.mu.Lock()
- defer m.mu.Unlock()
- liveRoutes := m.listLiveRoutesLocked()
- // Merge static routes that might be disabled or have custom metadata
- matchedLive := make(map[int]bool)
- for _, sr := range m.staticRoutes {
- normSrDst := normalizeDst(sr.DstAddress)
- found := false
- for i, lr := range liveRoutes {
- if matchedLive[i] {
- continue
- }
- if normalizeDst(lr.DstAddress) != normSrDst {
- continue
- }
- if lr.RoutingTable != sr.RoutingTable {
- continue
- }
- gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
- if !gwMatches && (sdwan.IsSDWANGroup(sr.Interface) || sdwan.IsSDWANGroup(sr.Gateway)) {
- targetSDWAN := sr.Interface
- if !sdwan.IsSDWANGroup(targetSDWAN) {
- targetSDWAN = sr.Gateway
- }
- if resolved, ok := sdwan.ResolveGroupForRouting(targetSDWAN); ok {
- for _, nh := range resolved {
- if nh.Interface == lr.Interface || (nh.Gateway != "" && nh.Gateway == lr.Gateway) {
- gwMatches = true
- break
- }
- }
- }
- }
- if gwMatches {
- matchedLive[i] = true
- liveRoutes[i].Comment = sr.Comment
- liveRoutes[i].Static = true
- liveRoutes[i].Dynamic = false
- liveRoutes[i].Protocol = "static"
- liveRoutes[i].ID = sr.ID
- if sr.Interface != "" {
- liveRoutes[i].Interface = sr.Interface
- }
- if liveRoutes[i].Gateway == "" && sr.Gateway != "" {
- liveRoutes[i].Gateway = sr.Gateway
- }
- if sr.Distance > 0 && liveRoutes[i].Distance == 0 {
- liveRoutes[i].Distance = sr.Distance
- }
- liveRoutes[i].CheckGateway = sr.CheckGateway
- liveRoutes[i].CheckTarget = sr.CheckTarget
- liveRoutes[i].CheckInterval = sr.CheckInterval
- liveRoutes[i].CheckThreshold = sr.CheckThreshold
- liveRoutes[i].HealthStatus = sr.HealthStatus
- liveRoutes[i].HealthRTT = sr.HealthRTT
- liveRoutes[i].HealthLossPct = sr.HealthLossPct
- liveRoutes[i].HealthFailCount = sr.HealthFailCount
- liveRoutes[i].HealthLastCheck = sr.HealthLastCheck
- found = true
- break
- }
- }
- if !found {
- // Inactive or disabled static route
- srCopy := sr
- srCopy.Active = false
- srCopy.Static = true
- srCopy.Dynamic = false
- srCopy.Protocol = "static"
- liveRoutes = append(liveRoutes, srCopy)
- }
- }
- // Detect Equal-Cost Multi-Path (ECMP) routes
- groupCounts := make(map[string]int)
- for _, r := range liveRoutes {
- if r.Active && !r.Disabled {
- key := fmt.Sprintf("%s|%s|%d", normalizeDst(r.DstAddress), r.RoutingTable, r.Distance)
- groupCounts[key]++
- }
- }
- for i := range liveRoutes {
- key := fmt.Sprintf("%s|%s|%d", normalizeDst(liveRoutes[i].DstAddress), liveRoutes[i].RoutingTable, liveRoutes[i].Distance)
- if liveRoutes[i].IsMultiPath || (liveRoutes[i].Active && !liveRoutes[i].Disabled && groupCounts[key] > 1) {
- liveRoutes[i].ECMP = true
- }
- if liveRoutes[i].DstAddress == "224.0.0.0/4" || strings.HasPrefix(liveRoutes[i].DstAddress, "224.") || strings.HasPrefix(liveRoutes[i].DstAddress, "ff") {
- liveRoutes[i].Multicast = true
- }
- }
- sort.Slice(liveRoutes, func(i, j int) bool {
- if liveRoutes[i].RoutingTable != liveRoutes[j].RoutingTable {
- return liveRoutes[i].RoutingTable < liveRoutes[j].RoutingTable
- }
- if liveRoutes[i].DstAddress != liveRoutes[j].DstAddress {
- return liveRoutes[i].DstAddress < liveRoutes[j].DstAddress
- }
- return liveRoutes[i].Gateway < liveRoutes[j].Gateway
- })
- return liveRoutes
- }
- func (m *RoutingManager) SaveRoute(r *RouteItem) (err error) {
- if r == nil {
- return fmt.Errorf("route cannot be nil")
- }
- m.mu.Lock()
- defer m.mu.Unlock()
- before := append([]RouteItem(nil), m.staticRoutes...)
- dirty, applied := false, false
- defer func() {
- if err != nil && dirty {
- m.staticRoutes = before
- if applied {
- _ = m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
- }
- m.applyAll()
- _ = m.save()
- }
- }()
- if r.DstAddress == "" {
- return fmt.Errorf("destination address is required")
- }
- if r.DstAddress == "default" {
- r.DstAddress = "0.0.0.0/0"
- }
- if r.RoutingTable == "" {
- r.RoutingTable = "main"
- }
- if _, _, parseErr := net.ParseCIDR(r.DstAddress); parseErr != nil && net.ParseIP(r.DstAddress) == nil {
- return fmt.Errorf("invalid destination: %s", r.DstAddress)
- }
- dirty = true
- r.Static = true
- origID := r.ID
- foundIndex := -1
- // 1. Direct ID match in static routes (if not a temporary/kernel route ID)
- if r.ID != "" && !strings.HasPrefix(r.ID, "kr-") {
- for i, existing := range m.staticRoutes {
- if existing.ID == r.ID {
- foundIndex = i
- break
- }
- }
- }
- // 2. Match by OldDstAddress / OldGateway passed from the edit modal
- if foundIndex == -1 && r.OldDstAddress != "" {
- normOldDst := normalizeDst(r.OldDstAddress)
- oldTable := r.OldRoutingTable
- if oldTable == "" {
- oldTable = "main"
- }
- for i, existing := range m.staticRoutes {
- exTbl := existing.RoutingTable
- if exTbl == "" {
- exTbl = "main"
- }
- if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
- oldGwMatches := r.OldGateway == "" ||
- existing.Gateway == r.OldGateway ||
- existing.Interface == r.OldGateway ||
- (r.OldInterface != "" && existing.Interface == r.OldInterface)
- if oldGwMatches {
- foundIndex = i
- break
- }
- }
- }
- }
- // 3. Match by target DstAddress + Table + Gateway/Interface (prevent duplicates on re-save)
- if foundIndex == -1 {
- normNewDst := normalizeDst(r.DstAddress)
- for i, existing := range m.staticRoutes {
- exTbl := existing.RoutingTable
- if exTbl == "" {
- exTbl = "main"
- }
- if normalizeDst(existing.DstAddress) == normNewDst && exTbl == r.RoutingTable {
- gwMatches := (existing.Gateway != "" && existing.Gateway == r.Gateway) ||
- (existing.Interface != "" && existing.Interface == r.Interface) ||
- (existing.Gateway == "" && r.Gateway == "")
- if gwMatches {
- foundIndex = i
- break
- }
- }
- }
- }
- // 4. Fallback match: if editing with OldDstAddress but gateway was changed and didn't match oldGw
- if foundIndex == -1 && r.OldDstAddress != "" {
- normOldDst := normalizeDst(r.OldDstAddress)
- oldTable := r.OldRoutingTable
- if oldTable == "" {
- oldTable = "main"
- }
- for i, existing := range m.staticRoutes {
- exTbl := existing.RoutingTable
- if exTbl == "" {
- exTbl = "main"
- }
- if normalizeDst(existing.DstAddress) == normOldDst && exTbl == oldTable {
- foundIndex = i
- break
- }
- }
- }
- if r.CheckInterval <= 0 {
- r.CheckInterval = 5
- }
- if r.CheckThreshold <= 0 {
- r.CheckThreshold = 3
- }
- if r.CheckGateway == "internet" && strings.TrimSpace(r.CheckTarget) == "" {
- r.CheckTarget = "1.1.1.1"
- }
- if r.CheckGateway != "" && r.CheckGateway != "none" {
- if r.HealthStatus == "" {
- r.HealthStatus = "checking"
- }
- } else {
- r.CheckGateway = "none"
- r.HealthStatus = "none"
- }
- var oldRouteToClean *RouteItem
- if foundIndex >= 0 {
- oldExisting := m.staticRoutes[foundIndex]
- r.ID = oldExisting.ID // Preserve persistent ID!
- if normalizeDst(oldExisting.DstAddress) != normalizeDst(r.DstAddress) ||
- oldExisting.RoutingTable != r.RoutingTable ||
- oldExisting.Distance != r.Distance ||
- oldExisting.Gateway != r.Gateway ||
- oldExisting.Interface != r.Interface {
- oldCopy := oldExisting
- oldRouteToClean = &oldCopy
- }
- if r.HealthStatus == "checking" && oldExisting.HealthStatus != "" && oldExisting.CheckGateway == r.CheckGateway {
- r.HealthStatus = oldExisting.HealthStatus
- r.HealthRTT = oldExisting.HealthRTT
- r.HealthLossPct = oldExisting.HealthLossPct
- r.HealthLastCheck = oldExisting.HealthLastCheck
- }
- m.staticRoutes[foundIndex] = *r
- } else {
- if r.ID == "" || strings.HasPrefix(r.ID, "kr-") {
- r.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
- }
- // If adopting a live kernel route not in staticRoutes, remove it from direct kernel routes
- if strings.HasPrefix(origID, "kr-") {
- for _, lr := range m.listLiveRoutesLocked() {
- if lr.ID == origID {
- _ = m.deleteDirectKernelRoute(lr)
- break
- }
- }
- }
- m.staticRoutes = append(m.staticRoutes, *r)
- }
- if r.OldDstAddress != "" {
- oldDist := 0
- if r.OldDistance != nil {
- oldDist = *r.OldDistance
- }
- if normalizeDst(r.OldDstAddress) != normalizeDst(r.DstAddress) ||
- r.OldRoutingTable != r.RoutingTable ||
- oldDist != r.Distance ||
- r.OldGateway != r.Gateway ||
- r.OldInterface != r.Interface {
- oldRouteToClean = &RouteItem{
- DstAddress: r.OldDstAddress,
- Gateway: r.OldGateway,
- RoutingTable: r.OldRoutingTable,
- Distance: oldDist,
- Interface: r.OldInterface,
- }
- }
- }
- for i := range m.staticRoutes {
- if m.staticRoutes[i].ID == r.ID {
- if !m.staticRoutes[i].Disabled && m.staticRoutes[i].HealthStatus != "offline" {
- m.staticRoutes[i].Active = true
- } else {
- m.staticRoutes[i].Active = false
- }
- break
- }
- }
- // In-memory deduplication pass on static routes
- seenKeys := make(map[string]bool)
- var deduped []RouteItem
- for _, sr := range m.staticRoutes {
- k := fmt.Sprintf("%s|%s|%s|%s|%d", normalizeDst(sr.DstAddress), sr.RoutingTable, sr.Gateway, sr.Interface, sr.Distance)
- if !seenKeys[k] {
- seenKeys[k] = true
- deduped = append(deduped, sr)
- }
- }
- m.staticRoutes = deduped
- if saveErr := m.save(); saveErr != nil {
- return saveErr
- }
- // Clean up old route group if destination, routing table, distance, gateway, or interface changed
- if oldRouteToClean != nil {
- _ = m.syncRouteGroupToKernel(oldRouteToClean.DstAddress, oldRouteToClean.RoutingTable, oldRouteToClean.Distance)
- _ = m.deleteDirectKernelRoute(*oldRouteToClean)
- }
- // Apply updated/new route group to kernel
- if err := m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance); err != nil {
- return err
- }
- applied = true
- return nil
- }
- func (m *RoutingManager) DeleteRoute(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- var updated []RouteItem
- var target *RouteItem
- // 1. Direct ID match in static routes
- for _, r := range m.staticRoutes {
- if r.ID == id {
- targetCopy := r
- target = &targetCopy
- } else {
- updated = append(updated, r)
- }
- }
- // 2. If not found by direct ID, check if it's a live kernel route ID (e.g. kr-...)
- if target == nil {
- for _, lr := range m.listLiveRoutesLocked() {
- if lr.ID == id {
- // Check if any static route corresponds to this live route
- matchIdx := -1
- normLrDst := normalizeDst(lr.DstAddress)
- for i, sr := range m.staticRoutes {
- gwMatches := sr.Gateway == "" || lr.Gateway == sr.Gateway || lr.Interface == sr.Gateway || (sr.Interface != "" && lr.Interface == sr.Interface)
- if normalizeDst(sr.DstAddress) == normLrDst && sr.RoutingTable == lr.RoutingTable && gwMatches {
- matchIdx = i
- break
- }
- }
- if matchIdx >= 0 {
- targetCopy := m.staticRoutes[matchIdx]
- target = &targetCopy
- for idx, r := range m.staticRoutes {
- if idx != matchIdx {
- updated = append(updated, r)
- }
- }
- _ = m.deleteDirectKernelRoute(lr)
- break
- } else {
- // Pure kernel route, not managed in static_routes.json
- return m.deleteDirectKernelRoute(lr)
- }
- }
- }
- }
- if target != nil {
- m.staticRoutes = updated
- _ = m.save()
- _ = m.syncRouteGroupToKernel(target.DstAddress, target.RoutingTable, target.Distance)
- _ = m.deleteDirectKernelRoute(*target)
- return nil
- }
- return fmt.Errorf("route not found")
- }
- func (m *RoutingManager) SetRouteState(id string, disabled bool) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- for i := range m.staticRoutes {
- if m.staticRoutes[i].ID == id {
- m.staticRoutes[i].Disabled = disabled
- if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
- m.staticRoutes[i].Active = true
- } else if disabled {
- m.staticRoutes[i].Active = false
- }
- _ = m.save()
- _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
- return nil
- }
- }
- // If not in staticRoutes, could be a live route ID (kr-...)
- for _, lr := range m.listLiveRoutesLocked() {
- if lr.ID == id {
- // Check if any static route corresponds to this live route
- normLrDst := normalizeDst(lr.DstAddress)
- for i := range m.staticRoutes {
- 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)
- if normalizeDst(m.staticRoutes[i].DstAddress) == normLrDst && m.staticRoutes[i].RoutingTable == lr.RoutingTable && gwMatches {
- m.staticRoutes[i].Disabled = disabled
- if !disabled && m.staticRoutes[i].HealthStatus != "offline" {
- m.staticRoutes[i].Active = true
- } else if disabled {
- m.staticRoutes[i].Active = false
- }
- _ = m.save()
- _ = m.syncRouteGroupToKernel(m.staticRoutes[i].DstAddress, m.staticRoutes[i].RoutingTable, m.staticRoutes[i].Distance)
- return nil
- }
- }
- // If pure kernel static route, adopt into staticRoutes as disabled
- if disabled {
- lr.Disabled = true
- lr.Static = true
- lr.Active = false
- lr.ID = fmt.Sprintf("route-%d", time.Now().UnixNano())
- m.staticRoutes = append(m.staticRoutes, lr)
- _ = m.save()
- _ = m.syncRouteGroupToKernel(lr.DstAddress, lr.RoutingTable, lr.Distance)
- return nil
- }
- }
- }
- return fmt.Errorf("route not found")
- }
- func sliceContains(list []string, item string) bool {
- for _, s := range list {
- if s == item {
- return true
- }
- }
- return false
- }
- func normalizeDst(dst string) string {
- dst = strings.TrimSpace(dst)
- if dst == "" || dst == "default" || dst == "0.0.0.0/0" {
- return "default"
- }
- if !strings.Contains(dst, "/") && net.ParseIP(dst) != nil {
- return dst + "/32"
- }
- return dst
- }
- func detectGatewayForInterface(ifaceName string) string {
- link, err := netlink.LinkByName(ifaceName)
- if err == nil {
- routes, err := netlink.RouteList(link, netlink.FAMILY_V4)
- if err == nil {
- for _, r := range routes {
- if (r.Dst == nil || r.Dst.IP.IsUnspecified()) && r.Gw != nil && !r.Gw.IsUnspecified() {
- return r.Gw.String()
- }
- }
- for _, r := range routes {
- if r.Gw != nil && !r.Gw.IsUnspecified() {
- return r.Gw.String()
- }
- }
- }
- }
- out, err := exec.Command("ip", "route", "show", "dev", ifaceName).CombinedOutput()
- if err == nil {
- lines := strings.Split(string(out), "\n")
- for _, l := range lines {
- if strings.Contains(l, "via ") {
- fields := strings.Fields(l)
- for i, f := range fields {
- if f == "via" && i+1 < len(fields) {
- gw := fields[i+1]
- if net.ParseIP(gw) != nil {
- return gw
- }
- }
- }
- }
- }
- }
- return ""
- }
- func (m *RoutingManager) syncRouteGroupToKernel(dstAddress, routingTable string, distance int) error {
- normDst := normalizeDst(dstAddress)
- tbl := strings.TrimSpace(routingTable)
- if tbl == "" {
- tbl = "main"
- }
- var activeRoutes []RouteItem
- for _, r := range m.staticRoutes {
- rDst := normalizeDst(r.DstAddress)
- rTbl := strings.TrimSpace(r.RoutingTable)
- if rTbl == "" {
- rTbl = "main"
- }
- if rDst == normDst && rTbl == tbl && r.Distance == distance {
- if !r.Disabled && r.Active && r.HealthStatus != "offline" {
- activeRoutes = append(activeRoutes, r)
- }
- }
- }
- if len(activeRoutes) == 0 {
- // Safety guard: if all default routes are marked offline, do NOT delete the default route into a blackout!
- // Fallback to keeping all enabled static routes in the group active so recovery traffic and emergency pings can flow.
- if normDst == "default" {
- var fallbackRoutes []RouteItem
- for _, r := range m.staticRoutes {
- rDst := normalizeDst(r.DstAddress)
- rTbl := strings.TrimSpace(r.RoutingTable)
- if rTbl == "" {
- rTbl = "main"
- }
- if rDst == normDst && rTbl == tbl && r.Distance == distance && !r.Disabled {
- fallbackRoutes = append(fallbackRoutes, r)
- }
- }
- if len(fallbackRoutes) > 0 {
- log.Printf("[RouteManager] All default routes offline in group! Keeping fallback routes active to prevent blackout")
- activeRoutes = fallbackRoutes
- }
- }
- }
- if len(activeRoutes) == 0 {
- args := []string{"route", "del", normDst}
- if distance > 0 {
- args = append(args, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- args = append(args, "table", tbl)
- }
- args = append(args, "proto", "static")
- _ = exec.Command("ip", args...).Run()
- // Also delete without proto static in case route protocol differed
- fbArgs := []string{"route", "del", normDst}
- if distance > 0 {
- fbArgs = append(fbArgs, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- fbArgs = append(fbArgs, "table", tbl)
- }
- _ = exec.Command("ip", fbArgs...).Run()
- // Bare fallback
- _ = exec.Command("ip", "route", "del", normDst).Run()
- // Also delete blackhole route variant if it existed
- bhArgs := []string{"route", "del", "blackhole", normDst}
- if distance > 0 {
- bhArgs = append(bhArgs, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- bhArgs = append(bhArgs, "table", tbl)
- }
- _ = exec.Command("ip", bhArgs...).Run()
- return nil
- }
- type expandedNexthop struct {
- Gateway string
- Interface string
- Weight int
- }
- var allNexthops []expandedNexthop
- isBlackhole := false
- for _, r := range activeRoutes {
- gw := strings.TrimSpace(r.Gateway)
- iface := strings.TrimSpace(r.Interface)
- if strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole") {
- isBlackhole = true
- break
- }
- // Check if interface or gateway specifies an SD-WAN virtual group
- targetSDWAN := ""
- if sdwan.IsSDWANGroup(iface) {
- targetSDWAN = iface
- } else if sdwan.IsSDWANGroup(gw) {
- targetSDWAN = gw
- }
- if targetSDWAN != "" {
- resolved, ok := sdwan.ResolveGroupForRouting(targetSDWAN)
- if ok && len(resolved) > 0 {
- for _, nh := range resolved {
- allNexthops = append(allNexthops, expandedNexthop{
- Gateway: nh.Gateway,
- Interface: nh.Interface,
- Weight: nh.Weight,
- })
- }
- continue
- }
- }
- // Standard static route
- if gw != "" && net.ParseIP(gw) == nil && iface == "" {
- iface = gw
- gw = ""
- }
- if gw == "" && iface != "" {
- gw = detectGatewayForInterface(iface)
- }
- allNexthops = append(allNexthops, expandedNexthop{
- Gateway: gw,
- Interface: iface,
- Weight: 1,
- })
- }
- if isBlackhole {
- args := []string{"route", "replace", "blackhole", normDst}
- if distance > 0 {
- args = append(args, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- args = append(args, "table", tbl)
- }
- args = append(args, "proto", "static")
- if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil {
- return fmt.Errorf("failed to apply blackhole route: %s: %w", string(out), err)
- }
- return nil
- }
- if len(allNexthops) == 0 {
- return nil
- }
- if len(allNexthops) == 1 {
- nh := allNexthops[0]
- args := []string{"route", "replace", normDst}
- hasVia := false
- if nh.Gateway != "" && net.ParseIP(nh.Gateway) != nil {
- args = append(args, "via", nh.Gateway)
- hasVia = true
- }
- if nh.Interface != "" {
- args = append(args, "dev", nh.Interface)
- }
- if hasVia && nh.Interface != "" {
- args = append(args, "onlink")
- }
- if distance > 0 {
- args = append(args, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- args = append(args, "table", tbl)
- }
- args = append(args, "proto", "static")
- cmd := exec.Command("ip", args...)
- if out, err := cmd.CombinedOutput(); err != nil {
- if sliceContains(args, "onlink") {
- var noOnlinkArgs []string
- for _, a := range args {
- if a != "onlink" {
- noOnlinkArgs = append(noOnlinkArgs, a)
- }
- }
- if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
- return nil
- }
- }
- return fmt.Errorf("failed to apply route (%s): %s: %w", strings.Join(args, " "), string(out), err)
- }
- return nil
- }
- // Multiple nexthops: ECMP multipath route
- args := []string{"route", "replace", normDst, "scope", "global"}
- if distance > 0 {
- args = append(args, "metric", strconv.Itoa(distance))
- }
- if tbl != "main" {
- args = append(args, "table", tbl)
- }
- args = append(args, "proto", "static")
- for _, nh := range allNexthops {
- args = append(args, "nexthop")
- hasVia := false
- if nh.Gateway != "" && net.ParseIP(nh.Gateway) != nil {
- args = append(args, "via", nh.Gateway)
- hasVia = true
- }
- if nh.Interface != "" {
- args = append(args, "dev", nh.Interface)
- }
- if hasVia && nh.Interface != "" {
- args = append(args, "onlink")
- }
- w := nh.Weight
- if w <= 0 {
- w = 1
- }
- args = append(args, "weight", strconv.Itoa(w))
- }
- cmd := exec.Command("ip", args...)
- if out, err := cmd.CombinedOutput(); err != nil {
- if sliceContains(args, "onlink") {
- var noOnlinkArgs []string
- for _, a := range args {
- if a != "onlink" {
- noOnlinkArgs = append(noOnlinkArgs, a)
- }
- }
- if _, fbErr := exec.Command("ip", noOnlinkArgs...).CombinedOutput(); fbErr == nil {
- return nil
- }
- }
- return fmt.Errorf("failed to apply multipath route (%s): %s: %w", strings.Join(args, " "), string(out), err)
- }
- return nil
- }
- // SyncSDWANRoutes reapplies kernel routes for static routes referencing SD-WAN groups when group state changes.
- func (m *RoutingManager) SyncSDWANRoutes() {
- m.mu.Lock()
- defer m.mu.Unlock()
- type groupKey struct {
- dst string
- table string
- dist int
- }
- seen := make(map[groupKey]bool)
- var groupsToSync []groupKey
- for _, r := range m.staticRoutes {
- if r.Disabled {
- continue
- }
- if sdwan.IsSDWANGroup(r.Interface) || sdwan.IsSDWANGroup(r.Gateway) {
- tbl := strings.TrimSpace(r.RoutingTable)
- if tbl == "" {
- tbl = "main"
- }
- normDst := normalizeDst(r.DstAddress)
- k := groupKey{dst: normDst, table: tbl, dist: r.Distance}
- if !seen[k] {
- seen[k] = true
- groupsToSync = append(groupsToSync, groupKey{dst: r.DstAddress, table: tbl, dist: r.Distance})
- }
- }
- }
- for _, g := range groupsToSync {
- if err := m.syncRouteGroupToKernel(g.dst, g.table, g.dist); err != nil {
- log.Printf("[RouteManager] SD-WAN failover route sync failed for %s (%s metric %d): %v", g.dst, g.table, g.dist, err)
- } else {
- log.Printf("[RouteManager] SD-WAN failover synced route %s (%s metric %d) successfully", g.dst, g.table, g.dist)
- }
- }
- }
- func (m *RoutingManager) applyRouteToKernel(r RouteItem) error {
- return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
- }
- func (m *RoutingManager) removeRouteFromKernel(r RouteItem) error {
- return m.syncRouteGroupToKernel(r.DstAddress, r.RoutingTable, r.Distance)
- }
- func (m *RoutingManager) deleteDirectKernelRoute(r RouteItem) error {
- normDst := normalizeDst(r.DstAddress)
- gw := strings.TrimSpace(r.Gateway)
- isBlackhole := strings.EqualFold(gw, "blackhole") || strings.EqualFold(r.Action, "blackhole")
- var args []string
- if isBlackhole {
- args = []string{"route", "del", "blackhole", normDst}
- } else {
- args = []string{"route", "del", normDst}
- if gw != "" && net.ParseIP(gw) != nil {
- args = append(args, "via", gw)
- }
- iface := strings.TrimSpace(r.Interface)
- if iface != "" {
- args = append(args, "dev", iface)
- }
- }
- if r.RoutingTable != "" && r.RoutingTable != "main" {
- args = append(args, "table", r.RoutingTable)
- }
- if r.Distance > 0 {
- args = append(args, "metric", strconv.Itoa(r.Distance))
- }
- cmd := exec.Command("ip", args...)
- if out, err := cmd.CombinedOutput(); err == nil {
- return nil
- } else {
- log.Printf("[RouteManager] direct ip route del (%s): %s (%v), attempting fallback", strings.Join(args, " "), string(out), err)
- }
- if isBlackhole {
- fbBhArgs := []string{"route", "del", "blackhole", normDst}
- if r.RoutingTable != "" && r.RoutingTable != "main" {
- fbBhArgs = append(fbBhArgs, "table", r.RoutingTable)
- }
- if r.Distance > 0 {
- fbBhArgs = append(fbBhArgs, "metric", strconv.Itoa(r.Distance))
- }
- if err := exec.Command("ip", fbBhArgs...).Run(); err == nil {
- return nil
- }
- return exec.Command("ip", "route", "del", "blackhole", normDst).Run()
- }
- fbArgs := []string{"route", "del", normDst}
- if r.RoutingTable != "" && r.RoutingTable != "main" {
- fbArgs = append(fbArgs, "table", r.RoutingTable)
- }
- if r.Distance > 0 {
- fbArgs = append(fbArgs, "metric", strconv.Itoa(r.Distance))
- }
- if err := exec.Command("ip", fbArgs...).Run(); err == nil {
- return nil
- }
- return exec.Command("ip", "route", "del", normDst).Run()
- }
- // ==================== Policy Rules (/ip route rule) ====================
- func (m *RoutingManager) ListPolicyRules() []PolicyRuleItem {
- m.mu.Lock()
- defer m.mu.Unlock()
- // Query live rules from kernel
- rules, err := netlink.RuleList(netlink.FAMILY_V4)
- if err != nil {
- return m.policyRules
- }
- tableNames := m.getTableMap()
- var res []PolicyRuleItem
- userRulesByPrio := make(map[int]PolicyRuleItem)
- for _, pr := range m.policyRules {
- userRulesByPrio[pr.Priority] = pr
- }
- for _, r := range rules {
- tableName := "main"
- if name, ok := tableNames[r.Table]; ok {
- tableName = name
- } else if r.Table != 254 && r.Table != 0 {
- tableName = strconv.Itoa(r.Table)
- }
- src := ""
- if r.Src != nil {
- src = r.Src.String()
- }
- dst := ""
- if r.Dst != nil {
- dst = r.Dst.String()
- }
- markStr := ""
- if r.Mark > 0 {
- markStr = fmt.Sprintf("0x%x (%d)", r.Mark, r.Mark)
- }
- id := fmt.Sprintf("rule-%d-%d", r.Priority, r.Table)
- comment := ""
- isDefault := false
- isSystem := false
- if r.Priority == 0 || r.Priority == 32766 || r.Priority == 32767 {
- isDefault = true
- isSystem = true
- } else if userRule, ok := userRulesByPrio[r.Priority]; ok {
- if userRule.ID != "" {
- id = userRule.ID
- }
- comment = userRule.Comment
- isDefault = false
- isSystem = false
- } else {
- // System/daemon rule not added by user in debtik (e.g. WireGuard, IPsec)
- isSystem = true
- }
- res = append(res, PolicyRuleItem{
- ID: id,
- Priority: r.Priority,
- SrcAddress: src,
- DstAddress: dst,
- RoutingMark: markStr,
- Table: tableName,
- TableID: r.Table,
- Action: "lookup",
- Comment: comment,
- IsDefault: isDefault,
- IsSystem: isSystem,
- })
- }
- return res
- }
- func (m *RoutingManager) SavePolicyRule(pr PolicyRuleItem) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if pr.Table == "" {
- pr.Table = "main"
- }
- if pr.ID == "" {
- pr.ID = fmt.Sprintf("prule-%d", time.Now().UnixNano())
- }
- if pr.Priority == 0 {
- pr.Priority = 1000 + len(m.policyRules)*10
- }
- if err := m.applyRuleToKernel(pr); err != nil {
- return err
- }
- m.policyRules = append(m.policyRules, pr)
- return m.save()
- }
- func (m *RoutingManager) DeletePolicyRule(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- var updated []PolicyRuleItem
- var target *PolicyRuleItem
- for _, pr := range m.policyRules {
- if pr.ID == id || fmt.Sprintf("rule-%d-%d", pr.Priority, pr.TableID) == id {
- target = &pr
- } else {
- updated = append(updated, pr)
- }
- }
- if target != nil {
- _ = m.removeRuleFromKernel(*target)
- } else if strings.HasPrefix(id, "rule-") {
- parts := strings.Split(id, "-")
- if len(parts) >= 2 {
- if prio, err := strconv.Atoi(parts[1]); err == nil && prio > 0 {
- _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(prio)).Run()
- }
- }
- }
- m.policyRules = updated
- return m.save()
- }
- func (m *RoutingManager) applyRuleToKernel(pr PolicyRuleItem) error {
- args := []string{"rule", "add"}
- if pr.Priority > 0 {
- args = append(args, "pref", strconv.Itoa(pr.Priority))
- }
- if pr.SrcAddress != "" {
- args = append(args, "from", pr.SrcAddress)
- }
- if pr.DstAddress != "" {
- args = append(args, "to", pr.DstAddress)
- }
- if pr.RoutingMark != "" {
- // Clean mark string if it has (hex)
- markClean := pr.RoutingMark
- if strings.Contains(markClean, "(") {
- markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
- }
- args = append(args, "fwmark", markClean)
- }
- if pr.Table != "" {
- args = append(args, "lookup", pr.Table)
- }
- cmd := exec.Command("ip", args...)
- out, err := cmd.CombinedOutput()
- if err != nil {
- return fmt.Errorf("failed to add rule (%s): %s: %w", strings.Join(args, " "), string(out), err)
- }
- return nil
- }
- func (m *RoutingManager) removeRuleFromKernel(pr PolicyRuleItem) error {
- if pr.Priority > 0 {
- _ = exec.Command("ip", "rule", "del", "pref", strconv.Itoa(pr.Priority)).Run()
- return nil
- }
- args := []string{"rule", "del"}
- if pr.RoutingMark != "" {
- markClean := pr.RoutingMark
- if strings.Contains(markClean, "(") {
- markClean = strings.TrimSpace(markClean[:strings.Index(markClean, "(")])
- }
- args = append(args, "fwmark", markClean)
- }
- if pr.Table != "" {
- args = append(args, "lookup", pr.Table)
- }
- _ = exec.Command("ip", args...).Run()
- return nil
- }
- // ==================== Routing Tables ====================
- func (m *RoutingManager) ListTables() []RoutingTableItem {
- m.mu.Lock()
- defer m.mu.Unlock()
- tables := []RoutingTableItem{
- {Name: "main", TableID: 254, Comment: "Default system routing table"},
- {Name: "default", TableID: 253, Comment: "Default fallback table"},
- {Name: "local", TableID: 255, Comment: "Local kernel device table"},
- }
- tables = append(tables, m.customTables...)
- return tables
- }
- func (m *RoutingManager) SaveTable(t RoutingTableItem) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if t.Name == "" {
- return fmt.Errorf("table name is required")
- }
- if t.TableID == 0 {
- // Auto assign FIB ID starting at 100
- t.TableID = 100 + len(m.customTables)
- }
- for _, existing := range m.customTables {
- if existing.Name == t.Name || existing.TableID == t.TableID {
- return fmt.Errorf("table with name %q or ID %d already exists", t.Name, t.TableID)
- }
- }
- m.customTables = append(m.customTables, t)
- _ = m.save()
- m.syncCustomTablesToSystem()
- return nil
- }
- func (m *RoutingManager) getTableMap() map[int]string {
- tableMap := map[int]string{
- 254: "main",
- 253: "default",
- 255: "local",
- }
- // Read /etc/iproute2/rt_tables
- if f, err := os.Open(RTTableFilePath); err == nil {
- defer f.Close()
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- parts := strings.Fields(line)
- if len(parts) >= 2 {
- if id, err := strconv.Atoi(parts[0]); err == nil {
- tableMap[id] = parts[1]
- }
- }
- }
- }
- for _, t := range m.customTables {
- tableMap[t.TableID] = t.Name
- }
- return tableMap
- }
- func (m *RoutingManager) Stop() {
- if m.stopChan != nil {
- select {
- case <-m.stopChan:
- default:
- close(m.stopChan)
- }
- }
- }
- // RenameInterface updates static routes and policy rules when an interface is renamed.
- func (m *RoutingManager) RenameInterface(oldName, newName string) {
- m.mu.Lock()
- defer m.mu.Unlock()
- changed := false
- for i := range m.staticRoutes {
- if m.staticRoutes[i].Interface == oldName {
- m.staticRoutes[i].Interface = newName
- changed = true
- }
- if m.staticRoutes[i].Gateway == oldName {
- m.staticRoutes[i].Gateway = newName
- changed = true
- }
- }
- if changed {
- _ = m.save()
- }
- }
|