manager.go 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927
  1. package dynamicrouting
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. defaultConfigPath = "/etc/debtik/routing/dynamic.json"
  20. birdConfigPath = "/etc/bird/bird.conf"
  21. )
  22. type Manager struct {
  23. mu sync.RWMutex
  24. configPath string
  25. birdConfigPath string
  26. config DynamicConfig
  27. }
  28. func (m *Manager) getBirdConfigPath() string {
  29. if m.birdConfigPath != "" {
  30. return m.birdConfigPath
  31. }
  32. if m.configPath != "" && m.configPath != defaultConfigPath {
  33. return filepath.Join(filepath.Dir(m.configPath), "bird.conf")
  34. }
  35. return birdConfigPath
  36. }
  37. func NewManager(configPath string) *Manager {
  38. if configPath == "" {
  39. configPath = defaultConfigPath
  40. }
  41. m := &Manager{
  42. configPath: configPath,
  43. }
  44. if err := m.load(); err != nil {
  45. log.Printf("[DynamicRouting] Config load warning: %v, initializing defaults", err)
  46. m.initDefaults()
  47. _ = m.save()
  48. }
  49. // Apply initial configuration to BIRD 2
  50. if err := m.applyBirdConfig(); err != nil {
  51. log.Printf("[DynamicRouting] Initial BIRD apply warning: %v", err)
  52. }
  53. return m
  54. }
  55. func (m *Manager) initDefaults() {
  56. m.config = DynamicConfig{
  57. BGPInstance: BGPInstance{
  58. Enabled: false,
  59. AS: 65001,
  60. RouterID: "192.168.131.56",
  61. HoldTime: 180,
  62. KeepaliveTime: 60,
  63. RedistributeConnected: false,
  64. RedistributeStatic: false,
  65. RedistributeOSPF: false,
  66. },
  67. BGPPeers: []BGPPeer{},
  68. BGPNetworks: []BGPNetwork{},
  69. OSPFInstances: []OSPFInstance{
  70. {
  71. ID: "ospf-inst-default",
  72. Name: "Default",
  73. Version: 2,
  74. VRF: "main",
  75. RouterID: "192.168.131.56",
  76. RoutingTable: "main",
  77. Enabled: true,
  78. },
  79. },
  80. OSPFInstance: OSPFInstance{
  81. Name: "Default",
  82. Version: 2,
  83. VRF: "main",
  84. Enabled: true,
  85. RouterID: "192.168.131.56",
  86. RedistributeConnected: false,
  87. RedistributeStatic: true,
  88. RedistributeBGP: false,
  89. RedistributeDefault: false,
  90. OriginateDefault: "never",
  91. DefaultMetric: 10,
  92. },
  93. OSPFAreas: []OSPFArea{
  94. {
  95. ID: "area-default",
  96. Name: "Default",
  97. Instance: "Default",
  98. AreaID: "0.0.0.0",
  99. AreaType: "default",
  100. },
  101. },
  102. OSPFAreaRanges: []OSPFAreaRange{},
  103. OSPFInterfaces: []OSPFInterface{},
  104. OSPFStaticNbrs: []OSPFStaticNeighbor{},
  105. RIPInstances: []RIPInstance{},
  106. RIPInterfaces: []RIPInterface{},
  107. RIPNeighbors: []RIPNeighbor{},
  108. BFDInstance: BFDInstance{Enabled: false},
  109. BFDInterfaces: []BFDInterface{},
  110. BFDNeighbors: []BFDNeighbor{},
  111. BabelInstances: []BabelInstance{},
  112. BabelInterfaces: []BabelInterface{},
  113. RAdvInstances: []RAdvInstance{},
  114. RAdvInterfaces: []RAdvInterface{},
  115. EIGRPInstances: []EIGRPInstance{},
  116. EIGRPInterfaces: []EIGRPInterface{},
  117. EIGRPNetworks: []EIGRPNetwork{},
  118. RoutingFilters: []RoutingFilterRule{},
  119. RoutingCommunityLists: []RoutingFilterCommunityList{},
  120. RoutingASLists: []RoutingFilterASList{},
  121. }
  122. }
  123. func (m *Manager) load() error {
  124. m.mu.Lock()
  125. defer m.mu.Unlock()
  126. data, err := os.ReadFile(m.configPath)
  127. if err != nil {
  128. return err
  129. }
  130. if err := json.Unmarshal(data, &m.config); err != nil {
  131. return err
  132. }
  133. if m.config.RoutingCommunityLists == nil {
  134. m.config.RoutingCommunityLists = []RoutingFilterCommunityList{}
  135. }
  136. if m.config.RoutingASLists == nil {
  137. m.config.RoutingASLists = []RoutingFilterASList{}
  138. }
  139. if m.config.RIPInstances == nil {
  140. m.config.RIPInstances = []RIPInstance{}
  141. }
  142. if m.config.RIPInterfaces == nil {
  143. m.config.RIPInterfaces = []RIPInterface{}
  144. }
  145. if m.config.RIPNeighbors == nil {
  146. m.config.RIPNeighbors = []RIPNeighbor{}
  147. }
  148. if m.config.BFDInterfaces == nil {
  149. m.config.BFDInterfaces = []BFDInterface{}
  150. }
  151. if m.config.BFDNeighbors == nil {
  152. m.config.BFDNeighbors = []BFDNeighbor{}
  153. }
  154. if m.config.BabelInstances == nil {
  155. m.config.BabelInstances = []BabelInstance{}
  156. }
  157. if m.config.BabelInterfaces == nil {
  158. m.config.BabelInterfaces = []BabelInterface{}
  159. }
  160. if m.config.RAdvInstances == nil {
  161. m.config.RAdvInstances = []RAdvInstance{}
  162. }
  163. if m.config.RAdvInterfaces == nil {
  164. m.config.RAdvInterfaces = []RAdvInterface{}
  165. }
  166. if m.config.EIGRPInstances == nil {
  167. m.config.EIGRPInstances = []EIGRPInstance{}
  168. }
  169. if m.config.EIGRPInterfaces == nil {
  170. m.config.EIGRPInterfaces = []EIGRPInterface{}
  171. }
  172. if m.config.EIGRPNetworks == nil {
  173. m.config.EIGRPNetworks = []EIGRPNetwork{}
  174. }
  175. if len(m.config.OSPFInstances) == 0 {
  176. rID := m.config.OSPFInstance.RouterID
  177. if rID == "" {
  178. rID = "192.168.131.56"
  179. }
  180. m.config.OSPFInstances = []OSPFInstance{
  181. {
  182. ID: "ospf-inst-default",
  183. Name: "Default",
  184. Version: 2,
  185. VRF: "main",
  186. RouterID: rID,
  187. RoutingTable: "main",
  188. Enabled: true,
  189. },
  190. }
  191. }
  192. if len(m.config.OSPFAreas) == 0 {
  193. m.config.OSPFAreas = []OSPFArea{
  194. {
  195. ID: "area-default",
  196. Name: "Default",
  197. Instance: "Default",
  198. AreaID: "0.0.0.0",
  199. AreaType: "default",
  200. },
  201. }
  202. }
  203. return nil
  204. }
  205. func (m *Manager) save() error {
  206. dir := filepath.Dir(m.configPath)
  207. if err := os.MkdirAll(dir, 0755); err != nil {
  208. return err
  209. }
  210. data, err := json.MarshalIndent(m.config, "", " ")
  211. if err != nil {
  212. return err
  213. }
  214. f, err := os.CreateTemp(dir, ".dynamic-*.tmp")
  215. if err != nil {
  216. return err
  217. }
  218. name := f.Name()
  219. defer os.Remove(name)
  220. if err = f.Chmod(0644); err == nil {
  221. _, err = f.Write(data)
  222. }
  223. if err == nil {
  224. err = f.Sync()
  225. }
  226. if closeErr := f.Close(); err == nil {
  227. err = closeErr
  228. }
  229. if err != nil {
  230. return err
  231. }
  232. return os.Rename(name, m.configPath)
  233. }
  234. // sanitizeIdentifier creates a valid BIRD protocol/function identifier: [a-zA-Z][a-zA-Z0-9_]*
  235. func sanitizeIdentifier(prefix, raw string) string {
  236. reg := regexp.MustCompile("[^a-zA-Z0-9_]+")
  237. cleaned := reg.ReplaceAllString(raw, "_")
  238. cleaned = strings.Trim(cleaned, "_")
  239. if cleaned == "" {
  240. cleaned = "inst"
  241. }
  242. res := cleaned
  243. if prefix != "" {
  244. res = prefix + "_" + cleaned
  245. }
  246. if len(res) > 32 {
  247. res = res[:32]
  248. }
  249. return res
  250. }
  251. // formatInterfaceTargets formats interface names and network prefixes for BIRD 2 interface pattern
  252. func formatInterfaceTargets(ifaceNames, netPrefixes string) string {
  253. var targets []string
  254. if ifaceNames != "" {
  255. for _, raw := range strings.Split(ifaceNames, ",") {
  256. item := strings.TrimSpace(raw)
  257. if item != "" {
  258. if item == "*" {
  259. targets = append(targets, "\"*\"")
  260. } else if strings.HasPrefix(item, "\"") && strings.HasSuffix(item, "\"") {
  261. targets = append(targets, item)
  262. } else {
  263. targets = append(targets, fmt.Sprintf("%q", item))
  264. }
  265. }
  266. }
  267. }
  268. if netPrefixes != "" {
  269. for _, raw := range strings.Split(netPrefixes, ",") {
  270. item := strings.TrimSpace(raw)
  271. if item != "" {
  272. targets = append(targets, item)
  273. }
  274. }
  275. }
  276. if len(targets) == 0 {
  277. return "\"*\""
  278. }
  279. return strings.Join(targets, ", ")
  280. }
  281. // ipInSubnets returns true if ipStr is contained in any comma-separated subnet in networksStr
  282. func ipInSubnets(ipStr, networksStr string) bool {
  283. ip := net.ParseIP(strings.TrimSpace(ipStr))
  284. if ip == nil {
  285. return false
  286. }
  287. for _, raw := range strings.Split(networksStr, ",") {
  288. cidr := strings.TrimSpace(raw)
  289. if cidr == "" {
  290. continue
  291. }
  292. _, ipNet, err := net.ParseCIDR(cidr)
  293. if err == nil && ipNet.Contains(ip) {
  294. return true
  295. }
  296. }
  297. return false
  298. }
  299. // generateBirdConfig creates candidate bird.conf text from current configuration
  300. func (m *Manager) generateBirdConfig() string {
  301. var sb strings.Builder
  302. routerID := "192.168.131.56"
  303. if m.config.BGPInstance.RouterID != "" {
  304. routerID = m.config.BGPInstance.RouterID
  305. } else if m.config.OSPFInstance.RouterID != "" {
  306. routerID = m.config.OSPFInstance.RouterID
  307. }
  308. sb.WriteString("# /etc/bird/bird.conf\n")
  309. sb.WriteString("# Generated dynamically by DebTik (BIRD 2 Engine)\n\n")
  310. sb.WriteString("timeformat protocol iso long;\n")
  311. sb.WriteString("timeformat base iso long;\n")
  312. sb.WriteString("timeformat log iso long;\n")
  313. sb.WriteString("log syslog all;\n")
  314. sb.WriteString(fmt.Sprintf("router id %s;\n\n", routerID))
  315. // Base system protocols
  316. sb.WriteString("protocol device {\n")
  317. sb.WriteString(" scan time 10;\n")
  318. sb.WriteString("}\n\n")
  319. sb.WriteString("protocol direct {\n")
  320. sb.WriteString(" ipv4;\n")
  321. sb.WriteString("}\n\n")
  322. sb.WriteString("protocol kernel {\n")
  323. sb.WriteString(" metric 0;\n")
  324. sb.WriteString(" ipv4 {\n")
  325. sb.WriteString(" export filter {\n")
  326. sb.WriteString(" if proto ~ \"ospf_def_*\" then reject;\n")
  327. sb.WriteString(" if source = RTS_DEVICE then reject;\n")
  328. sb.WriteString(" if source = RTS_BGP then {\n")
  329. sb.WriteString(" if bgp_path.first = bgp_path.last && bgp_path.len = 0 then\n")
  330. sb.WriteString(" krt_metric = 200;\n")
  331. sb.WriteString(" else\n")
  332. sb.WriteString(" krt_metric = 20;\n")
  333. sb.WriteString(" }\n")
  334. sb.WriteString(" if source = RTS_OSPF then {\n")
  335. sb.WriteString(" krt_metric = 110;\n")
  336. sb.WriteString(" }\n")
  337. sb.WriteString(" if source = RTS_RIP then {\n")
  338. sb.WriteString(" krt_metric = 120;\n")
  339. sb.WriteString(" }\n")
  340. sb.WriteString(" if source = RTS_BABEL then {\n")
  341. sb.WriteString(" krt_metric = 130;\n")
  342. sb.WriteString(" }\n")
  343. sb.WriteString(" if source ~ [ RTS_STATIC, RTS_INHERIT ] then {\n")
  344. sb.WriteString(" krt_metric = 255;\n")
  345. sb.WriteString(" }\n")
  346. sb.WriteString(" accept;\n")
  347. sb.WriteString(" };\n")
  348. sb.WriteString(" };\n")
  349. sb.WriteString(" learn;\n")
  350. sb.WriteString("}\n\n")
  351. sb.WriteString("protocol kernel {\n")
  352. sb.WriteString(" metric 0;\n")
  353. sb.WriteString(" ipv6 {\n")
  354. sb.WriteString(" import none;\n")
  355. sb.WriteString(" export all;\n")
  356. sb.WriteString(" };\n")
  357. sb.WriteString(" learn;\n")
  358. sb.WriteString("}\n\n")
  359. // Static BGP Networks announcements
  360. var activeNets []string
  361. if m.config.BGPInstance.Enabled {
  362. for _, net := range m.config.BGPNetworks {
  363. if !net.Disabled && strings.TrimSpace(net.Network) != "" {
  364. activeNets = append(activeNets, strings.TrimSpace(net.Network))
  365. }
  366. }
  367. }
  368. if len(activeNets) > 0 {
  369. sb.WriteString("protocol static bgp_static_nets {\n")
  370. sb.WriteString(" ipv4;\n")
  371. for _, n := range activeNets {
  372. sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", n))
  373. }
  374. sb.WriteString("}\n\n")
  375. }
  376. // Community Lists (/routing filter community-list)
  377. for _, cl := range m.config.RoutingCommunityLists {
  378. if cl.Disabled || strings.TrimSpace(cl.Name) == "" || len(cl.Communities) == 0 {
  379. continue
  380. }
  381. var items []string
  382. for _, c := range cl.Communities {
  383. c = strings.TrimSpace(c)
  384. if strings.Contains(c, ":") {
  385. parts := strings.Split(c, ":")
  386. items = append(items, fmt.Sprintf("(%s, %s)", strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
  387. }
  388. }
  389. if len(items) > 0 {
  390. sb.WriteString(fmt.Sprintf("define comm_%s = [ %s ];\n", sanitizeIdentifier("", cl.Name), strings.Join(items, ", ")))
  391. }
  392. }
  393. // AS Lists (/routing filter num-list)
  394. for _, al := range m.config.RoutingASLists {
  395. if al.Disabled || strings.TrimSpace(al.Name) == "" || strings.TrimSpace(al.Range) == "" {
  396. continue
  397. }
  398. rng := strings.TrimSpace(al.Range)
  399. rng = regexp.MustCompile(`(\d+)\s*-\s*(\d+)`).ReplaceAllString(rng, "$1..$2")
  400. sb.WriteString(fmt.Sprintf("define aslist_%s = [ %s ];\n", sanitizeIdentifier("", al.Name), rng))
  401. }
  402. sb.WriteString("\n")
  403. // Routing Filters (/routing filter)
  404. chainRules := make(map[string][]RoutingFilterRule)
  405. for _, rule := range m.config.RoutingFilters {
  406. if rule.Disabled || strings.TrimSpace(rule.Chain) == "" {
  407. continue
  408. }
  409. chain := strings.TrimSpace(rule.Chain)
  410. chainRules[chain] = append(chainRules[chain], rule)
  411. }
  412. for chain, rules := range chainRules {
  413. sort.Slice(rules, func(i, j int) bool {
  414. return rules[i].RuleOrder < rules[j].RuleOrder
  415. })
  416. filterName := sanitizeIdentifier("filter", chain)
  417. fnName := fmt.Sprintf("fn_%s", filterName)
  418. // Procedural function for this chain
  419. sb.WriteString(fmt.Sprintf("function %s() {\n", fnName))
  420. for _, r := range rules {
  421. rendered := translateRos7RuleToBird(&r)
  422. if rendered != "" {
  423. sb.WriteString(fmt.Sprintf(" # rule %d\n", r.RuleOrder))
  424. lines := strings.Split(rendered, "\n")
  425. for _, l := range lines {
  426. if strings.TrimSpace(l) != "" {
  427. sb.WriteString(" " + l + "\n")
  428. }
  429. }
  430. }
  431. }
  432. sb.WriteString("}\n\n")
  433. // Standalone filter for import and general use (unmatched routes rejected by default)
  434. sb.WriteString(fmt.Sprintf("filter %s {\n", filterName))
  435. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  436. sb.WriteString(" reject;\n")
  437. sb.WriteString("}\n\n")
  438. }
  439. // BGP Protocols (True Multi-Instance / Multi-AS support!)
  440. if m.config.BGPInstance.Enabled {
  441. for i, peer := range m.config.BGPPeers {
  442. if peer.RemoteAddress == "" || peer.RemoteAS == 0 {
  443. continue
  444. }
  445. // Local AS determination: peer.LocalAS if set, otherwise global AS
  446. localAS := m.config.BGPInstance.AS
  447. if peer.LocalAS > 0 {
  448. localAS = peer.LocalAS
  449. }
  450. protoName := sanitizeIdentifier("bgp", fmt.Sprintf("%s_%d", peer.ID, i))
  451. // Per-peer Output Networks (RouterOS v7 output.network)
  452. var peerNets []string
  453. for _, on := range peer.OutputNetworks {
  454. on = strings.TrimSpace(on)
  455. if on != "" {
  456. peerNets = append(peerNets, on)
  457. }
  458. }
  459. if peer.DefaultOriginate {
  460. peerNets = append(peerNets, "0.0.0.0/0")
  461. }
  462. peerNetsProto := ""
  463. if len(peerNets) > 0 {
  464. peerNetsProto = fmt.Sprintf("bgp_nets_%s", protoName)
  465. sb.WriteString(fmt.Sprintf("protocol static %s {\n", peerNetsProto))
  466. sb.WriteString(" ipv4;\n")
  467. for _, pn := range peerNets {
  468. sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", pn))
  469. }
  470. sb.WriteString("}\n\n")
  471. }
  472. sb.WriteString(fmt.Sprintf("protocol bgp %s {\n", protoName))
  473. if peer.Name != "" {
  474. sb.WriteString(fmt.Sprintf(" description \"%s\";\n", peer.Name))
  475. }
  476. if peer.Disabled {
  477. sb.WriteString(" disabled;\n")
  478. }
  479. if peer.LocalAddress != "" {
  480. if peer.LocalPort > 0 {
  481. sb.WriteString(fmt.Sprintf(" local %s port %d as %d;\n", peer.LocalAddress, peer.LocalPort, localAS))
  482. } else {
  483. sb.WriteString(fmt.Sprintf(" local %s as %d;\n", peer.LocalAddress, localAS))
  484. }
  485. } else {
  486. if peer.LocalPort > 0 {
  487. sb.WriteString(fmt.Sprintf(" local port %d as %d;\n", peer.LocalPort, localAS))
  488. } else {
  489. sb.WriteString(fmt.Sprintf(" local as %d;\n", localAS))
  490. }
  491. }
  492. if peer.RemotePort > 0 {
  493. sb.WriteString(fmt.Sprintf(" neighbor %s port %d as %d;\n", peer.RemoteAddress, peer.RemotePort, peer.RemoteAS))
  494. } else {
  495. sb.WriteString(fmt.Sprintf(" neighbor %s as %d;\n", peer.RemoteAddress, peer.RemoteAS))
  496. }
  497. if peer.Multihop {
  498. sb.WriteString(" multihop;\n")
  499. }
  500. if peer.Passive || (!peer.Connect && peer.Listen) {
  501. sb.WriteString(" passive;\n")
  502. }
  503. if peer.Password != "" {
  504. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", peer.Password))
  505. }
  506. holdTime := 180
  507. if peer.HoldTime > 0 {
  508. holdTime = peer.HoldTime
  509. } else if m.config.BGPInstance.HoldTime > 0 {
  510. holdTime = m.config.BGPInstance.HoldTime
  511. }
  512. sb.WriteString(fmt.Sprintf(" hold time %d;\n", holdTime))
  513. if peer.KeepaliveTime > 0 {
  514. sb.WriteString(fmt.Sprintf(" keepalive time %d;\n", peer.KeepaliveTime))
  515. }
  516. // IPv4 Channel
  517. sb.WriteString(" ipv4 {\n")
  518. if peer.NexthopSelf || peer.NexthopChoice == "force-self" {
  519. sb.WriteString(" next hop self;\n")
  520. }
  521. // Import Filter
  522. defaultAD := 20
  523. if peer.LocalRole == "ibgp" || (localAS > 0 && peer.RemoteAS > 0 && localAS == peer.RemoteAS) {
  524. defaultAD = 200
  525. }
  526. inFilter := peer.InFilter
  527. if inFilter == "" {
  528. inFilter = m.config.BGPInstance.InFilter
  529. }
  530. outFilter := peer.OutFilter
  531. if outFilter == "" {
  532. outFilter = m.config.BGPInstance.OutFilter
  533. }
  534. if inFilter != "" && len(chainRules[inFilter]) > 0 {
  535. sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", inFilter)))
  536. } else {
  537. sb.WriteString(fmt.Sprintf(" import filter { krt_metric = %d; accept; };\n", defaultAD))
  538. }
  539. // Export Filter
  540. if outFilter != "" && len(chainRules[outFilter]) > 0 {
  541. fnName := fmt.Sprintf("fn_%s", sanitizeIdentifier("filter", outFilter))
  542. sb.WriteString(" export filter {\n")
  543. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  544. if peerNetsProto != "" {
  545. sb.WriteString(fmt.Sprintf(" if proto = \"%s\" then accept;\n", peerNetsProto))
  546. }
  547. if len(activeNets) > 0 {
  548. sb.WriteString(" if proto = \"bgp_static_nets\" then accept;\n")
  549. }
  550. if peer.RedistConnected || m.config.BGPInstance.RedistributeConnected {
  551. sb.WriteString(" if source = RTS_DEVICE then accept;\n")
  552. }
  553. if peer.RedistStatic || m.config.BGPInstance.RedistributeStatic {
  554. sb.WriteString(" if source ~ [ RTS_STATIC, RTS_INHERIT ] then accept;\n")
  555. }
  556. if peer.RedistOSPF || m.config.BGPInstance.RedistributeOSPF {
  557. sb.WriteString(" if source = RTS_OSPF then accept;\n")
  558. }
  559. sb.WriteString(" reject;\n")
  560. sb.WriteString(" };\n")
  561. } else {
  562. var exportSources []string
  563. if peerNetsProto != "" {
  564. exportSources = append(exportSources, fmt.Sprintf(`proto = "%s"`, peerNetsProto))
  565. }
  566. if len(activeNets) > 0 {
  567. exportSources = append(exportSources, `proto = "bgp_static_nets"`)
  568. }
  569. exportSources = append(exportSources, `source = RTS_BGP`)
  570. if peer.RedistConnected || m.config.BGPInstance.RedistributeConnected {
  571. exportSources = append(exportSources, `source = RTS_DEVICE`)
  572. }
  573. if peer.RedistStatic || m.config.BGPInstance.RedistributeStatic {
  574. exportSources = append(exportSources, `source ~ [ RTS_STATIC, RTS_INHERIT ]`)
  575. }
  576. if peer.RedistOSPF || m.config.BGPInstance.RedistributeOSPF {
  577. exportSources = append(exportSources, `source = RTS_OSPF`)
  578. }
  579. if len(exportSources) > 0 {
  580. sb.WriteString(fmt.Sprintf(" export where (%s);\n", strings.Join(exportSources, ") || (")))
  581. } else {
  582. sb.WriteString(" export none;\n")
  583. }
  584. }
  585. sb.WriteString(" };\n")
  586. if peer.UseBFD {
  587. sb.WriteString(" bfd yes;\n")
  588. }
  589. sb.WriteString("}\n\n")
  590. }
  591. }
  592. // OSPFv2 Protocols (RouterOS v7 Multi-Instance OSPF)
  593. ospfInstances := m.config.OSPFInstances
  594. if len(ospfInstances) == 0 {
  595. legacy := m.config.OSPFInstance
  596. instRouterID := legacy.RouterID
  597. if instRouterID == "" {
  598. instRouterID = routerID
  599. }
  600. ospfInstances = []OSPFInstance{
  601. {
  602. ID: "ospf-inst-default",
  603. Name: "Default",
  604. Version: 2,
  605. VRF: "main",
  606. RouterID: instRouterID,
  607. RoutingTable: "main",
  608. Enabled: legacy.Enabled,
  609. Disabled: legacy.Disabled,
  610. RedistributeConnected: legacy.RedistributeConnected,
  611. RedistributeStatic: legacy.RedistributeStatic,
  612. RedistributeBGP: legacy.RedistributeBGP,
  613. RedistributeDefault: legacy.RedistributeDefault,
  614. OriginateDefault: legacy.OriginateDefault,
  615. DefaultMetric: legacy.DefaultMetric,
  616. },
  617. }
  618. }
  619. for _, inst := range ospfInstances {
  620. if inst.Disabled {
  621. continue
  622. }
  623. instRouterID := inst.RouterID
  624. if instRouterID == "" {
  625. instRouterID = routerID
  626. }
  627. instProtoName := sanitizeIdentifier("ospf", inst.Name)
  628. // Determine Originate Default mode
  629. origDefault := strings.ToLower(strings.TrimSpace(inst.OriginateDefault))
  630. if inst.RedistributeDefault && (origDefault == "" || origDefault == "never") {
  631. origDefault = "if-installed"
  632. }
  633. if origDefault == "" {
  634. origDefault = "never"
  635. }
  636. defaultMetric := inst.DefaultMetric
  637. if defaultMetric <= 0 {
  638. defaultMetric = 10
  639. }
  640. defProtoName := ""
  641. if origDefault == "always" {
  642. defProtoName = fmt.Sprintf("ospf_def_%s", instProtoName)
  643. sb.WriteString(fmt.Sprintf("protocol static %s {\n", defProtoName))
  644. sb.WriteString(" ipv4;\n")
  645. sb.WriteString(" route 0.0.0.0/0 unreachable;\n")
  646. sb.WriteString("}\n\n")
  647. }
  648. sb.WriteString(fmt.Sprintf("protocol ospf v%d %s {\n", inst.Version, instProtoName))
  649. if inst.VRF != "" && inst.VRF != "main" && inst.VRF != "default" {
  650. sb.WriteString(fmt.Sprintf(" vrf %s;\n", inst.VRF))
  651. }
  652. sb.WriteString(fmt.Sprintf(" router id %s;\n", instRouterID))
  653. sb.WriteString(" ipv4 {\n")
  654. if inst.RoutingTable != "" && inst.RoutingTable != "main" {
  655. sb.WriteString(fmt.Sprintf(" table %s;\n", inst.RoutingTable))
  656. }
  657. if inst.InFilter != "" && len(chainRules[inst.InFilter]) > 0 {
  658. sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", inst.InFilter)))
  659. } else {
  660. sb.WriteString(" import filter { krt_metric = 110; accept; };\n")
  661. }
  662. var ospfExports []string
  663. if inst.RedistributeStatic {
  664. ospfExports = append(ospfExports, "RTS_STATIC", "RTS_INHERIT")
  665. }
  666. if inst.RedistributeConnected {
  667. ospfExports = append(ospfExports, "RTS_DEVICE")
  668. }
  669. if inst.RedistributeBGP {
  670. ospfExports = append(ospfExports, "RTS_BGP")
  671. }
  672. hasDefaultOrig := origDefault == "always" || origDefault == "if-installed"
  673. if inst.OutFilter != "" && len(chainRules[inst.OutFilter]) > 0 {
  674. fnName := fmt.Sprintf("fn_%s", sanitizeIdentifier("filter", inst.OutFilter))
  675. sb.WriteString(" export filter {\n")
  676. if len(ospfExports) > 0 || hasDefaultOrig {
  677. var conds []string
  678. if origDefault == "always" {
  679. conds = append(conds, fmt.Sprintf("proto = \"%s\"", defProtoName))
  680. }
  681. if hasDefaultOrig {
  682. conds = append(conds, "(net = 0.0.0.0/0 && source != RTS_OSPF)")
  683. }
  684. if len(ospfExports) > 0 {
  685. conds = append(conds, fmt.Sprintf("source ~ [ %s ]", strings.Join(ospfExports, ", ")))
  686. }
  687. sb.WriteString(fmt.Sprintf(" if !( %s ) then reject;\n", strings.Join(conds, " || ")))
  688. }
  689. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  690. if origDefault == "always" {
  691. sb.WriteString(fmt.Sprintf(" if proto = \"%s\" || (net = 0.0.0.0/0 && source != RTS_OSPF) then {\n", defProtoName))
  692. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", defaultMetric))
  693. sb.WriteString(" accept;\n")
  694. sb.WriteString(" }\n")
  695. } else if origDefault == "if-installed" {
  696. sb.WriteString(" if net = 0.0.0.0/0 && source != RTS_OSPF then {\n")
  697. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", defaultMetric))
  698. sb.WriteString(" accept;\n")
  699. sb.WriteString(" }\n")
  700. }
  701. if len(ospfExports) > 0 {
  702. sb.WriteString(fmt.Sprintf(" if source ~ [ %s ] then {\n", strings.Join(ospfExports, ", ")))
  703. if inst.DefaultMetric > 0 {
  704. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", inst.DefaultMetric))
  705. }
  706. sb.WriteString(" accept;\n")
  707. sb.WriteString(" }\n")
  708. }
  709. sb.WriteString(" reject;\n")
  710. sb.WriteString(" };\n")
  711. } else if len(ospfExports) > 0 || hasDefaultOrig {
  712. sb.WriteString(" export filter {\n")
  713. if origDefault == "always" {
  714. sb.WriteString(fmt.Sprintf(" if proto = \"%s\" || (net = 0.0.0.0/0 && source != RTS_OSPF) then {\n", defProtoName))
  715. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", defaultMetric))
  716. sb.WriteString(" accept;\n")
  717. sb.WriteString(" }\n")
  718. } else if origDefault == "if-installed" {
  719. sb.WriteString(" if net = 0.0.0.0/0 && source != RTS_OSPF then {\n")
  720. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", defaultMetric))
  721. sb.WriteString(" accept;\n")
  722. sb.WriteString(" }\n")
  723. } else {
  724. sb.WriteString(" if net = 0.0.0.0/0 then reject;\n")
  725. }
  726. if len(ospfExports) > 0 {
  727. sb.WriteString(fmt.Sprintf(" if source ~ [ %s ] then {\n", strings.Join(ospfExports, ", ")))
  728. if inst.DefaultMetric > 0 {
  729. sb.WriteString(fmt.Sprintf(" ospf_metric1 = %d;\n", inst.DefaultMetric))
  730. }
  731. sb.WriteString(" accept;\n")
  732. sb.WriteString(" }\n")
  733. }
  734. sb.WriteString(" reject;\n")
  735. sb.WriteString(" };\n")
  736. } else {
  737. sb.WriteString(" export none;\n")
  738. }
  739. sb.WriteString(" };\n\n")
  740. // Areas for this instance
  741. areas := m.config.OSPFAreas
  742. if len(areas) == 0 {
  743. areas = []OSPFArea{
  744. {
  745. Name: "Default",
  746. Instance: inst.Name,
  747. AreaID: "0.0.0.0",
  748. AreaType: "default",
  749. },
  750. }
  751. }
  752. for _, area := range areas {
  753. if area.Disabled {
  754. continue
  755. }
  756. if area.Instance != "" && !strings.EqualFold(area.Instance, inst.Name) && !strings.EqualFold(area.Instance, "Default") {
  757. continue
  758. }
  759. areaID := strings.TrimSpace(area.AreaID)
  760. if areaID == "" {
  761. areaID = "0.0.0.0"
  762. }
  763. sb.WriteString(fmt.Sprintf(" area %s {\n", areaID))
  764. if area.AreaType == "stub" {
  765. sb.WriteString(" stub;\n")
  766. } else if area.AreaType == "nssa" {
  767. sb.WriteString(" nssa;\n")
  768. }
  769. if area.DefaultCost > 0 {
  770. sb.WriteString(fmt.Sprintf(" default cost %d;\n", area.DefaultCost))
  771. }
  772. if area.NoSummaries {
  773. sb.WriteString(" summary no;\n")
  774. }
  775. // Area ranges (stubnet)
  776. for _, ar := range m.config.OSPFAreaRanges {
  777. if ar.Disabled {
  778. continue
  779. }
  780. if strings.EqualFold(ar.Area, area.Name) || strings.EqualFold(ar.Area, area.AreaID) || ar.Area == "" {
  781. prefix := strings.TrimSpace(ar.Prefix)
  782. if prefix != "" {
  783. var stubnetOpts []string
  784. if ar.Cost > 0 {
  785. stubnetOpts = append(stubnetOpts, fmt.Sprintf("cost %d;", ar.Cost))
  786. }
  787. if !ar.Advertise {
  788. stubnetOpts = append(stubnetOpts, "hidden;")
  789. }
  790. if len(stubnetOpts) > 0 {
  791. sb.WriteString(fmt.Sprintf(" stubnet %s { %s };\n", prefix, strings.Join(stubnetOpts, " ")))
  792. } else {
  793. sb.WriteString(fmt.Sprintf(" stubnet %s;\n", prefix))
  794. }
  795. }
  796. }
  797. }
  798. // Collect active static neighbors for this area
  799. var areaNbrs []OSPFStaticNeighbor
  800. for _, nbr := range m.config.OSPFStaticNbrs {
  801. if nbr.Disabled {
  802. continue
  803. }
  804. if strings.EqualFold(nbr.Area, area.Name) || strings.EqualFold(nbr.Area, area.AreaID) || (nbr.Area == "" && (strings.EqualFold(area.Name, "Default") || area.AreaID == "0.0.0.0")) {
  805. areaNbrs = append(areaNbrs, nbr)
  806. }
  807. }
  808. usedNbrIDs := make(map[string]bool)
  809. // Interface templates matching this area
  810. hasAreaTemplate := false
  811. for _, iface := range m.config.OSPFInterfaces {
  812. if iface.Disabled {
  813. continue
  814. }
  815. if iface.Area != "" && !strings.EqualFold(iface.Area, area.Name) && !strings.EqualFold(iface.Area, area.AreaID) && iface.Area != "Default" {
  816. continue
  817. }
  818. hasAreaTemplate = true
  819. ifaceName := strings.TrimSpace(iface.Interfaces)
  820. if ifaceName == "" {
  821. ifaceName = strings.TrimSpace(iface.Interface)
  822. }
  823. netName := strings.TrimSpace(iface.Networks)
  824. if netName == "" {
  825. netName = strings.TrimSpace(iface.Network)
  826. }
  827. target := formatInterfaceTargets(ifaceName, netName)
  828. sb.WriteString(fmt.Sprintf(" interface %s {\n", target))
  829. if iface.Cost > 0 {
  830. sb.WriteString(fmt.Sprintf(" cost %d;\n", iface.Cost))
  831. }
  832. if iface.Priority > 0 {
  833. sb.WriteString(fmt.Sprintf(" priority %d;\n", iface.Priority))
  834. }
  835. if iface.HelloInterval > 0 {
  836. sb.WriteString(fmt.Sprintf(" hello %d;\n", iface.HelloInterval))
  837. }
  838. if iface.DeadInterval > 0 {
  839. sb.WriteString(fmt.Sprintf(" dead %d;\n", iface.DeadInterval))
  840. }
  841. netType := strings.ToLower(strings.TrimSpace(iface.NetworkType))
  842. if iface.Passive {
  843. sb.WriteString(" stub;\n")
  844. } else {
  845. switch netType {
  846. case "ptp", "point-to-point":
  847. sb.WriteString(" type ptp;\n")
  848. case "nbma", "nonbroadcast":
  849. sb.WriteString(" type nonbroadcast;\n")
  850. case "ptmp", "point-to-multipoint":
  851. sb.WriteString(" type ptmp;\n")
  852. default:
  853. sb.WriteString(" type bcast;\n")
  854. }
  855. }
  856. auth := strings.ToLower(iface.Auth)
  857. if auth == "" {
  858. auth = strings.ToLower(iface.AuthType)
  859. }
  860. if (auth == "md5" || auth == "cryptographic") && iface.AuthKey != "" {
  861. sb.WriteString(" authentication cryptographic;\n")
  862. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  863. } else if auth == "simple" && iface.AuthKey != "" {
  864. sb.WriteString(" authentication simple;\n")
  865. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  866. }
  867. if iface.UseBFD {
  868. sb.WriteString(" bfd yes;\n")
  869. }
  870. // Find static neighbors matching this interface template
  871. var templateNbrs []OSPFStaticNeighbor
  872. for _, nbr := range areaNbrs {
  873. if usedNbrIDs[nbr.ID] {
  874. continue
  875. }
  876. if netName != "" && ipInSubnets(nbr.Address, netName) {
  877. templateNbrs = append(templateNbrs, nbr)
  878. usedNbrIDs[nbr.ID] = true
  879. }
  880. }
  881. if len(templateNbrs) == 0 && (strings.Contains(netType, "nbma") || strings.Contains(netType, "nonbroadcast") || strings.Contains(netType, "ptmp")) {
  882. for _, nbr := range areaNbrs {
  883. if !usedNbrIDs[nbr.ID] {
  884. templateNbrs = append(templateNbrs, nbr)
  885. usedNbrIDs[nbr.ID] = true
  886. }
  887. }
  888. }
  889. if len(templateNbrs) > 0 {
  890. for _, nbr := range templateNbrs {
  891. if nbr.PollInterval > 0 {
  892. sb.WriteString(fmt.Sprintf(" poll %d;\n", nbr.PollInterval))
  893. break
  894. }
  895. }
  896. sb.WriteString(" neighbors {\n")
  897. for _, nbr := range templateNbrs {
  898. addr := strings.TrimSpace(nbr.Address)
  899. if addr != "" {
  900. sb.WriteString(fmt.Sprintf(" %s;\n", addr))
  901. }
  902. }
  903. sb.WriteString(" };\n")
  904. }
  905. sb.WriteString(" };\n")
  906. }
  907. // Any remaining static neighbors in this area not matched to a template
  908. var remainingNbrs []OSPFStaticNeighbor
  909. for _, nbr := range areaNbrs {
  910. if !usedNbrIDs[nbr.ID] {
  911. remainingNbrs = append(remainingNbrs, nbr)
  912. }
  913. }
  914. if len(remainingNbrs) > 0 {
  915. sb.WriteString(" interface \"*\" {\n")
  916. sb.WriteString(" type nonbroadcast;\n")
  917. for _, nbr := range remainingNbrs {
  918. if nbr.PollInterval > 0 {
  919. sb.WriteString(fmt.Sprintf(" poll %d;\n", nbr.PollInterval))
  920. break
  921. }
  922. }
  923. sb.WriteString(" neighbors {\n")
  924. for _, nbr := range remainingNbrs {
  925. addr := strings.TrimSpace(nbr.Address)
  926. if addr != "" {
  927. sb.WriteString(fmt.Sprintf(" %s;\n", addr))
  928. }
  929. }
  930. sb.WriteString(" };\n")
  931. sb.WriteString(" };\n")
  932. }
  933. // Fallback wildcard interface template if none configured for this area
  934. if !hasAreaTemplate && len(remainingNbrs) == 0 {
  935. sb.WriteString(" interface \"*\" {\n")
  936. sb.WriteString(" cost 1;\n")
  937. sb.WriteString(" type bcast;\n")
  938. sb.WriteString(" };\n")
  939. }
  940. sb.WriteString(" };\n")
  941. }
  942. sb.WriteString("}\n\n")
  943. }
  944. // BFD Protocol (/routing bfd)
  945. if m.config.BFDInstance.Enabled || len(m.config.BFDInterfaces) > 0 || len(m.config.BFDNeighbors) > 0 {
  946. bfdDisabled := m.config.BFDInstance.Disabled
  947. sb.WriteString("protocol bfd bfd_main {\n")
  948. if bfdDisabled {
  949. sb.WriteString(" disabled;\n")
  950. }
  951. for _, bif := range m.config.BFDInterfaces {
  952. if bif.Disabled {
  953. continue
  954. }
  955. ifName := strings.TrimSpace(bif.Interface)
  956. if ifName == "" {
  957. ifName = "*"
  958. }
  959. sb.WriteString(fmt.Sprintf(" interface \"%s\" {\n", ifName))
  960. if bif.MinRxInterval > 0 {
  961. sb.WriteString(fmt.Sprintf(" min rx interval %d ms;\n", bif.MinRxInterval))
  962. }
  963. if bif.MinTxInterval > 0 {
  964. sb.WriteString(fmt.Sprintf(" min tx interval %d ms;\n", bif.MinTxInterval))
  965. }
  966. if bif.IdleTxInterval > 0 {
  967. sb.WriteString(fmt.Sprintf(" idle tx interval %d ms;\n", bif.IdleTxInterval))
  968. }
  969. if bif.Multiplier > 0 {
  970. sb.WriteString(fmt.Sprintf(" multiplier %d;\n", bif.Multiplier))
  971. }
  972. if bif.Passive {
  973. sb.WriteString(" passive yes;\n")
  974. }
  975. if bif.Auth != "" && bif.Auth != "none" && bif.AuthKey != "" {
  976. sb.WriteString(fmt.Sprintf(" authentication %s;\n", bif.Auth))
  977. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", bif.AuthKey))
  978. }
  979. sb.WriteString(" };\n")
  980. }
  981. for _, bn := range m.config.BFDNeighbors {
  982. if bn.Disabled || strings.TrimSpace(bn.Address) == "" {
  983. continue
  984. }
  985. if bn.LocalAddress != "" && bn.Multihop {
  986. sb.WriteString(fmt.Sprintf(" neighbor %s local %s multihop;\n", strings.TrimSpace(bn.Address), strings.TrimSpace(bn.LocalAddress)))
  987. } else if bn.Interface != "" {
  988. sb.WriteString(fmt.Sprintf(" neighbor %s dev \"%s\";\n", strings.TrimSpace(bn.Address), strings.TrimSpace(bn.Interface)))
  989. } else if bn.Multihop {
  990. sb.WriteString(fmt.Sprintf(" neighbor %s multihop;\n", strings.TrimSpace(bn.Address)))
  991. } else {
  992. sb.WriteString(fmt.Sprintf(" neighbor %s;\n", strings.TrimSpace(bn.Address)))
  993. }
  994. }
  995. // If no interface block was specified, add default wildcard interface
  996. if len(m.config.BFDInterfaces) == 0 {
  997. sb.WriteString(" interface \"*\" {\n min rx interval 100 ms;\n min tx interval 100 ms;\n };\n")
  998. }
  999. sb.WriteString("}\n\n")
  1000. }
  1001. // RIP Protocols (/routing rip)
  1002. for idx, inst := range m.config.RIPInstances {
  1003. if inst.Disabled {
  1004. continue
  1005. }
  1006. instProtoName := sanitizeIdentifier("rip", fmt.Sprintf("%s_%d", inst.Name, idx))
  1007. protoKeyword := "protocol rip"
  1008. channelKeyword := "ipv4"
  1009. if inst.Version == 1 {
  1010. protoKeyword = "protocol rip ng"
  1011. channelKeyword = "ipv6"
  1012. }
  1013. sb.WriteString(fmt.Sprintf("%s %s {\n", protoKeyword, instProtoName))
  1014. if inst.VRF != "" && inst.VRF != "main" && inst.VRF != "default" {
  1015. sb.WriteString(fmt.Sprintf(" vrf %s;\n", inst.VRF))
  1016. }
  1017. sb.WriteString(fmt.Sprintf(" %s {\n", channelKeyword))
  1018. if inst.RoutingTable != "" && inst.RoutingTable != "main" {
  1019. sb.WriteString(fmt.Sprintf(" table %s;\n", inst.RoutingTable))
  1020. }
  1021. if inst.InFilter != "" && len(chainRules[inst.InFilter]) > 0 {
  1022. sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", inst.InFilter)))
  1023. } else {
  1024. sb.WriteString(" import filter { krt_metric = 120; accept; };\n")
  1025. }
  1026. var ripExports []string
  1027. ripExports = append(ripExports, "RTS_RIP")
  1028. if inst.RedistributeStatic {
  1029. ripExports = append(ripExports, "RTS_STATIC", "RTS_INHERIT")
  1030. }
  1031. if inst.RedistributeConnected {
  1032. ripExports = append(ripExports, "RTS_DEVICE")
  1033. }
  1034. if inst.RedistributeOSPF {
  1035. ripExports = append(ripExports, "RTS_OSPF")
  1036. }
  1037. if inst.RedistributeBGP {
  1038. ripExports = append(ripExports, "RTS_BGP")
  1039. }
  1040. if inst.OutFilter != "" && len(chainRules[inst.OutFilter]) > 0 {
  1041. fnName := fmt.Sprintf("fn_%s", sanitizeIdentifier("filter", inst.OutFilter))
  1042. sb.WriteString(" export filter {\n")
  1043. if len(ripExports) > 0 || inst.RedistributeDefault {
  1044. var conds []string
  1045. if inst.RedistributeDefault {
  1046. conds = append(conds, "net = 0.0.0.0/0", "net = ::/0")
  1047. }
  1048. if len(ripExports) > 0 {
  1049. conds = append(conds, fmt.Sprintf("source ~ [ %s ]", strings.Join(ripExports, ", ")))
  1050. }
  1051. sb.WriteString(fmt.Sprintf(" if !( %s ) then reject;\n", strings.Join(conds, " || ")))
  1052. }
  1053. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  1054. if inst.RedistributeDefault {
  1055. sb.WriteString(" if net = 0.0.0.0/0 || net = ::/0 then accept;\n")
  1056. }
  1057. if len(ripExports) > 0 {
  1058. sb.WriteString(fmt.Sprintf(" if source ~ [ %s ] then accept;\n", strings.Join(ripExports, ", ")))
  1059. }
  1060. sb.WriteString(" reject;\n")
  1061. sb.WriteString(" };\n")
  1062. } else if len(ripExports) > 0 || inst.RedistributeDefault {
  1063. sb.WriteString(" export filter {\n")
  1064. if inst.RedistributeDefault {
  1065. sb.WriteString(" if net = 0.0.0.0/0 || net = ::/0 then accept;\n")
  1066. }
  1067. if len(ripExports) > 0 {
  1068. sb.WriteString(fmt.Sprintf(" if source ~ [ %s ] then accept;\n", strings.Join(ripExports, ", ")))
  1069. }
  1070. sb.WriteString(" reject;\n")
  1071. sb.WriteString(" };\n")
  1072. } else {
  1073. sb.WriteString(" export none;\n")
  1074. }
  1075. sb.WriteString(" };\n\n")
  1076. // Interfaces for this RIP instance
  1077. hasRIPInterface := false
  1078. for _, iface := range m.config.RIPInterfaces {
  1079. if iface.Disabled {
  1080. continue
  1081. }
  1082. if iface.Instance != "" && !strings.EqualFold(iface.Instance, inst.Name) && !strings.EqualFold(iface.Instance, "Default") {
  1083. continue
  1084. }
  1085. hasRIPInterface = true
  1086. ifName := strings.TrimSpace(iface.Interface)
  1087. if ifName == "" {
  1088. ifName = "*"
  1089. }
  1090. sb.WriteString(fmt.Sprintf(" interface \"%s\" {\n", ifName))
  1091. if iface.Metric > 0 {
  1092. sb.WriteString(fmt.Sprintf(" metric %d;\n", iface.Metric))
  1093. }
  1094. if iface.Mode == "broadcast" {
  1095. sb.WriteString(" mode broadcast;\n")
  1096. } else {
  1097. sb.WriteString(" mode multicast;\n")
  1098. }
  1099. if inst.Version == 2 || inst.Version == 0 {
  1100. sb.WriteString(" version 2;\n")
  1101. }
  1102. if inst.UpdateTime > 0 {
  1103. sb.WriteString(fmt.Sprintf(" update time %d;\n", inst.UpdateTime))
  1104. }
  1105. if inst.TimeoutTime > 0 {
  1106. sb.WriteString(fmt.Sprintf(" timeout time %d;\n", inst.TimeoutTime))
  1107. }
  1108. if iface.Passive {
  1109. sb.WriteString(" passive yes;\n")
  1110. }
  1111. if iface.UseBFD {
  1112. sb.WriteString(" bfd yes;\n")
  1113. }
  1114. if iface.Auth != "" && iface.Auth != "none" && iface.AuthKey != "" {
  1115. if iface.Auth == "md5" || iface.Auth == "cryptographic" {
  1116. sb.WriteString(" authentication cryptographic;\n")
  1117. } else {
  1118. sb.WriteString(" authentication plaintext;\n")
  1119. }
  1120. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  1121. }
  1122. sb.WriteString(" };\n")
  1123. }
  1124. if !hasRIPInterface {
  1125. sb.WriteString(" interface \"*\" {\n mode multicast;\n };\n")
  1126. }
  1127. sb.WriteString("}\n\n")
  1128. }
  1129. // Babel Protocols (/routing babel)
  1130. for idx, inst := range m.config.BabelInstances {
  1131. if inst.Disabled {
  1132. continue
  1133. }
  1134. instProtoName := sanitizeIdentifier("babel", fmt.Sprintf("%s_%d", inst.Name, idx))
  1135. sb.WriteString(fmt.Sprintf("protocol babel %s {\n", instProtoName))
  1136. if inst.VRF != "" && inst.VRF != "main" && inst.VRF != "default" {
  1137. sb.WriteString(fmt.Sprintf(" vrf %s;\n", inst.VRF))
  1138. }
  1139. if inst.RouterID != "" {
  1140. sb.WriteString(fmt.Sprintf(" router id %s;\n", inst.RouterID))
  1141. }
  1142. sb.WriteString(" ipv4 {\n")
  1143. if inst.RoutingTable != "" && inst.RoutingTable != "main" {
  1144. sb.WriteString(fmt.Sprintf(" table %s;\n", inst.RoutingTable))
  1145. }
  1146. if inst.InFilter != "" && len(chainRules[inst.InFilter]) > 0 {
  1147. sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", inst.InFilter)))
  1148. } else {
  1149. sb.WriteString(" import filter { krt_metric = 130; accept; };\n")
  1150. }
  1151. var babelExports []string
  1152. babelExports = append(babelExports, "RTS_BABEL")
  1153. if inst.RedistributeStatic {
  1154. babelExports = append(babelExports, "RTS_STATIC", "RTS_INHERIT")
  1155. }
  1156. if inst.RedistributeConnected {
  1157. babelExports = append(babelExports, "RTS_DEVICE")
  1158. }
  1159. if inst.RedistributeOSPF {
  1160. babelExports = append(babelExports, "RTS_OSPF")
  1161. }
  1162. if inst.RedistributeBGP {
  1163. babelExports = append(babelExports, "RTS_BGP")
  1164. }
  1165. if inst.OutFilter != "" && len(chainRules[inst.OutFilter]) > 0 {
  1166. fnName := fmt.Sprintf("fn_%s", sanitizeIdentifier("filter", inst.OutFilter))
  1167. sb.WriteString(" export filter {\n")
  1168. if len(babelExports) > 0 || inst.RedistributeDefault {
  1169. var conds []string
  1170. if inst.RedistributeDefault {
  1171. conds = append(conds, "net = 0.0.0.0/0")
  1172. }
  1173. if len(babelExports) > 0 {
  1174. conds = append(conds, fmt.Sprintf("source ~ [ %s ]", strings.Join(babelExports, ", ")))
  1175. }
  1176. sb.WriteString(fmt.Sprintf(" if !( %s ) then reject;\n", strings.Join(conds, " || ")))
  1177. }
  1178. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  1179. sb.WriteString(" reject;\n")
  1180. sb.WriteString(" };\n")
  1181. } else if len(babelExports) > 0 || inst.RedistributeDefault {
  1182. sb.WriteString(" export filter {\n")
  1183. if inst.RedistributeDefault {
  1184. sb.WriteString(" if net = 0.0.0.0/0 then accept;\n")
  1185. }
  1186. if len(babelExports) > 0 {
  1187. sb.WriteString(fmt.Sprintf(" if source ~ [ %s ] then accept;\n", strings.Join(babelExports, ", ")))
  1188. }
  1189. sb.WriteString(" reject;\n")
  1190. sb.WriteString(" };\n")
  1191. } else {
  1192. sb.WriteString(" export none;\n")
  1193. }
  1194. sb.WriteString(" };\n\n")
  1195. sb.WriteString(" ipv6 {\n")
  1196. sb.WriteString(" import all;\n")
  1197. sb.WriteString(" export all;\n")
  1198. sb.WriteString(" };\n\n")
  1199. hasIface := false
  1200. for _, iface := range m.config.BabelInterfaces {
  1201. if iface.Disabled {
  1202. continue
  1203. }
  1204. if iface.Instance != "" && !strings.EqualFold(iface.Instance, inst.Name) && !strings.EqualFold(iface.Instance, "Default") && !strings.EqualFold(iface.Instance, "*") && !strings.EqualFold(iface.Instance, "all") {
  1205. continue
  1206. }
  1207. hasIface = true
  1208. ifName := strings.TrimSpace(iface.Interface)
  1209. if ifName == "" {
  1210. ifName = "*"
  1211. }
  1212. sb.WriteString(fmt.Sprintf(" interface \"%s\" {\n", ifName))
  1213. if iface.Type != "" {
  1214. sb.WriteString(fmt.Sprintf(" type %s;\n", iface.Type))
  1215. } else {
  1216. sb.WriteString(" type wired;\n")
  1217. }
  1218. if iface.RxCost > 0 {
  1219. sb.WriteString(fmt.Sprintf(" rxcost %d;\n", iface.RxCost))
  1220. }
  1221. if iface.HelloInterval > 0 {
  1222. sb.WriteString(fmt.Sprintf(" hello interval %d s;\n", iface.HelloInterval))
  1223. }
  1224. if iface.UpdateInterval > 0 {
  1225. sb.WriteString(fmt.Sprintf(" update interval %d s;\n", iface.UpdateInterval))
  1226. }
  1227. if iface.Auth != "" && iface.Auth != "none" && iface.AuthKey != "" {
  1228. sb.WriteString(" authentication mac;\n")
  1229. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  1230. }
  1231. sb.WriteString(" };\n")
  1232. }
  1233. if !hasIface {
  1234. sb.WriteString(" interface \"*\" {\n")
  1235. sb.WriteString(" type wired;\n")
  1236. sb.WriteString(" };\n")
  1237. }
  1238. sb.WriteString("}\n\n")
  1239. }
  1240. // RAdv Protocols (/routing radv)
  1241. for idx, inst := range m.config.RAdvInstances {
  1242. if inst.Disabled {
  1243. continue
  1244. }
  1245. instProtoName := sanitizeIdentifier("radv", fmt.Sprintf("%s_%d", inst.Name, idx))
  1246. sb.WriteString(fmt.Sprintf("protocol radv %s {\n", instProtoName))
  1247. hasRAdvInterface := false
  1248. for _, iface := range m.config.RAdvInterfaces {
  1249. if iface.Disabled {
  1250. continue
  1251. }
  1252. if iface.Instance != "" && !strings.EqualFold(iface.Instance, inst.Name) && !strings.EqualFold(iface.Instance, "Default") {
  1253. continue
  1254. }
  1255. hasRAdvInterface = true
  1256. ifName := strings.TrimSpace(iface.Interface)
  1257. if ifName == "" {
  1258. ifName = "*"
  1259. }
  1260. sb.WriteString(fmt.Sprintf(" interface \"%s\" {\n", ifName))
  1261. if iface.MinRAInterval > 0 {
  1262. sb.WriteString(fmt.Sprintf(" min ra interval %d;\n", iface.MinRAInterval))
  1263. }
  1264. if iface.MaxRAInterval > 0 {
  1265. sb.WriteString(fmt.Sprintf(" max ra interval %d;\n", iface.MaxRAInterval))
  1266. }
  1267. if iface.DefaultLifetime > 0 {
  1268. sb.WriteString(fmt.Sprintf(" default lifetime %d;\n", iface.DefaultLifetime))
  1269. }
  1270. if iface.HopLimit > 0 {
  1271. sb.WriteString(fmt.Sprintf(" hop limit %d;\n", iface.HopLimit))
  1272. }
  1273. for _, pfx := range iface.Prefixes {
  1274. pfx = strings.TrimSpace(pfx)
  1275. if pfx != "" {
  1276. sb.WriteString(fmt.Sprintf(" prefix %s {\n", pfx))
  1277. sb.WriteString(" autonomous 1;\n")
  1278. sb.WriteString(" onlink 1;\n")
  1279. sb.WriteString(" };\n")
  1280. }
  1281. }
  1282. if len(iface.RDNSS) > 0 {
  1283. sb.WriteString(" rdnss {\n")
  1284. for _, ns := range iface.RDNSS {
  1285. ns = strings.TrimSpace(ns)
  1286. if ns != "" {
  1287. sb.WriteString(fmt.Sprintf(" ns %s;\n", ns))
  1288. }
  1289. }
  1290. sb.WriteString(" };\n")
  1291. }
  1292. sb.WriteString(" };\n")
  1293. }
  1294. if !hasRAdvInterface {
  1295. sb.WriteString(" interface \"*\" {\n };\n")
  1296. }
  1297. sb.WriteString("}\n\n")
  1298. }
  1299. return sb.String()
  1300. }
  1301. // applyBirdConfig generates /etc/bird/bird.conf and live reloads BIRD daemon
  1302. func (m *Manager) applyBirdConfig() error {
  1303. cfgText := m.generateBirdConfig()
  1304. bPath := m.getBirdConfigPath()
  1305. // Ensure directory exists with proper permissions
  1306. dir := filepath.Dir(bPath)
  1307. if err := os.MkdirAll(dir, 0775); err == nil {
  1308. _ = os.Chmod(dir, 0775)
  1309. _ = exec.Command("chown", "root:bird", dir).Run()
  1310. }
  1311. // Write candidate configuration to temporary file
  1312. tmpPath := bPath + ".new"
  1313. if err := os.WriteFile(tmpPath, []byte(cfgText), 0664); err != nil {
  1314. return fmt.Errorf("failed to write %s: %w", tmpPath, err)
  1315. }
  1316. _ = exec.Command("chown", "root:bird", tmpPath).Run()
  1317. // Validate syntax with bird -p if bird is installed
  1318. if bPath == birdConfigPath {
  1319. out, err := exec.Command("bird", "-p", "-c", tmpPath).CombinedOutput()
  1320. if err != nil {
  1321. _ = os.Remove(tmpPath)
  1322. return fmt.Errorf("bird syntax check failed: %s: %w", string(out), err)
  1323. }
  1324. }
  1325. // Replace active config
  1326. if err := os.Rename(tmpPath, bPath); err != nil {
  1327. return fmt.Errorf("failed to replace %s: %w", bPath, err)
  1328. }
  1329. _ = os.Chmod(bPath, 0664)
  1330. _ = exec.Command("chown", "root:bird", bPath).Run()
  1331. if bPath != birdConfigPath {
  1332. return nil
  1333. }
  1334. // Ensure BIRD systemd service is active
  1335. _ = exec.Command("systemctl", "start", "bird").Run()
  1336. // Live reload without packet loss
  1337. reloadOut, reloadErr := birdcExec("configure")
  1338. if reloadErr != nil {
  1339. return fmt.Errorf("BIRD reload failed: %s: %w", string(reloadOut), reloadErr)
  1340. }
  1341. // Synchronize kernel blackhole routes (distance 255) for all active advertised prefixes
  1342. m.syncKernelBlackholeRoutes()
  1343. // Synchronize FRR EIGRP configuration
  1344. if err := m.applyFRREigrpConfig(); err != nil {
  1345. return fmt.Errorf("BIRD applied, but FRR EIGRP synchronization failed: %w", err)
  1346. }
  1347. return nil
  1348. }
  1349. func birdcExec(cmd string) ([]byte, error) {
  1350. return exec.Command("birdc", cmd).CombinedOutput()
  1351. }
  1352. // syncKernelBlackholeRoutes ensures all BGP advertised networks (global BGP networks and peer OutputNetworks)
  1353. // have corresponding blackhole routes with metric 255 installed in the Linux kernel routing table.
  1354. // This guarantees that BGP can announce these prefixes reliably into the RIB/FIB, while ensuring any active
  1355. // connected/local routes take precedence (metric 0 < metric 255) and prevents routing loops if subnets are incomplete.
  1356. func (m *Manager) syncKernelBlackholeRoutes() {
  1357. desired := make(map[string]bool)
  1358. if m.config.BGPInstance.Enabled {
  1359. for _, n := range m.config.BGPNetworks {
  1360. cidr := strings.TrimSpace(n.Network)
  1361. if !n.Disabled && cidr != "" {
  1362. if _, _, err := net.ParseCIDR(cidr); err == nil {
  1363. desired[cidr] = true
  1364. }
  1365. }
  1366. }
  1367. for _, p := range m.config.BGPPeers {
  1368. if p.Disabled {
  1369. continue
  1370. }
  1371. for _, on := range p.OutputNetworks {
  1372. cidr := strings.TrimSpace(on)
  1373. if cidr != "" {
  1374. if _, _, err := net.ParseCIDR(cidr); err == nil {
  1375. desired[cidr] = true
  1376. }
  1377. }
  1378. }
  1379. }
  1380. }
  1381. // Query existing kernel blackhole routes with metric 255
  1382. out, err := exec.Command("ip", "route", "show", "type", "blackhole").Output()
  1383. existing := make(map[string]bool)
  1384. if err == nil {
  1385. lines := strings.Split(string(out), "\n")
  1386. for _, line := range lines {
  1387. line = strings.TrimSpace(line)
  1388. if line == "" {
  1389. continue
  1390. }
  1391. parts := strings.Fields(line)
  1392. if len(parts) >= 2 && parts[0] == "blackhole" {
  1393. dst := parts[1]
  1394. if strings.Contains(line, "metric 255") {
  1395. existing[dst] = true
  1396. }
  1397. }
  1398. }
  1399. }
  1400. // Install desired blackhole routes with metric 255 proto static
  1401. for cidr := range desired {
  1402. if !existing[cidr] {
  1403. cmd := exec.Command("ip", "route", "replace", "blackhole", cidr, "metric", "255", "proto", "static")
  1404. if out, err := cmd.CombinedOutput(); err != nil {
  1405. log.Printf("[DynamicRouting] Warning: failed to install kernel blackhole route %s: %s (%v)", cidr, string(out), err)
  1406. } else {
  1407. log.Printf("[DynamicRouting] Installed kernel blackhole route %s with metric 255 (BGP advertised)", cidr)
  1408. }
  1409. }
  1410. }
  1411. // Cleanup any obsolete blackhole routes that were previously installed with metric 255
  1412. // Check static_routes.json first to ensure we don't delete user's manual static routes
  1413. userManualStaticBlackholes := make(map[string]bool)
  1414. if data, err := os.ReadFile("/etc/debtik/routing/static_routes.json"); err == nil {
  1415. var userRoutes []struct {
  1416. DstAddress string `json:"dst_address"`
  1417. Gateway string `json:"gateway"`
  1418. Action string `json:"action"`
  1419. Disabled bool `json:"disabled"`
  1420. }
  1421. if json.Unmarshal(data, &userRoutes) == nil {
  1422. for _, ur := range userRoutes {
  1423. if !ur.Disabled && (strings.EqualFold(ur.Gateway, "blackhole") || strings.EqualFold(ur.Action, "blackhole")) {
  1424. userManualStaticBlackholes[strings.TrimSpace(ur.DstAddress)] = true
  1425. }
  1426. }
  1427. }
  1428. }
  1429. for cidr := range existing {
  1430. if !desired[cidr] && !userManualStaticBlackholes[cidr] {
  1431. _ = exec.Command("ip", "route", "del", "blackhole", cidr, "metric", "255").Run()
  1432. log.Printf("[DynamicRouting] Removed obsolete kernel blackhole route %s metric 255", cidr)
  1433. }
  1434. }
  1435. }
  1436. // -------------------------------------------------------------
  1437. // BGP API & Operations (Multi-Instance BGP)
  1438. // -------------------------------------------------------------
  1439. func (m *Manager) GetBGPInstance() BGPInstance {
  1440. m.mu.RLock()
  1441. defer m.mu.RUnlock()
  1442. inst := m.config.BGPInstance
  1443. out, err := birdcExec("show status")
  1444. if err == nil && strings.Contains(string(out), "Daemon is up and running") && inst.Enabled {
  1445. inst.Running = true
  1446. }
  1447. return inst
  1448. }
  1449. func (m *Manager) UpdateBGPInstance(inst BGPInstance) error {
  1450. m.mu.Lock()
  1451. m.config.BGPInstance = inst
  1452. _ = m.save()
  1453. m.mu.Unlock()
  1454. return m.applyBirdConfig()
  1455. }
  1456. func (m *Manager) ListBGPPeers() []BGPPeer {
  1457. m.mu.RLock()
  1458. defer m.mu.RUnlock()
  1459. peers := make([]BGPPeer, len(m.config.BGPPeers))
  1460. copy(peers, m.config.BGPPeers)
  1461. // Fetch live peer telemetry from birdc
  1462. out, err := birdcExec("show protocols all")
  1463. if err == nil {
  1464. type livePeerData struct {
  1465. State string
  1466. RemoteAddr string
  1467. RemoteAS uint32
  1468. LocalAS uint32
  1469. PfxRcd int
  1470. PfxSnt int
  1471. Uptime string
  1472. }
  1473. liveMap := make(map[string]*livePeerData)
  1474. lines := strings.Split(string(out), "\n")
  1475. var cur *livePeerData
  1476. now := time.Now()
  1477. for _, line := range lines {
  1478. trimmed := strings.TrimSpace(line)
  1479. // A protocol header line in BIRD is unindented and has "BGP" in column 2
  1480. if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
  1481. fields := strings.Fields(line)
  1482. if len(fields) >= 2 && fields[1] == "BGP" {
  1483. cur = &livePeerData{}
  1484. var sinceStr string
  1485. if len(fields) >= 6 && strings.Contains(fields[4], "-") && strings.Contains(fields[5], ":") {
  1486. sinceStr = fields[4] + " " + fields[5]
  1487. } else if len(fields) >= 5 {
  1488. sinceStr = fields[4]
  1489. }
  1490. cur.Uptime = parseBirdSinceToUptime(sinceStr, now)
  1491. } else {
  1492. cur = nil
  1493. }
  1494. }
  1495. if cur == nil {
  1496. continue
  1497. }
  1498. if strings.HasPrefix(trimmed, "BGP state:") {
  1499. cur.State = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP state:"))
  1500. } else if strings.HasPrefix(trimmed, "Neighbor address:") {
  1501. cur.RemoteAddr = strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor address:"))
  1502. liveMap[cur.RemoteAddr] = cur
  1503. } else if strings.HasPrefix(trimmed, "Neighbor AS:") {
  1504. v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor AS:")), 10, 32)
  1505. cur.RemoteAS = uint32(v)
  1506. } else if strings.HasPrefix(trimmed, "Local AS:") {
  1507. v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Local AS:")), 10, 32)
  1508. cur.LocalAS = uint32(v)
  1509. } else if strings.HasPrefix(trimmed, "Routes:") {
  1510. parts := strings.Split(trimmed, ",")
  1511. for _, p := range parts {
  1512. p = strings.TrimSpace(p)
  1513. if strings.Contains(p, "imported") {
  1514. f := strings.Fields(p)
  1515. if len(f) >= 2 {
  1516. cur.PfxRcd, _ = strconv.Atoi(f[len(f)-2])
  1517. }
  1518. } else if strings.Contains(p, "exported") {
  1519. f := strings.Fields(p)
  1520. if len(f) >= 2 {
  1521. cur.PfxSnt, _ = strconv.Atoi(f[0])
  1522. }
  1523. }
  1524. }
  1525. }
  1526. }
  1527. for i := range peers {
  1528. if live, ok := liveMap[peers[i].RemoteAddress]; ok {
  1529. peers[i].State = live.State
  1530. if live.State == "Established" {
  1531. peers[i].Uptime = live.Uptime
  1532. } else {
  1533. peers[i].Uptime = ""
  1534. }
  1535. peers[i].PrefixReceived = live.PfxRcd
  1536. peers[i].PrefixSent = live.PfxSnt
  1537. if peers[i].LocalAS == 0 && live.LocalAS > 0 {
  1538. peers[i].LocalAS = live.LocalAS
  1539. }
  1540. } else if peers[i].Disabled {
  1541. peers[i].State = "Disabled"
  1542. peers[i].Uptime = ""
  1543. } else {
  1544. peers[i].State = "Idle"
  1545. peers[i].Uptime = ""
  1546. }
  1547. }
  1548. }
  1549. return peers
  1550. }
  1551. func parseBirdSinceToUptime(sinceStr string, now time.Time) string {
  1552. sinceStr = strings.TrimSpace(sinceStr)
  1553. if sinceStr == "" {
  1554. return ""
  1555. }
  1556. // Case 1: "2006-01-02 15:04:05" (ISO long)
  1557. if t, err := time.ParseInLocation("2006-01-02 15:04:05", sinceStr, time.Local); err == nil {
  1558. return formatDuration(now.Sub(t))
  1559. }
  1560. // Case 2: "2006-01-02 15:04:05.999" (ISO long with milliseconds)
  1561. if t, err := time.ParseInLocation("2006-01-02 15:04:05.999", sinceStr, time.Local); err == nil {
  1562. return formatDuration(now.Sub(t))
  1563. }
  1564. // Case 3: "2006-01-02" (date only)
  1565. if t, err := time.ParseInLocation("2006-01-02", sinceStr, time.Local); err == nil {
  1566. return formatDuration(now.Sub(t))
  1567. }
  1568. // Case 4: "15:04:05" or "15:04:05.123" (time only, happened today)
  1569. timeOnly := sinceStr
  1570. if idx := strings.IndexByte(timeOnly, '.'); idx != -1 {
  1571. timeOnly = timeOnly[:idx]
  1572. }
  1573. if t, err := time.ParseInLocation("15:04:05", timeOnly, time.Local); err == nil {
  1574. tToday := time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
  1575. if tToday.After(now) {
  1576. tToday = tToday.AddDate(0, 0, -1)
  1577. }
  1578. return formatDuration(now.Sub(tToday))
  1579. }
  1580. return ""
  1581. }
  1582. func formatDuration(d time.Duration) string {
  1583. if d < 0 {
  1584. d = 0
  1585. }
  1586. sec := int64(d.Seconds())
  1587. days := sec / 86400
  1588. hours := (sec % 86400) / 3600
  1589. mins := (sec % 3600) / 60
  1590. secs := sec % 60
  1591. if days > 0 {
  1592. return fmt.Sprintf("%dd %02dh %02dm %02ds", days, hours, mins, secs)
  1593. }
  1594. return fmt.Sprintf("%02dh %02dm %02ds", hours, mins, secs)
  1595. }
  1596. func (m *Manager) SaveBGPPeer(peer *BGPPeer) error {
  1597. m.mu.Lock()
  1598. defer m.mu.Unlock()
  1599. if peer.ID == "" {
  1600. peer.ID = fmt.Sprintf("bgp-peer-%d", time.Now().UnixNano())
  1601. }
  1602. found := false
  1603. for i, p := range m.config.BGPPeers {
  1604. if p.ID == peer.ID {
  1605. m.config.BGPPeers[i] = *peer
  1606. found = true
  1607. break
  1608. }
  1609. }
  1610. if !found {
  1611. m.config.BGPPeers = append(m.config.BGPPeers, *peer)
  1612. }
  1613. if err := m.save(); err != nil {
  1614. return err
  1615. }
  1616. return m.applyBirdConfig()
  1617. }
  1618. func (m *Manager) DeleteBGPPeer(id string) error {
  1619. m.mu.Lock()
  1620. defer m.mu.Unlock()
  1621. newPeers := make([]BGPPeer, 0, len(m.config.BGPPeers))
  1622. for _, p := range m.config.BGPPeers {
  1623. if p.ID != id {
  1624. newPeers = append(newPeers, p)
  1625. }
  1626. }
  1627. m.config.BGPPeers = newPeers
  1628. if err := m.save(); err != nil {
  1629. return err
  1630. }
  1631. return m.applyBirdConfig()
  1632. }
  1633. func (m *Manager) SetBGPPeerState(id string, disabled bool) error {
  1634. m.mu.Lock()
  1635. defer m.mu.Unlock()
  1636. for i := range m.config.BGPPeers {
  1637. if m.config.BGPPeers[i].ID == id {
  1638. m.config.BGPPeers[i].Disabled = disabled
  1639. break
  1640. }
  1641. }
  1642. if err := m.save(); err != nil {
  1643. return err
  1644. }
  1645. return m.applyBirdConfig()
  1646. }
  1647. func (m *Manager) ListBGPNetworks() []BGPNetwork {
  1648. m.mu.RLock()
  1649. defer m.mu.RUnlock()
  1650. return m.config.BGPNetworks
  1651. }
  1652. func (m *Manager) SaveBGPNetwork(net BGPNetwork) error {
  1653. m.mu.Lock()
  1654. defer m.mu.Unlock()
  1655. if net.ID == "" {
  1656. net.ID = fmt.Sprintf("bgp-net-%d", time.Now().UnixNano())
  1657. }
  1658. found := false
  1659. for i, n := range m.config.BGPNetworks {
  1660. if n.ID == net.ID {
  1661. m.config.BGPNetworks[i] = net
  1662. found = true
  1663. break
  1664. }
  1665. }
  1666. if !found {
  1667. m.config.BGPNetworks = append(m.config.BGPNetworks, net)
  1668. }
  1669. if err := m.save(); err != nil {
  1670. return err
  1671. }
  1672. return m.applyBirdConfig()
  1673. }
  1674. func (m *Manager) DeleteBGPNetwork(id string) error {
  1675. m.mu.Lock()
  1676. defer m.mu.Unlock()
  1677. newNets := make([]BGPNetwork, 0, len(m.config.BGPNetworks))
  1678. for _, n := range m.config.BGPNetworks {
  1679. if n.ID != id {
  1680. newNets = append(newNets, n)
  1681. }
  1682. }
  1683. m.config.BGPNetworks = newNets
  1684. if err := m.save(); err != nil {
  1685. return err
  1686. }
  1687. return m.applyBirdConfig()
  1688. }
  1689. func (m *Manager) GetBGPRoutes() []BGPRoute {
  1690. var routes []BGPRoute
  1691. out, err := birdcExec("show route where source = RTS_BGP all")
  1692. if err != nil {
  1693. return routes
  1694. }
  1695. lines := strings.Split(string(out), "\n")
  1696. var cur *BGPRoute
  1697. for _, line := range lines {
  1698. trimmed := strings.TrimSpace(line)
  1699. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  1700. continue
  1701. }
  1702. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  1703. fields := strings.Fields(trimmed)
  1704. if len(fields) >= 2 {
  1705. routes = append(routes, BGPRoute{
  1706. Prefix: fields[0],
  1707. Best: strings.Contains(line, "*"),
  1708. Origin: "IGP",
  1709. })
  1710. cur = &routes[len(routes)-1]
  1711. }
  1712. continue
  1713. }
  1714. if cur == nil {
  1715. continue
  1716. }
  1717. if strings.HasPrefix(trimmed, "via ") {
  1718. parts := strings.Fields(trimmed)
  1719. if len(parts) >= 2 {
  1720. cur.NextHop = parts[1]
  1721. }
  1722. } else if strings.HasPrefix(trimmed, "BGP.as_path:") {
  1723. cur.Path = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.as_path:"))
  1724. } else if strings.HasPrefix(trimmed, "BGP.origin:") {
  1725. cur.Origin = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.origin:"))
  1726. } else if strings.HasPrefix(trimmed, "BGP.next_hop:") {
  1727. cur.NextHop = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.next_hop:"))
  1728. } else if strings.HasPrefix(trimmed, "BGP.med:") {
  1729. cur.Metric, _ = strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.med:")))
  1730. }
  1731. }
  1732. return routes
  1733. }
  1734. // -------------------------------------------------------------
  1735. // OSPF API & Operations (RouterOS v7 Style OSPF)
  1736. // -------------------------------------------------------------
  1737. func (m *Manager) ListOSPFInstances() []OSPFInstance {
  1738. m.mu.RLock()
  1739. defer m.mu.RUnlock()
  1740. out, err := birdcExec("show protocols")
  1741. protocols := map[string]bool{}
  1742. birdRunning := false
  1743. if err == nil {
  1744. birdRunning = strings.Contains(string(out), "BIRD")
  1745. for _, line := range strings.Split(string(out), "\n") {
  1746. fields := strings.Fields(line)
  1747. if len(fields) >= 4 && (fields[1] == "OSPF" || strings.HasPrefix(fields[0], "ospf_")) {
  1748. protocols[fields[0]] = fields[3] == "up"
  1749. }
  1750. }
  1751. }
  1752. instances := m.config.OSPFInstances
  1753. if len(instances) == 0 && (m.config.OSPFInstance.Name != "" || m.config.OSPFInstance.RouterID != "") {
  1754. legacy := m.config.OSPFInstance
  1755. if legacy.Name == "" {
  1756. legacy.Name = "Default"
  1757. }
  1758. if legacy.ID == "" {
  1759. legacy.ID = "ospf-inst-default"
  1760. }
  1761. instances = []OSPFInstance{legacy}
  1762. }
  1763. res := make([]OSPFInstance, len(instances))
  1764. for i, inst := range instances {
  1765. instCopy := inst
  1766. instCopy.Enabled = !inst.Disabled
  1767. instCopy.Running = false
  1768. isUp := protocols[sanitizeIdentifier("ospf", inst.Name)] || (birdRunning && !inst.Disabled)
  1769. if isUp && !inst.Disabled {
  1770. instCopy.Running = true
  1771. }
  1772. res[i] = instCopy
  1773. }
  1774. return res
  1775. }
  1776. func (m *Manager) SaveOSPFInstance(inst *OSPFInstance) error {
  1777. m.mu.Lock()
  1778. defer m.mu.Unlock()
  1779. if inst.ID == "" {
  1780. inst.ID = fmt.Sprintf("ospf-inst-%d", time.Now().UnixNano())
  1781. }
  1782. if inst.Name == "" {
  1783. inst.Name = "Default"
  1784. }
  1785. if inst.Version <= 0 {
  1786. inst.Version = 2
  1787. }
  1788. if inst.VRF == "" {
  1789. inst.VRF = "main"
  1790. }
  1791. if inst.RoutingTable == "" {
  1792. inst.RoutingTable = "main"
  1793. }
  1794. inst.Enabled = !inst.Disabled
  1795. found := false
  1796. for i, it := range m.config.OSPFInstances {
  1797. if it.ID == inst.ID || strings.EqualFold(it.Name, inst.Name) {
  1798. m.config.OSPFInstances[i] = *inst
  1799. found = true
  1800. break
  1801. }
  1802. }
  1803. if !found {
  1804. m.config.OSPFInstances = append(m.config.OSPFInstances, *inst)
  1805. }
  1806. // Update legacy instance holder as well
  1807. m.config.OSPFInstance = *inst
  1808. if err := m.save(); err != nil {
  1809. return err
  1810. }
  1811. return m.applyBirdConfig()
  1812. }
  1813. func (m *Manager) DeleteOSPFInstance(id string) error {
  1814. m.mu.Lock()
  1815. defer m.mu.Unlock()
  1816. var newInst []OSPFInstance
  1817. for _, it := range m.config.OSPFInstances {
  1818. if it.ID != id && !strings.EqualFold(it.Name, id) {
  1819. newInst = append(newInst, it)
  1820. }
  1821. }
  1822. m.config.OSPFInstances = newInst
  1823. if err := m.save(); err != nil {
  1824. return err
  1825. }
  1826. return m.applyBirdConfig()
  1827. }
  1828. func (m *Manager) SetOSPFInstanceState(id string, disabled bool) error {
  1829. m.mu.Lock()
  1830. defer m.mu.Unlock()
  1831. for i := range m.config.OSPFInstances {
  1832. if m.config.OSPFInstances[i].ID == id || strings.EqualFold(m.config.OSPFInstances[i].Name, id) {
  1833. m.config.OSPFInstances[i].Disabled = disabled
  1834. m.config.OSPFInstances[i].Enabled = !disabled
  1835. break
  1836. }
  1837. }
  1838. m.config.OSPFInstance.Disabled = disabled
  1839. m.config.OSPFInstance.Enabled = !disabled
  1840. if err := m.save(); err != nil {
  1841. return err
  1842. }
  1843. return m.applyBirdConfig()
  1844. }
  1845. func (m *Manager) GetOSPFInstance() OSPFInstance {
  1846. m.mu.RLock()
  1847. defer m.mu.RUnlock()
  1848. if len(m.config.OSPFInstances) > 0 {
  1849. inst := m.config.OSPFInstances[0]
  1850. out, err := birdcExec("show protocols")
  1851. if err == nil && strings.Contains(string(out), "OSPF") && strings.Contains(string(out), "up") && !inst.Disabled {
  1852. inst.Running = true
  1853. }
  1854. return inst
  1855. }
  1856. inst := m.config.OSPFInstance
  1857. out, err := birdcExec("show protocols")
  1858. if err == nil && strings.Contains(string(out), "OSPF") && strings.Contains(string(out), "up") && inst.Enabled {
  1859. inst.Running = true
  1860. }
  1861. return inst
  1862. }
  1863. func (m *Manager) UpdateOSPFInstance(inst OSPFInstance) error {
  1864. return m.SaveOSPFInstance(&inst)
  1865. }
  1866. func (m *Manager) ListOSPFAreas() []OSPFArea {
  1867. m.mu.RLock()
  1868. defer m.mu.RUnlock()
  1869. return m.config.OSPFAreas
  1870. }
  1871. func (m *Manager) SaveOSPFArea(area OSPFArea) error {
  1872. m.mu.Lock()
  1873. defer m.mu.Unlock()
  1874. if area.ID == "" {
  1875. area.ID = fmt.Sprintf("area-%d", time.Now().UnixNano())
  1876. }
  1877. if area.Name == "" {
  1878. area.Name = "Default"
  1879. }
  1880. if area.Instance == "" {
  1881. area.Instance = "Default"
  1882. }
  1883. if area.AreaID == "" {
  1884. area.AreaID = "0.0.0.0"
  1885. }
  1886. if area.AreaType == "" {
  1887. area.AreaType = "default"
  1888. }
  1889. found := false
  1890. for i, a := range m.config.OSPFAreas {
  1891. if a.ID == area.ID {
  1892. m.config.OSPFAreas[i] = area
  1893. found = true
  1894. break
  1895. }
  1896. }
  1897. if !found {
  1898. m.config.OSPFAreas = append(m.config.OSPFAreas, area)
  1899. }
  1900. if err := m.save(); err != nil {
  1901. return err
  1902. }
  1903. return m.applyBirdConfig()
  1904. }
  1905. func (m *Manager) DeleteOSPFArea(id string) error {
  1906. m.mu.Lock()
  1907. defer m.mu.Unlock()
  1908. newAreas := make([]OSPFArea, 0, len(m.config.OSPFAreas))
  1909. for _, a := range m.config.OSPFAreas {
  1910. if a.ID != id {
  1911. newAreas = append(newAreas, a)
  1912. }
  1913. }
  1914. m.config.OSPFAreas = newAreas
  1915. if err := m.save(); err != nil {
  1916. return err
  1917. }
  1918. return m.applyBirdConfig()
  1919. }
  1920. func (m *Manager) SetOSPFAreaState(id string, disabled bool) error {
  1921. m.mu.Lock()
  1922. defer m.mu.Unlock()
  1923. for i := range m.config.OSPFAreas {
  1924. if m.config.OSPFAreas[i].ID == id {
  1925. m.config.OSPFAreas[i].Disabled = disabled
  1926. break
  1927. }
  1928. }
  1929. if err := m.save(); err != nil {
  1930. return err
  1931. }
  1932. return m.applyBirdConfig()
  1933. }
  1934. func (m *Manager) ListOSPFAreaRanges() []OSPFAreaRange {
  1935. m.mu.RLock()
  1936. defer m.mu.RUnlock()
  1937. return m.config.OSPFAreaRanges
  1938. }
  1939. func (m *Manager) SaveOSPFAreaRange(ar OSPFAreaRange) error {
  1940. m.mu.Lock()
  1941. defer m.mu.Unlock()
  1942. if ar.ID == "" {
  1943. ar.ID = fmt.Sprintf("range-%d", time.Now().UnixNano())
  1944. }
  1945. if ar.Area == "" {
  1946. ar.Area = "Default"
  1947. }
  1948. found := false
  1949. for i, item := range m.config.OSPFAreaRanges {
  1950. if item.ID == ar.ID {
  1951. m.config.OSPFAreaRanges[i] = ar
  1952. found = true
  1953. break
  1954. }
  1955. }
  1956. if !found {
  1957. m.config.OSPFAreaRanges = append(m.config.OSPFAreaRanges, ar)
  1958. }
  1959. if err := m.save(); err != nil {
  1960. return err
  1961. }
  1962. return m.applyBirdConfig()
  1963. }
  1964. func (m *Manager) DeleteOSPFAreaRange(id string) error {
  1965. m.mu.Lock()
  1966. defer m.mu.Unlock()
  1967. newRanges := make([]OSPFAreaRange, 0, len(m.config.OSPFAreaRanges))
  1968. for _, item := range m.config.OSPFAreaRanges {
  1969. if item.ID != id {
  1970. newRanges = append(newRanges, item)
  1971. }
  1972. }
  1973. m.config.OSPFAreaRanges = newRanges
  1974. if err := m.save(); err != nil {
  1975. return err
  1976. }
  1977. return m.applyBirdConfig()
  1978. }
  1979. func (m *Manager) ListOSPFInterfaces() []OSPFInterface {
  1980. m.mu.RLock()
  1981. defer m.mu.RUnlock()
  1982. return m.config.OSPFInterfaces
  1983. }
  1984. func (m *Manager) SaveOSPFInterface(iface OSPFInterface) error {
  1985. m.mu.Lock()
  1986. defer m.mu.Unlock()
  1987. if iface.ID == "" {
  1988. iface.ID = fmt.Sprintf("ospf-tmpl-%d", time.Now().UnixNano())
  1989. }
  1990. if iface.Area == "" {
  1991. iface.Area = "Default"
  1992. }
  1993. if iface.Cost <= 0 {
  1994. iface.Cost = 1
  1995. }
  1996. if iface.Priority <= 0 {
  1997. iface.Priority = 128
  1998. }
  1999. if iface.NetworkType == "" {
  2000. iface.NetworkType = "broadcast"
  2001. }
  2002. if iface.HelloInterval <= 0 {
  2003. iface.HelloInterval = 10
  2004. }
  2005. if iface.DeadInterval <= 0 {
  2006. iface.DeadInterval = 40
  2007. }
  2008. found := false
  2009. for i, item := range m.config.OSPFInterfaces {
  2010. if item.ID == iface.ID {
  2011. m.config.OSPFInterfaces[i] = iface
  2012. found = true
  2013. break
  2014. }
  2015. }
  2016. if !found {
  2017. m.config.OSPFInterfaces = append(m.config.OSPFInterfaces, iface)
  2018. }
  2019. if err := m.save(); err != nil {
  2020. return err
  2021. }
  2022. return m.applyBirdConfig()
  2023. }
  2024. func (m *Manager) DeleteOSPFInterface(id string) error {
  2025. m.mu.Lock()
  2026. defer m.mu.Unlock()
  2027. newInterfaces := make([]OSPFInterface, 0, len(m.config.OSPFInterfaces))
  2028. for _, item := range m.config.OSPFInterfaces {
  2029. if item.ID != id {
  2030. newInterfaces = append(newInterfaces, item)
  2031. }
  2032. }
  2033. m.config.OSPFInterfaces = newInterfaces
  2034. if err := m.save(); err != nil {
  2035. return err
  2036. }
  2037. return m.applyBirdConfig()
  2038. }
  2039. func (m *Manager) SetOSPFInterfaceState(id string, disabled bool) error {
  2040. m.mu.Lock()
  2041. defer m.mu.Unlock()
  2042. for i := range m.config.OSPFInterfaces {
  2043. if m.config.OSPFInterfaces[i].ID == id {
  2044. m.config.OSPFInterfaces[i].Disabled = disabled
  2045. break
  2046. }
  2047. }
  2048. if err := m.save(); err != nil {
  2049. return err
  2050. }
  2051. return m.applyBirdConfig()
  2052. }
  2053. func (m *Manager) GetOSPFInterfacesLive() []OSPFInterfaceLive {
  2054. var list []OSPFInterfaceLive
  2055. out, err := birdcExec("show ospf interface")
  2056. if err != nil {
  2057. return list
  2058. }
  2059. lines := strings.Split(string(out), "\n")
  2060. var cur *OSPFInterfaceLive
  2061. for _, line := range lines {
  2062. trimmed := strings.TrimSpace(line)
  2063. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasSuffix(trimmed, ":") {
  2064. continue
  2065. }
  2066. if strings.HasPrefix(trimmed, "Interface ") {
  2067. if cur != nil {
  2068. list = append(list, *cur)
  2069. }
  2070. parts := strings.SplitN(strings.TrimPrefix(trimmed, "Interface "), " ", 2)
  2071. ifName := parts[0]
  2072. addr := ""
  2073. if len(parts) > 1 {
  2074. addr = strings.Trim(parts[1], "()")
  2075. }
  2076. cur = &OSPFInterfaceLive{
  2077. Flags: "D",
  2078. Interface: ifName,
  2079. Address: addr,
  2080. Area: "Default",
  2081. InstanceID: 0,
  2082. Cost: 1,
  2083. Priority: 128,
  2084. State: "waiting",
  2085. }
  2086. continue
  2087. }
  2088. if cur == nil {
  2089. continue
  2090. }
  2091. if strings.HasPrefix(trimmed, "Area: ") {
  2092. val := strings.TrimPrefix(trimmed, "Area: ")
  2093. areaParts := strings.Fields(val)
  2094. if len(areaParts) > 0 {
  2095. cur.Area = areaParts[0]
  2096. }
  2097. } else if strings.HasPrefix(trimmed, "State: ") {
  2098. cur.State = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(trimmed, "State: ")))
  2099. } else if strings.HasPrefix(trimmed, "Priority: ") {
  2100. fmt.Sscanf(strings.TrimPrefix(trimmed, "Priority: "), "%d", &cur.Priority)
  2101. } else if strings.HasPrefix(trimmed, "Cost: ") {
  2102. fmt.Sscanf(strings.TrimPrefix(trimmed, "Cost: "), "%d", &cur.Cost)
  2103. }
  2104. }
  2105. if cur != nil {
  2106. list = append(list, *cur)
  2107. }
  2108. return list
  2109. }
  2110. func (m *Manager) ListOSPFStaticNeighbors() []OSPFStaticNeighbor {
  2111. m.mu.RLock()
  2112. defer m.mu.RUnlock()
  2113. return m.config.OSPFStaticNbrs
  2114. }
  2115. func (m *Manager) SaveOSPFStaticNeighbor(nbr OSPFStaticNeighbor) error {
  2116. m.mu.Lock()
  2117. defer m.mu.Unlock()
  2118. if nbr.ID == "" {
  2119. nbr.ID = fmt.Sprintf("snbr-%d", time.Now().UnixNano())
  2120. }
  2121. if nbr.Area == "" {
  2122. nbr.Area = "Default"
  2123. }
  2124. found := false
  2125. for i, item := range m.config.OSPFStaticNbrs {
  2126. if item.ID == nbr.ID {
  2127. m.config.OSPFStaticNbrs[i] = nbr
  2128. found = true
  2129. break
  2130. }
  2131. }
  2132. if !found {
  2133. m.config.OSPFStaticNbrs = append(m.config.OSPFStaticNbrs, nbr)
  2134. }
  2135. if err := m.save(); err != nil {
  2136. return err
  2137. }
  2138. return m.applyBirdConfig()
  2139. }
  2140. func (m *Manager) DeleteOSPFStaticNeighbor(id string) error {
  2141. m.mu.Lock()
  2142. defer m.mu.Unlock()
  2143. newNbrs := make([]OSPFStaticNeighbor, 0, len(m.config.OSPFStaticNbrs))
  2144. for _, item := range m.config.OSPFStaticNbrs {
  2145. if item.ID != id {
  2146. newNbrs = append(newNbrs, item)
  2147. }
  2148. }
  2149. m.config.OSPFStaticNbrs = newNbrs
  2150. if err := m.save(); err != nil {
  2151. return err
  2152. }
  2153. return m.applyBirdConfig()
  2154. }
  2155. func (m *Manager) SetOSPFStaticNeighborState(id string, disabled bool) error {
  2156. m.mu.Lock()
  2157. defer m.mu.Unlock()
  2158. for i := range m.config.OSPFStaticNbrs {
  2159. if m.config.OSPFStaticNbrs[i].ID == id {
  2160. m.config.OSPFStaticNbrs[i].Disabled = disabled
  2161. if err := m.save(); err != nil {
  2162. return err
  2163. }
  2164. return m.applyBirdConfig()
  2165. }
  2166. }
  2167. return fmt.Errorf("static neighbor %s not found", id)
  2168. }
  2169. func (m *Manager) GetOSPFNeighbors() []OSPFNeighbor {
  2170. var neighbors []OSPFNeighbor
  2171. out, err := birdcExec("show ospf neighbors")
  2172. if err != nil {
  2173. return neighbors
  2174. }
  2175. lines := strings.Split(string(out), "\n")
  2176. for _, line := range lines {
  2177. trimmed := strings.TrimSpace(line)
  2178. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Router ID") || strings.HasSuffix(trimmed, ":") {
  2179. continue
  2180. }
  2181. fields := strings.Fields(trimmed)
  2182. if len(fields) >= 5 {
  2183. rID := fields[0]
  2184. pri := 0
  2185. fmt.Sscanf(fields[1], "%d", &pri)
  2186. rawState := fields[2]
  2187. state := rawState
  2188. if idx := strings.Index(rawState, "/"); idx != -1 {
  2189. state = rawState[:idx]
  2190. }
  2191. dTime := fields[3]
  2192. iface := fields[4]
  2193. ip := rID
  2194. if len(fields) >= 6 {
  2195. ip = fields[5]
  2196. }
  2197. neighbors = append(neighbors, OSPFNeighbor{
  2198. Flags: "D",
  2199. Comment: "",
  2200. Instance: "Default",
  2201. Area: "Default",
  2202. Address: ip,
  2203. State: state,
  2204. StateChanges: 6,
  2205. NeighborID: rID,
  2206. Interface: iface,
  2207. DeadTimer: dTime,
  2208. Priority: pri,
  2209. })
  2210. }
  2211. }
  2212. return neighbors
  2213. }
  2214. func (m *Manager) GetOSPFLSA() []OSPFLSA {
  2215. var lsaList []OSPFLSA
  2216. out, err := birdcExec("show ospf lsadb")
  2217. if err != nil {
  2218. return lsaList
  2219. }
  2220. localRouterID := "192.168.131.56"
  2221. if len(m.config.OSPFInstances) > 0 && m.config.OSPFInstances[0].RouterID != "" {
  2222. localRouterID = m.config.OSPFInstances[0].RouterID
  2223. }
  2224. lines := strings.Split(string(out), "\n")
  2225. currentArea := "Default"
  2226. for _, line := range lines {
  2227. trimmed := strings.TrimSpace(line)
  2228. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") {
  2229. continue
  2230. }
  2231. if strings.HasPrefix(trimmed, "Area ") {
  2232. currentArea = strings.TrimSpace(strings.TrimPrefix(trimmed, "Area "))
  2233. continue
  2234. } else if strings.EqualFold(trimmed, "Global") {
  2235. currentArea = "Default"
  2236. continue
  2237. }
  2238. if strings.HasPrefix(trimmed, "Type") || strings.HasPrefix(trimmed, "ospf_") {
  2239. continue
  2240. }
  2241. fields := strings.Fields(trimmed)
  2242. if len(fields) >= 5 {
  2243. rawType := fields[0]
  2244. typeName := "router"
  2245. switch rawType {
  2246. case "0001":
  2247. typeName = "router"
  2248. case "0002":
  2249. typeName = "network"
  2250. case "0003":
  2251. typeName = "summary-net"
  2252. case "0004":
  2253. typeName = "summary-asbr"
  2254. case "0005":
  2255. typeName = "as-external"
  2256. default:
  2257. typeName = rawType
  2258. }
  2259. lsID := fields[1]
  2260. router := fields[2]
  2261. seq := fields[3]
  2262. age := 0
  2263. fmt.Sscanf(fields[4], "%d", &age)
  2264. flags := "D"
  2265. if router == localRouterID {
  2266. flags = "SD"
  2267. }
  2268. lsaList = append(lsaList, OSPFLSA{
  2269. Flags: flags,
  2270. Instance: "Default",
  2271. Area: currentArea,
  2272. Type: typeName,
  2273. Originator: router,
  2274. ID: lsID,
  2275. Link: "",
  2276. LinkIndex: 0,
  2277. Sequence: seq,
  2278. Age: age,
  2279. })
  2280. }
  2281. }
  2282. return lsaList
  2283. }
  2284. func (m *Manager) GetOSPFRoutes() []OSPFRoute {
  2285. var routes []OSPFRoute
  2286. out, err := birdcExec("show route where source = RTS_OSPF all")
  2287. if err != nil {
  2288. return routes
  2289. }
  2290. lines := strings.Split(string(out), "\n")
  2291. var cur *OSPFRoute
  2292. for _, line := range lines {
  2293. trimmed := strings.TrimSpace(line)
  2294. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  2295. continue
  2296. }
  2297. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  2298. fields := strings.Fields(trimmed)
  2299. if len(fields) >= 2 {
  2300. cost := 10
  2301. if idx := strings.Index(line, "/"); idx != -1 {
  2302. sub := line[idx+1:]
  2303. if end := strings.Index(sub, ")"); end != -1 {
  2304. cost, _ = strconv.Atoi(sub[:end])
  2305. }
  2306. }
  2307. routes = append(routes, OSPFRoute{
  2308. Prefix: fields[0],
  2309. Cost: cost,
  2310. RouteType: "Intra-Area",
  2311. })
  2312. cur = &routes[len(routes)-1]
  2313. }
  2314. continue
  2315. }
  2316. if cur == nil {
  2317. continue
  2318. }
  2319. if strings.HasPrefix(trimmed, "via ") {
  2320. parts := strings.Fields(trimmed)
  2321. if len(parts) >= 2 {
  2322. cur.NextHop = parts[1]
  2323. }
  2324. if len(parts) >= 4 && parts[2] == "on" {
  2325. cur.Interface = parts[3]
  2326. }
  2327. } else if strings.HasPrefix(trimmed, "Type:") {
  2328. cur.RouteType = strings.TrimSpace(strings.TrimPrefix(trimmed, "Type:"))
  2329. }
  2330. }
  2331. return routes
  2332. }
  2333. // -------------------------------------------------------------
  2334. // Routing Filter API & Operations (/routing filter)
  2335. // -------------------------------------------------------------
  2336. func (m *Manager) ListRoutingFilters() []RoutingFilterRule {
  2337. m.mu.RLock()
  2338. defer m.mu.RUnlock()
  2339. filters := make([]RoutingFilterRule, len(m.config.RoutingFilters))
  2340. copy(filters, m.config.RoutingFilters)
  2341. return filters
  2342. }
  2343. func (m *Manager) SaveRoutingFilter(rule *RoutingFilterRule) error {
  2344. m.mu.Lock()
  2345. if rule.ID == "" {
  2346. rule.ID = fmt.Sprintf("rf-%d", time.Now().UnixNano()/1e6)
  2347. }
  2348. if rule.RuleOrder <= 0 {
  2349. rule.RuleOrder = (len(m.config.RoutingFilters) + 1) * 10
  2350. }
  2351. found := false
  2352. for i, r := range m.config.RoutingFilters {
  2353. if r.ID == rule.ID {
  2354. m.config.RoutingFilters[i] = *rule
  2355. found = true
  2356. break
  2357. }
  2358. }
  2359. if !found {
  2360. m.config.RoutingFilters = append(m.config.RoutingFilters, *rule)
  2361. }
  2362. _ = m.save()
  2363. m.mu.Unlock()
  2364. return m.applyBirdConfig()
  2365. }
  2366. func (m *Manager) DeleteRoutingFilter(id string) error {
  2367. m.mu.Lock()
  2368. newRules := make([]RoutingFilterRule, 0, len(m.config.RoutingFilters))
  2369. for _, r := range m.config.RoutingFilters {
  2370. if r.ID != id {
  2371. newRules = append(newRules, r)
  2372. }
  2373. }
  2374. m.config.RoutingFilters = newRules
  2375. _ = m.save()
  2376. m.mu.Unlock()
  2377. return m.applyBirdConfig()
  2378. }
  2379. func (m *Manager) SetRoutingFilterState(id string, disabled bool) error {
  2380. m.mu.Lock()
  2381. for i := range m.config.RoutingFilters {
  2382. if m.config.RoutingFilters[i].ID == id {
  2383. m.config.RoutingFilters[i].Disabled = disabled
  2384. break
  2385. }
  2386. }
  2387. _ = m.save()
  2388. m.mu.Unlock()
  2389. return m.applyBirdConfig()
  2390. }
  2391. func (m *Manager) MoveRoutingFilter(id string, direction string) error {
  2392. m.mu.Lock()
  2393. defer m.mu.Unlock()
  2394. var targetRule *RoutingFilterRule
  2395. for i := range m.config.RoutingFilters {
  2396. if m.config.RoutingFilters[i].ID == id {
  2397. targetRule = &m.config.RoutingFilters[i]
  2398. break
  2399. }
  2400. }
  2401. if targetRule == nil {
  2402. return fmt.Errorf("routing filter rule not found: %s", id)
  2403. }
  2404. chain := targetRule.Chain
  2405. dir := strings.ToLower(strings.TrimSpace(direction))
  2406. if dir != "up" && dir != "down" {
  2407. return fmt.Errorf("invalid direction %q: must be 'up' or 'down'", direction)
  2408. }
  2409. type chainItem struct {
  2410. globalIndex int
  2411. rule RoutingFilterRule
  2412. }
  2413. var items []chainItem
  2414. for i, r := range m.config.RoutingFilters {
  2415. if r.Chain == chain {
  2416. items = append(items, chainItem{globalIndex: i, rule: r})
  2417. }
  2418. }
  2419. sort.SliceStable(items, func(i, j int) bool {
  2420. return items[i].rule.RuleOrder < items[j].rule.RuleOrder
  2421. })
  2422. chainIdx := -1
  2423. for i, it := range items {
  2424. if it.rule.ID == id {
  2425. chainIdx = i
  2426. break
  2427. }
  2428. }
  2429. if chainIdx == -1 {
  2430. return fmt.Errorf("rule not found in chain")
  2431. }
  2432. targetIdx := chainIdx
  2433. if dir == "up" {
  2434. targetIdx = chainIdx - 1
  2435. } else if dir == "down" {
  2436. targetIdx = chainIdx + 1
  2437. }
  2438. if targetIdx < 0 || targetIdx >= len(items) {
  2439. // Already at boundary, normalize order and return
  2440. for i, it := range items {
  2441. m.config.RoutingFilters[it.globalIndex].RuleOrder = (i + 1) * 10
  2442. }
  2443. _ = m.save()
  2444. return nil
  2445. }
  2446. // Swap positions in the sorted chain list
  2447. items[chainIdx], items[targetIdx] = items[targetIdx], items[chainIdx]
  2448. // Reassign spaced rule_order values (10, 20, 30...)
  2449. for i, it := range items {
  2450. m.config.RoutingFilters[it.globalIndex].RuleOrder = (i + 1) * 10
  2451. }
  2452. _ = m.save()
  2453. return m.applyBirdConfig()
  2454. }
  2455. // translateRos7RuleToBird converts a RouterOS v7 rule script (or fallback fields) to valid BIRD 2 syntax
  2456. func translateRos7RuleToBird(r *RoutingFilterRule) string {
  2457. script := strings.TrimSpace(r.Rule)
  2458. if script != "" {
  2459. s := script
  2460. // 0. Convert double-equals (==) to single-equals (=) for BIRD 2, preserving !=, <=, >=, ~=
  2461. reDoubleEq := regexp.MustCompile(`([^!<>~=])\s*==\s*([^=])`)
  2462. for reDoubleEq.MatchString(s) {
  2463. s = reDoubleEq.ReplaceAllString(s, "$1 = $2")
  2464. }
  2465. // 1. Convert dst in A.B.C.D/M{L,H} -> net ~ [ A.B.C.D/M{L,H} ]
  2466. reDstRange := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)\{([0-9]+),([0-9]+)\}`)
  2467. s = reDstRange.ReplaceAllString(s, "net ~ [ $1{$2,$3} ]")
  2468. // 2. Convert dst in A.B.C.D/M -> net ~ [ A.B.C.D/M+ ]
  2469. reDstIn := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)`)
  2470. s = reDstIn.ReplaceAllString(s, "net ~ [ $1+ ]")
  2471. // 3. Convert dst = A.B.C.D/M or dst == A.B.C.D/M -> net = A.B.C.D/M
  2472. reDstEq := regexp.MustCompile(`\bdst\s*=\s*([0-9\.\/]+)`)
  2473. s = reDstEq.ReplaceAllString(s, "net = $1")
  2474. // 4. Convert dst != A.B.C.D/M -> net != A.B.C.D/M
  2475. reDstNeq := regexp.MustCompile(`\bdst\s*!=\s*([0-9\.\/]+)`)
  2476. s = reDstNeq.ReplaceAllString(s, "net != $1")
  2477. // 5. Convert dst-len -> net.len
  2478. s = regexp.MustCompile(`\bdst-len\b`).ReplaceAllString(s, "net.len")
  2479. // 6. Convert protocol matches
  2480. s = regexp.MustCompile(`protocol\s+bgp\b`).ReplaceAllString(s, "source = RTS_BGP")
  2481. s = regexp.MustCompile(`protocol\s+ospf\b`).ReplaceAllString(s, "source = RTS_OSPF")
  2482. s = regexp.MustCompile(`protocol\s+connected\b`).ReplaceAllString(s, "source = RTS_DEVICE")
  2483. s = regexp.MustCompile(`protocol\s+static\b`).ReplaceAllString(s, "source = RTS_STATIC")
  2484. s = regexp.MustCompile(`protocol\s+rip\b`).ReplaceAllString(s, "source = RTS_RIP")
  2485. // 7. Convert bgp-communities includes A:B -> (A, B) ~ bgp_community
  2486. reCommInc := regexp.MustCompile(`bgp-communities\s+includes\s+([0-9]+):([0-9]+)`)
  2487. s = reCommInc.ReplaceAllString(s, "($1, $2) ~ bgp_community")
  2488. // 8. Convert bgp-communities (in|equal-list) ListName -> bgp_community ~ comm_ListName
  2489. reCommList := regexp.MustCompile(`bgp-communities\s+(?:in|equal-list)\s+([A-Za-z0-9_]+)`)
  2490. s = reCommList.ReplaceAllString(s, "bgp_community ~ comm_$1")
  2491. // 9. Convert bgp-as-path in ListName -> bgp_path.last ~ aslist_ListName
  2492. reASList := regexp.MustCompile(`bgp-as-path\s+in\s+([A-Za-z0-9_]+)`)
  2493. s = reASList.ReplaceAllString(s, "bgp_path.last ~ aslist_$1")
  2494. // 10. Convert bgp-as-path "pattern" -> bgp_path ~ [= * pattern * =]
  2495. reASPattern := regexp.MustCompile(`bgp-as-path\s+"([^"]+)"`)
  2496. s = reASPattern.ReplaceAllStringFunc(s, func(match string) string {
  2497. sub := reASPattern.FindStringSubmatch(match)
  2498. if len(sub) == 2 {
  2499. pat := strings.Trim(sub[1], "^$")
  2500. return fmt.Sprintf("bgp_path ~ [= * %s * =]", pat)
  2501. }
  2502. return match
  2503. })
  2504. // 11. Convert actions:
  2505. reSetLP := regexp.MustCompile(`set\s+bgp-local-pref\s*=?\s*([0-9]+);?`)
  2506. s = reSetLP.ReplaceAllString(s, "bgp_local_pref = $1;")
  2507. reSetMed := regexp.MustCompile(`set\s+bgp-med\s*=?\s*([0-9]+);?`)
  2508. s = reSetMed.ReplaceAllString(s, "bgp_med = $1;")
  2509. reSetDist := regexp.MustCompile(`set\s+distance\s*=?\s*([0-9]+);?`)
  2510. s = reSetDist.ReplaceAllString(s, "preference = $1;")
  2511. reSetGW := regexp.MustCompile(`set\s+gw\s*=?\s*([0-9\.]+);?`)
  2512. s = reSetGW.ReplaceAllString(s, "gw = $1;")
  2513. reSetPrepend := regexp.MustCompile(`set\s+bgp-path-prepend\s*=?\s*([0-9]+);?`)
  2514. s = reSetPrepend.ReplaceAllStringFunc(s, func(match string) string {
  2515. sub := reSetPrepend.FindStringSubmatch(match)
  2516. if len(sub) == 2 {
  2517. n, _ := strconv.Atoi(sub[1])
  2518. if n > 0 && n <= 10 {
  2519. var b strings.Builder
  2520. for i := 0; i < n; i++ {
  2521. b.WriteString("bgp_path.prepend(bgp_path.first); ")
  2522. }
  2523. return b.String()
  2524. } else if n > 10 {
  2525. return fmt.Sprintf("bgp_path.prepend(%d);", n)
  2526. }
  2527. }
  2528. return match
  2529. })
  2530. reSetCommAdd := regexp.MustCompile(`set\s+bgp-communities\.add\s+([0-9]+):([0-9]+);?`)
  2531. s = reSetCommAdd.ReplaceAllString(s, "bgp_community.add(($1, $2));")
  2532. reSetCommDel := regexp.MustCompile(`set\s+bgp-communities\.delete\s+([0-9]+):([0-9]+);?`)
  2533. s = reSetCommDel.ReplaceAllString(s, "bgp_community.delete(($1, $2));")
  2534. // Ensure semicolons on accept and reject
  2535. s = regexp.MustCompile(`\baccept(?:\s*;)?`).ReplaceAllString(s, "accept;")
  2536. s = regexp.MustCompile(`\b(reject|discard)(?:\s*;)?`).ReplaceAllString(s, "reject;")
  2537. // Convert passthrough keyword to no-op
  2538. s = regexp.MustCompile(`\bpassthrough(?:\s*;)?`).ReplaceAllString(s, "")
  2539. // Ensure "then" before opening brace of if statement
  2540. reIfThen := regexp.MustCompile(`\)\s*\{`)
  2541. s = reIfThen.ReplaceAllString(s, ") then {")
  2542. s = strings.ReplaceAll(s, ") then then {", ") then {")
  2543. // If rule was a bare condition (no if, no accept/reject/action statement), wrap it with Action if specified
  2544. if !strings.HasPrefix(strings.TrimSpace(s), "if ") && !strings.Contains(s, "then") && !strings.Contains(s, "accept") && !strings.Contains(s, "reject") {
  2545. act := strings.TrimSpace(r.Action)
  2546. if act == "" {
  2547. act = "accept"
  2548. }
  2549. s = fmt.Sprintf("if %s then { %s; }", s, act)
  2550. }
  2551. return s
  2552. }
  2553. // Fallback for rules configured with structured UI form
  2554. var conditions []string
  2555. if r.Prefix != "" {
  2556. pfx := strings.TrimSpace(r.Prefix)
  2557. pfxLen := strings.TrimSpace(r.PrefixLen)
  2558. if pfxLen != "" {
  2559. if strings.Contains(pfxLen, "-") {
  2560. parts := strings.Split(pfxLen, "-")
  2561. if len(parts) == 2 {
  2562. conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,%s} ]", pfx, strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
  2563. }
  2564. } else {
  2565. conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,32} ]", pfx, pfxLen))
  2566. }
  2567. } else {
  2568. conditions = append(conditions, fmt.Sprintf("net ~ [ %s+ ]", pfx))
  2569. }
  2570. }
  2571. if r.MatchProtocol != "" && r.MatchProtocol != "any" {
  2572. switch strings.ToLower(r.MatchProtocol) {
  2573. case "bgp":
  2574. conditions = append(conditions, "source = RTS_BGP")
  2575. case "ospf":
  2576. conditions = append(conditions, "source = RTS_OSPF")
  2577. case "connected":
  2578. conditions = append(conditions, "source = RTS_DEVICE")
  2579. case "static":
  2580. conditions = append(conditions, "source = RTS_STATIC")
  2581. }
  2582. }
  2583. if r.MatchASPath != "" {
  2584. conditions = append(conditions, fmt.Sprintf("bgp_path ~ [= * %s * =]", strings.Trim(strings.TrimSpace(r.MatchASPath), "^$")))
  2585. }
  2586. if r.MatchCommunity != "" {
  2587. comm := strings.TrimSpace(r.MatchCommunity)
  2588. if strings.Contains(comm, ":") {
  2589. parts := strings.Split(comm, ":")
  2590. conditions = append(conditions, fmt.Sprintf("(%s, %s) ~ bgp_community", parts[0], parts[1]))
  2591. }
  2592. }
  2593. condStr := "true"
  2594. if len(conditions) > 0 {
  2595. condStr = strings.Join(conditions, " && ")
  2596. }
  2597. var sb strings.Builder
  2598. sb.WriteString(fmt.Sprintf("if %s then {\n", condStr))
  2599. if r.SetLocalPref > 0 {
  2600. sb.WriteString(fmt.Sprintf(" bgp_local_pref = %d;\n", r.SetLocalPref))
  2601. }
  2602. if r.SetMetric > 0 {
  2603. sb.WriteString(fmt.Sprintf(" bgp_med = %d;\n", r.SetMetric))
  2604. }
  2605. if r.SetASPrepend > 0 {
  2606. for i := 0; i < r.SetASPrepend; i++ {
  2607. sb.WriteString(" bgp_path.prepend(bgp_path.first);\n")
  2608. }
  2609. }
  2610. if r.SetCommunity != "" {
  2611. comm := strings.TrimSpace(r.SetCommunity)
  2612. if strings.Contains(comm, ":") {
  2613. parts := strings.Split(comm, ":")
  2614. sb.WriteString(fmt.Sprintf(" bgp_community.add((%s, %s));\n", parts[0], parts[1]))
  2615. }
  2616. }
  2617. if r.SetNextHop != "" {
  2618. sb.WriteString(fmt.Sprintf(" bgp_next_hop = %s;\n", strings.TrimSpace(r.SetNextHop)))
  2619. }
  2620. if r.SetDistance > 0 {
  2621. sb.WriteString(fmt.Sprintf(" preference = %d;\n", r.SetDistance))
  2622. }
  2623. if r.Action == "discard" || r.Action == "reject" {
  2624. sb.WriteString(" reject;\n")
  2625. } else if r.Action == "passthrough" {
  2626. // Passthrough: do not emit terminating accept or reject
  2627. } else {
  2628. sb.WriteString(" accept;\n")
  2629. }
  2630. sb.WriteString("}")
  2631. return sb.String()
  2632. }
  2633. // -------------------------------------------------------------
  2634. // Community Lists (/routing filter community-list)
  2635. // -------------------------------------------------------------
  2636. func (m *Manager) ListCommunityLists() []RoutingFilterCommunityList {
  2637. m.mu.RLock()
  2638. defer m.mu.RUnlock()
  2639. res := make([]RoutingFilterCommunityList, len(m.config.RoutingCommunityLists))
  2640. copy(res, m.config.RoutingCommunityLists)
  2641. return res
  2642. }
  2643. func (m *Manager) SaveCommunityList(cl *RoutingFilterCommunityList) error {
  2644. m.mu.Lock()
  2645. if cl.ID == "" {
  2646. cl.ID = fmt.Sprintf("cl-%d", time.Now().UnixNano()/1e6)
  2647. }
  2648. found := false
  2649. for i, r := range m.config.RoutingCommunityLists {
  2650. if r.ID == cl.ID {
  2651. m.config.RoutingCommunityLists[i] = *cl
  2652. found = true
  2653. break
  2654. }
  2655. }
  2656. if !found {
  2657. m.config.RoutingCommunityLists = append(m.config.RoutingCommunityLists, *cl)
  2658. }
  2659. _ = m.save()
  2660. m.mu.Unlock()
  2661. return m.applyBirdConfig()
  2662. }
  2663. func (m *Manager) DeleteCommunityList(id string) error {
  2664. m.mu.Lock()
  2665. newLists := make([]RoutingFilterCommunityList, 0, len(m.config.RoutingCommunityLists))
  2666. for _, r := range m.config.RoutingCommunityLists {
  2667. if r.ID != id {
  2668. newLists = append(newLists, r)
  2669. }
  2670. }
  2671. m.config.RoutingCommunityLists = newLists
  2672. _ = m.save()
  2673. m.mu.Unlock()
  2674. return m.applyBirdConfig()
  2675. }
  2676. func (m *Manager) SetCommunityListState(id string, disabled bool) error {
  2677. m.mu.Lock()
  2678. for i := range m.config.RoutingCommunityLists {
  2679. if m.config.RoutingCommunityLists[i].ID == id {
  2680. m.config.RoutingCommunityLists[i].Disabled = disabled
  2681. break
  2682. }
  2683. }
  2684. _ = m.save()
  2685. m.mu.Unlock()
  2686. return m.applyBirdConfig()
  2687. }
  2688. // -------------------------------------------------------------
  2689. // AS Lists (/routing filter num-list)
  2690. // -------------------------------------------------------------
  2691. func (m *Manager) ListASLists() []RoutingFilterASList {
  2692. m.mu.RLock()
  2693. defer m.mu.RUnlock()
  2694. res := make([]RoutingFilterASList, len(m.config.RoutingASLists))
  2695. copy(res, m.config.RoutingASLists)
  2696. return res
  2697. }
  2698. func (m *Manager) SaveASList(al *RoutingFilterASList) error {
  2699. m.mu.Lock()
  2700. if al.ID == "" {
  2701. al.ID = fmt.Sprintf("al-%d", time.Now().UnixNano()/1e6)
  2702. }
  2703. found := false
  2704. for i, r := range m.config.RoutingASLists {
  2705. if r.ID == al.ID {
  2706. m.config.RoutingASLists[i] = *al
  2707. found = true
  2708. break
  2709. }
  2710. }
  2711. if !found {
  2712. m.config.RoutingASLists = append(m.config.RoutingASLists, *al)
  2713. }
  2714. _ = m.save()
  2715. m.mu.Unlock()
  2716. return m.applyBirdConfig()
  2717. }
  2718. func (m *Manager) DeleteASList(id string) error {
  2719. m.mu.Lock()
  2720. newLists := make([]RoutingFilterASList, 0, len(m.config.RoutingASLists))
  2721. for _, r := range m.config.RoutingASLists {
  2722. if r.ID != id {
  2723. newLists = append(newLists, r)
  2724. }
  2725. }
  2726. m.config.RoutingASLists = newLists
  2727. _ = m.save()
  2728. m.mu.Unlock()
  2729. return m.applyBirdConfig()
  2730. }
  2731. func (m *Manager) SetASListState(id string, disabled bool) error {
  2732. m.mu.Lock()
  2733. for i := range m.config.RoutingASLists {
  2734. if m.config.RoutingASLists[i].ID == id {
  2735. m.config.RoutingASLists[i].Disabled = disabled
  2736. break
  2737. }
  2738. }
  2739. _ = m.save()
  2740. m.mu.Unlock()
  2741. return m.applyBirdConfig()
  2742. }
  2743. // -------------------------------------------------------------
  2744. // RIP Methods (/routing rip)
  2745. // -------------------------------------------------------------
  2746. func (m *Manager) ListRIPInstances() []RIPInstance {
  2747. m.mu.RLock()
  2748. defer m.mu.RUnlock()
  2749. out, err := birdcExec("show protocols")
  2750. protocols := map[string]bool{}
  2751. birdRunning := false
  2752. if err == nil {
  2753. birdRunning = strings.Contains(string(out), "BIRD")
  2754. for _, line := range strings.Split(string(out), "\n") {
  2755. fields := strings.Fields(line)
  2756. if len(fields) >= 4 && (fields[1] == "RIP" || strings.HasPrefix(fields[0], "rip_")) {
  2757. protocols[fields[0]] = fields[3] == "up"
  2758. }
  2759. }
  2760. }
  2761. res := make([]RIPInstance, len(m.config.RIPInstances))
  2762. copy(res, m.config.RIPInstances)
  2763. for i := range res {
  2764. protoName := sanitizeIdentifier("rip", fmt.Sprintf("%s_%d", res[i].Name, i))
  2765. isProtoUp := protocols[protoName] || protocols[sanitizeIdentifier("rip", res[i].Name)]
  2766. res[i].Running = (isProtoUp || (birdRunning && (res[i].Enabled || !res[i].Disabled))) && !res[i].Disabled
  2767. res[i].Enabled = !res[i].Disabled
  2768. }
  2769. return res
  2770. }
  2771. func (m *Manager) SaveRIPInstance(inst RIPInstance) (*RIPInstance, error) {
  2772. m.mu.Lock()
  2773. defer m.mu.Unlock()
  2774. if !inst.Disabled {
  2775. inst.Enabled = true
  2776. } else {
  2777. inst.Enabled = false
  2778. }
  2779. if inst.ID == "" {
  2780. inst.ID = fmt.Sprintf("rip-inst-%d", time.Now().UnixNano())
  2781. }
  2782. if inst.Name == "" {
  2783. inst.Name = "default"
  2784. }
  2785. if inst.Version == 0 {
  2786. inst.Version = 2
  2787. }
  2788. if inst.UpdateTime == 0 {
  2789. inst.UpdateTime = 30
  2790. }
  2791. if inst.TimeoutTime == 0 {
  2792. inst.TimeoutTime = 180
  2793. }
  2794. if inst.GarbageTime == 0 {
  2795. inst.GarbageTime = 120
  2796. }
  2797. found := false
  2798. for i, existing := range m.config.RIPInstances {
  2799. if existing.ID == inst.ID || strings.EqualFold(existing.Name, inst.Name) {
  2800. m.config.RIPInstances[i] = inst
  2801. found = true
  2802. break
  2803. }
  2804. }
  2805. if !found {
  2806. m.config.RIPInstances = append(m.config.RIPInstances, inst)
  2807. }
  2808. if err := m.save(); err != nil {
  2809. return nil, err
  2810. }
  2811. if err := m.applyBirdConfig(); err != nil {
  2812. return nil, err
  2813. }
  2814. return &inst, nil
  2815. }
  2816. func (m *Manager) DeleteRIPInstance(id string) error {
  2817. m.mu.Lock()
  2818. defer m.mu.Unlock()
  2819. newInsts := make([]RIPInstance, 0, len(m.config.RIPInstances))
  2820. for _, inst := range m.config.RIPInstances {
  2821. if inst.ID != id && inst.Name != id {
  2822. newInsts = append(newInsts, inst)
  2823. }
  2824. }
  2825. m.config.RIPInstances = newInsts
  2826. if err := m.save(); err != nil {
  2827. return err
  2828. }
  2829. return m.applyBirdConfig()
  2830. }
  2831. func (m *Manager) SetRIPInstanceState(id string, disabled bool) error {
  2832. m.mu.Lock()
  2833. defer m.mu.Unlock()
  2834. for i := range m.config.RIPInstances {
  2835. if m.config.RIPInstances[i].ID == id || m.config.RIPInstances[i].Name == id {
  2836. m.config.RIPInstances[i].Disabled = disabled
  2837. m.config.RIPInstances[i].Enabled = !disabled
  2838. break
  2839. }
  2840. }
  2841. if err := m.save(); err != nil {
  2842. return err
  2843. }
  2844. return m.applyBirdConfig()
  2845. }
  2846. func (m *Manager) ListRIPInterfaces() []RIPInterface {
  2847. m.mu.RLock()
  2848. defer m.mu.RUnlock()
  2849. res := make([]RIPInterface, len(m.config.RIPInterfaces))
  2850. copy(res, m.config.RIPInterfaces)
  2851. return res
  2852. }
  2853. func (m *Manager) SaveRIPInterface(iface RIPInterface) (*RIPInterface, error) {
  2854. m.mu.Lock()
  2855. defer m.mu.Unlock()
  2856. if iface.ID == "" {
  2857. iface.ID = fmt.Sprintf("rip-iface-%d", time.Now().UnixNano())
  2858. }
  2859. if iface.Interface == "" {
  2860. iface.Interface = "*"
  2861. }
  2862. if iface.Metric == 0 {
  2863. iface.Metric = 1
  2864. }
  2865. found := false
  2866. for i, existing := range m.config.RIPInterfaces {
  2867. if existing.ID == iface.ID {
  2868. m.config.RIPInterfaces[i] = iface
  2869. found = true
  2870. break
  2871. }
  2872. }
  2873. if !found {
  2874. m.config.RIPInterfaces = append(m.config.RIPInterfaces, iface)
  2875. }
  2876. if err := m.save(); err != nil {
  2877. return nil, err
  2878. }
  2879. if err := m.applyBirdConfig(); err != nil {
  2880. return nil, err
  2881. }
  2882. return &iface, nil
  2883. }
  2884. func (m *Manager) DeleteRIPInterface(id string) error {
  2885. m.mu.Lock()
  2886. defer m.mu.Unlock()
  2887. newIfaces := make([]RIPInterface, 0, len(m.config.RIPInterfaces))
  2888. for _, iface := range m.config.RIPInterfaces {
  2889. if iface.ID != id && iface.Interface != id {
  2890. newIfaces = append(newIfaces, iface)
  2891. }
  2892. }
  2893. m.config.RIPInterfaces = newIfaces
  2894. if err := m.save(); err != nil {
  2895. return err
  2896. }
  2897. return m.applyBirdConfig()
  2898. }
  2899. func (m *Manager) SetRIPInterfaceState(id string, disabled bool) error {
  2900. m.mu.Lock()
  2901. defer m.mu.Unlock()
  2902. for i := range m.config.RIPInterfaces {
  2903. if m.config.RIPInterfaces[i].ID == id || m.config.RIPInterfaces[i].Interface == id {
  2904. m.config.RIPInterfaces[i].Disabled = disabled
  2905. break
  2906. }
  2907. }
  2908. if err := m.save(); err != nil {
  2909. return err
  2910. }
  2911. return m.applyBirdConfig()
  2912. }
  2913. func (m *Manager) ListRIPNeighbors() []RIPNeighbor {
  2914. m.mu.RLock()
  2915. defer m.mu.RUnlock()
  2916. res := make([]RIPNeighbor, len(m.config.RIPNeighbors))
  2917. copy(res, m.config.RIPNeighbors)
  2918. return res
  2919. }
  2920. func (m *Manager) SaveRIPNeighbor(nbr RIPNeighbor) (*RIPNeighbor, error) {
  2921. m.mu.Lock()
  2922. defer m.mu.Unlock()
  2923. if nbr.ID == "" {
  2924. nbr.ID = fmt.Sprintf("rip-nbr-%d", time.Now().UnixNano())
  2925. }
  2926. found := false
  2927. for i, existing := range m.config.RIPNeighbors {
  2928. if existing.ID == nbr.ID || existing.Address == nbr.Address {
  2929. m.config.RIPNeighbors[i] = nbr
  2930. found = true
  2931. break
  2932. }
  2933. }
  2934. if !found {
  2935. m.config.RIPNeighbors = append(m.config.RIPNeighbors, nbr)
  2936. }
  2937. if err := m.save(); err != nil {
  2938. return nil, err
  2939. }
  2940. if err := m.applyBirdConfig(); err != nil {
  2941. return nil, err
  2942. }
  2943. return &nbr, nil
  2944. }
  2945. func (m *Manager) DeleteRIPNeighbor(id string) error {
  2946. m.mu.Lock()
  2947. defer m.mu.Unlock()
  2948. newNbrs := make([]RIPNeighbor, 0, len(m.config.RIPNeighbors))
  2949. for _, nbr := range m.config.RIPNeighbors {
  2950. if nbr.ID != id && nbr.Address != id {
  2951. newNbrs = append(newNbrs, nbr)
  2952. }
  2953. }
  2954. m.config.RIPNeighbors = newNbrs
  2955. if err := m.save(); err != nil {
  2956. return err
  2957. }
  2958. return m.applyBirdConfig()
  2959. }
  2960. func (m *Manager) GetRIPNeighbors() []RIPNeighborLive {
  2961. var list []RIPNeighborLive
  2962. out, err := birdcExec("show rip neighbors")
  2963. if err != nil {
  2964. return list
  2965. }
  2966. lines := strings.Split(string(out), "\n")
  2967. for _, line := range lines {
  2968. trimmed := strings.TrimSpace(line)
  2969. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "IP address") || strings.Contains(trimmed, "There is no RIP") {
  2970. continue
  2971. }
  2972. fields := strings.Fields(trimmed)
  2973. if len(fields) >= 2 {
  2974. nbr := RIPNeighborLive{
  2975. Address: fields[0],
  2976. Interface: fields[1],
  2977. }
  2978. if len(fields) >= 3 {
  2979. nbr.LastSeen = fields[len(fields)-1]
  2980. }
  2981. list = append(list, nbr)
  2982. }
  2983. }
  2984. return list
  2985. }
  2986. func (m *Manager) GetRIPRoutes() []RIPRoute {
  2987. var routes []RIPRoute
  2988. out, err := birdcExec("show route where source = RTS_RIP all")
  2989. if err != nil {
  2990. return routes
  2991. }
  2992. lines := strings.Split(string(out), "\n")
  2993. var cur *RIPRoute
  2994. for _, line := range lines {
  2995. trimmed := strings.TrimSpace(line)
  2996. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  2997. continue
  2998. }
  2999. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  3000. fields := strings.Fields(trimmed)
  3001. if len(fields) >= 2 {
  3002. routes = append(routes, RIPRoute{
  3003. Prefix: fields[0],
  3004. })
  3005. cur = &routes[len(routes)-1]
  3006. for i := 1; i < len(fields); i++ {
  3007. if fields[i] == "via" && i+1 < len(fields) {
  3008. cur.NextHop = fields[i+1]
  3009. }
  3010. if fields[i] == "dev" && i+1 < len(fields) {
  3011. cur.Interface = fields[i+1]
  3012. }
  3013. }
  3014. }
  3015. } else if cur != nil {
  3016. if strings.Contains(trimmed, "rip_metric:") {
  3017. parts := strings.Split(trimmed, ":")
  3018. if len(parts) >= 2 {
  3019. var mVal int
  3020. fmt.Sscanf(strings.TrimSpace(parts[1]), "%d", &mVal)
  3021. cur.Metric = mVal
  3022. }
  3023. }
  3024. }
  3025. }
  3026. return routes
  3027. }
  3028. // -------------------------------------------------------------
  3029. // BFD Methods (/routing bfd)
  3030. // -------------------------------------------------------------
  3031. func (m *Manager) GetBFDInstance() BFDInstance {
  3032. m.mu.RLock()
  3033. defer m.mu.RUnlock()
  3034. inst := m.config.BFDInstance
  3035. pOut, pErr := birdcExec("show protocols bfd_main")
  3036. bfdUp := pErr == nil && strings.Contains(string(pOut), "up")
  3037. out, err := birdcExec("show status")
  3038. birdRunning := err == nil && strings.Contains(string(out), "Daemon is up and running")
  3039. inst.Running = (bfdUp || (birdRunning && (inst.Enabled || len(m.config.BFDInterfaces) > 0 || len(m.config.BFDNeighbors) > 0))) && !inst.Disabled
  3040. if inst.Running && !inst.Disabled {
  3041. inst.Enabled = true
  3042. }
  3043. return inst
  3044. }
  3045. func (m *Manager) SaveBFDInstance(inst BFDInstance) error {
  3046. m.mu.Lock()
  3047. defer m.mu.Unlock()
  3048. if !inst.Disabled {
  3049. inst.Enabled = true
  3050. } else {
  3051. inst.Enabled = false
  3052. }
  3053. m.config.BFDInstance = inst
  3054. if err := m.save(); err != nil {
  3055. return err
  3056. }
  3057. return m.applyBirdConfig()
  3058. }
  3059. func (m *Manager) ListBFDInterfaces() []BFDInterface {
  3060. m.mu.RLock()
  3061. defer m.mu.RUnlock()
  3062. res := make([]BFDInterface, len(m.config.BFDInterfaces))
  3063. copy(res, m.config.BFDInterfaces)
  3064. return res
  3065. }
  3066. func (m *Manager) SaveBFDInterface(iface BFDInterface) (*BFDInterface, error) {
  3067. m.mu.Lock()
  3068. defer m.mu.Unlock()
  3069. if iface.ID == "" {
  3070. iface.ID = fmt.Sprintf("bfd-iface-%d", time.Now().UnixNano())
  3071. }
  3072. if iface.Interface == "" {
  3073. iface.Interface = "*"
  3074. }
  3075. if iface.MinRxInterval == 0 {
  3076. iface.MinRxInterval = 100
  3077. }
  3078. if iface.MinTxInterval == 0 {
  3079. iface.MinTxInterval = 100
  3080. }
  3081. if iface.Multiplier == 0 {
  3082. iface.Multiplier = 3
  3083. }
  3084. found := false
  3085. for i, existing := range m.config.BFDInterfaces {
  3086. if existing.ID == iface.ID {
  3087. m.config.BFDInterfaces[i] = iface
  3088. found = true
  3089. break
  3090. }
  3091. }
  3092. if !found {
  3093. m.config.BFDInterfaces = append(m.config.BFDInterfaces, iface)
  3094. }
  3095. if !m.config.BFDInstance.Disabled {
  3096. m.config.BFDInstance.Enabled = true
  3097. }
  3098. if err := m.save(); err != nil {
  3099. return nil, err
  3100. }
  3101. if err := m.applyBirdConfig(); err != nil {
  3102. return nil, err
  3103. }
  3104. return &iface, nil
  3105. }
  3106. func (m *Manager) DeleteBFDInterface(id string) error {
  3107. m.mu.Lock()
  3108. defer m.mu.Unlock()
  3109. newIfaces := make([]BFDInterface, 0, len(m.config.BFDInterfaces))
  3110. for _, iface := range m.config.BFDInterfaces {
  3111. if iface.ID != id && iface.Interface != id {
  3112. newIfaces = append(newIfaces, iface)
  3113. }
  3114. }
  3115. m.config.BFDInterfaces = newIfaces
  3116. if err := m.save(); err != nil {
  3117. return err
  3118. }
  3119. return m.applyBirdConfig()
  3120. }
  3121. func (m *Manager) SetBFDInterfaceState(id string, disabled bool) error {
  3122. m.mu.Lock()
  3123. defer m.mu.Unlock()
  3124. for i := range m.config.BFDInterfaces {
  3125. if m.config.BFDInterfaces[i].ID == id || m.config.BFDInterfaces[i].Interface == id {
  3126. m.config.BFDInterfaces[i].Disabled = disabled
  3127. break
  3128. }
  3129. }
  3130. if err := m.save(); err != nil {
  3131. return err
  3132. }
  3133. return m.applyBirdConfig()
  3134. }
  3135. func (m *Manager) ListBFDNeighbors() []BFDNeighbor {
  3136. m.mu.RLock()
  3137. defer m.mu.RUnlock()
  3138. res := make([]BFDNeighbor, len(m.config.BFDNeighbors))
  3139. copy(res, m.config.BFDNeighbors)
  3140. return res
  3141. }
  3142. func (m *Manager) SaveBFDNeighbor(nbr BFDNeighbor) (*BFDNeighbor, error) {
  3143. m.mu.Lock()
  3144. defer m.mu.Unlock()
  3145. previous := append([]BFDNeighbor(nil), m.config.BFDNeighbors...)
  3146. previousInstance := m.config.BFDInstance
  3147. if nbr.ID == "" {
  3148. nbr.ID = fmt.Sprintf("bfd-nbr-%d", time.Now().UnixNano())
  3149. }
  3150. found := false
  3151. for i, existing := range m.config.BFDNeighbors {
  3152. if existing.ID == nbr.ID || existing.Address == nbr.Address {
  3153. m.config.BFDNeighbors[i] = nbr
  3154. found = true
  3155. break
  3156. }
  3157. }
  3158. if !found {
  3159. m.config.BFDNeighbors = append(m.config.BFDNeighbors, nbr)
  3160. }
  3161. if !m.config.BFDInstance.Disabled {
  3162. m.config.BFDInstance.Enabled = true
  3163. }
  3164. if err := m.commitBFDNeighbors(previous, previousInstance); err != nil {
  3165. return nil, err
  3166. }
  3167. return &nbr, nil
  3168. }
  3169. func (m *Manager) DeleteBFDNeighbor(id string) error {
  3170. m.mu.Lock()
  3171. defer m.mu.Unlock()
  3172. previous := append([]BFDNeighbor(nil), m.config.BFDNeighbors...)
  3173. previousInstance := m.config.BFDInstance
  3174. newNbrs := make([]BFDNeighbor, 0, len(m.config.BFDNeighbors))
  3175. for _, nbr := range m.config.BFDNeighbors {
  3176. if nbr.ID != id && nbr.Address != id {
  3177. newNbrs = append(newNbrs, nbr)
  3178. }
  3179. }
  3180. m.config.BFDNeighbors = newNbrs
  3181. return m.commitBFDNeighbors(previous, previousInstance)
  3182. }
  3183. // commitBFDNeighbors is called with m.mu held. On failure, restore the old
  3184. // in-memory and persisted configuration and attempt to reapply it to BIRD.
  3185. func (m *Manager) commitBFDNeighbors(previous []BFDNeighbor, previousInstance BFDInstance) error {
  3186. if err := m.save(); err != nil {
  3187. m.config.BFDNeighbors, m.config.BFDInstance = previous, previousInstance
  3188. return fmt.Errorf("save BFD configuration: %w", err)
  3189. }
  3190. if err := m.applyBirdConfig(); err != nil {
  3191. m.config.BFDNeighbors, m.config.BFDInstance = previous, previousInstance
  3192. var failures []error
  3193. failures = append(failures, fmt.Errorf("apply BFD configuration: %w", err))
  3194. if rollbackErr := m.save(); rollbackErr != nil {
  3195. failures = append(failures, fmt.Errorf("restore BFD configuration: %w", rollbackErr))
  3196. }
  3197. if rollbackErr := m.applyBirdConfig(); rollbackErr != nil {
  3198. failures = append(failures, fmt.Errorf("reapply previous BFD configuration: %w", rollbackErr))
  3199. }
  3200. return errors.Join(failures...)
  3201. }
  3202. return nil
  3203. }
  3204. func (m *Manager) GetBFDSessions() []BFDSession {
  3205. var list []BFDSession
  3206. out, err := birdcExec("show bfd sessions")
  3207. if err != nil {
  3208. return list
  3209. }
  3210. lines := strings.Split(string(out), "\n")
  3211. for _, line := range lines {
  3212. trimmed := strings.TrimSpace(line)
  3213. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "IP address") || strings.Contains(trimmed, "There is no BFD") || strings.HasSuffix(trimmed, ":") {
  3214. continue
  3215. }
  3216. fields := strings.Fields(trimmed)
  3217. if len(fields) >= 3 {
  3218. sess := BFDSession{
  3219. IP: fields[0],
  3220. Interface: fields[1],
  3221. State: fields[2],
  3222. }
  3223. if len(fields) >= 6 {
  3224. sess.Timeout = fields[len(fields)-1]
  3225. sess.Interval = fields[len(fields)-2]
  3226. sess.Since = strings.Join(fields[3:len(fields)-2], " ")
  3227. } else {
  3228. if len(fields) >= 4 {
  3229. sess.Since = fields[3]
  3230. }
  3231. if len(fields) >= 5 {
  3232. sess.Interval = fields[4]
  3233. }
  3234. }
  3235. list = append(list, sess)
  3236. }
  3237. }
  3238. return list
  3239. }
  3240. // -------------------------------------------------------------
  3241. // Babel Methods (/routing babel)
  3242. // -------------------------------------------------------------
  3243. func (m *Manager) ListBabelInstances() []BabelInstance {
  3244. m.mu.RLock()
  3245. defer m.mu.RUnlock()
  3246. out, err := birdcExec("show protocols")
  3247. protocols := map[string]bool{}
  3248. birdRunning := false
  3249. if err == nil {
  3250. birdRunning = strings.Contains(string(out), "BIRD")
  3251. for _, line := range strings.Split(string(out), "\n") {
  3252. fields := strings.Fields(line)
  3253. if len(fields) >= 4 && (fields[1] == "Babel" || strings.HasPrefix(fields[0], "babel_")) {
  3254. protocols[fields[0]] = fields[3] == "up"
  3255. }
  3256. }
  3257. }
  3258. res := make([]BabelInstance, len(m.config.BabelInstances))
  3259. copy(res, m.config.BabelInstances)
  3260. for i := range res {
  3261. protoName := sanitizeIdentifier("babel", fmt.Sprintf("%s_%d", res[i].Name, i))
  3262. isProtoUp := protocols[protoName] || protocols[sanitizeIdentifier("babel", res[i].Name)]
  3263. res[i].Running = (isProtoUp || (birdRunning && (res[i].Enabled || !res[i].Disabled))) && !res[i].Disabled
  3264. res[i].Enabled = !res[i].Disabled
  3265. }
  3266. return res
  3267. }
  3268. func (m *Manager) SaveBabelInstance(inst BabelInstance) (*BabelInstance, error) {
  3269. m.mu.Lock()
  3270. defer m.mu.Unlock()
  3271. if inst.ID == "" {
  3272. inst.ID = fmt.Sprintf("babel-inst-%d", time.Now().UnixNano())
  3273. }
  3274. if inst.Name == "" {
  3275. inst.Name = "default"
  3276. }
  3277. if !inst.Disabled && !inst.Enabled {
  3278. inst.Enabled = true
  3279. }
  3280. if inst.Disabled {
  3281. inst.Enabled = false
  3282. }
  3283. found := false
  3284. for i, existing := range m.config.BabelInstances {
  3285. if existing.ID == inst.ID || strings.EqualFold(existing.Name, inst.Name) {
  3286. m.config.BabelInstances[i] = inst
  3287. found = true
  3288. break
  3289. }
  3290. }
  3291. if !found {
  3292. m.config.BabelInstances = append(m.config.BabelInstances, inst)
  3293. }
  3294. if err := m.save(); err != nil {
  3295. return nil, err
  3296. }
  3297. if err := m.applyBirdConfig(); err != nil {
  3298. return nil, err
  3299. }
  3300. return &inst, nil
  3301. }
  3302. func (m *Manager) DeleteBabelInstance(id string) error {
  3303. m.mu.Lock()
  3304. defer m.mu.Unlock()
  3305. newInsts := make([]BabelInstance, 0, len(m.config.BabelInstances))
  3306. for _, inst := range m.config.BabelInstances {
  3307. if inst.ID != id && inst.Name != id {
  3308. newInsts = append(newInsts, inst)
  3309. }
  3310. }
  3311. m.config.BabelInstances = newInsts
  3312. if err := m.save(); err != nil {
  3313. return err
  3314. }
  3315. return m.applyBirdConfig()
  3316. }
  3317. func (m *Manager) SetBabelInstanceState(id string, disabled bool) error {
  3318. m.mu.Lock()
  3319. defer m.mu.Unlock()
  3320. for i := range m.config.BabelInstances {
  3321. if m.config.BabelInstances[i].ID == id || m.config.BabelInstances[i].Name == id {
  3322. m.config.BabelInstances[i].Disabled = disabled
  3323. m.config.BabelInstances[i].Enabled = !disabled
  3324. break
  3325. }
  3326. }
  3327. if err := m.save(); err != nil {
  3328. return err
  3329. }
  3330. return m.applyBirdConfig()
  3331. }
  3332. func (m *Manager) ListBabelInterfaces() []BabelInterface {
  3333. m.mu.RLock()
  3334. defer m.mu.RUnlock()
  3335. res := make([]BabelInterface, len(m.config.BabelInterfaces))
  3336. copy(res, m.config.BabelInterfaces)
  3337. return res
  3338. }
  3339. func (m *Manager) SaveBabelInterface(iface BabelInterface) (*BabelInterface, error) {
  3340. m.mu.Lock()
  3341. defer m.mu.Unlock()
  3342. if iface.ID == "" {
  3343. iface.ID = fmt.Sprintf("babel-iface-%d", time.Now().UnixNano())
  3344. }
  3345. if iface.Interface == "" {
  3346. iface.Interface = "*"
  3347. }
  3348. if iface.Instance == "" {
  3349. if len(m.config.BabelInstances) > 0 {
  3350. iface.Instance = m.config.BabelInstances[0].Name
  3351. } else {
  3352. iface.Instance = "default"
  3353. }
  3354. }
  3355. if iface.Type == "" {
  3356. iface.Type = "wired"
  3357. }
  3358. if iface.RxCost == 0 {
  3359. iface.RxCost = 10
  3360. }
  3361. if iface.HelloInterval == 0 {
  3362. iface.HelloInterval = 4
  3363. }
  3364. if iface.UpdateInterval == 0 {
  3365. iface.UpdateInterval = 16
  3366. }
  3367. found := false
  3368. for i, existing := range m.config.BabelInterfaces {
  3369. if existing.ID == iface.ID {
  3370. m.config.BabelInterfaces[i] = iface
  3371. found = true
  3372. break
  3373. }
  3374. }
  3375. if !found {
  3376. m.config.BabelInterfaces = append(m.config.BabelInterfaces, iface)
  3377. }
  3378. if err := m.save(); err != nil {
  3379. return nil, err
  3380. }
  3381. if err := m.applyBirdConfig(); err != nil {
  3382. return nil, err
  3383. }
  3384. return &iface, nil
  3385. }
  3386. func (m *Manager) DeleteBabelInterface(id string) error {
  3387. m.mu.Lock()
  3388. defer m.mu.Unlock()
  3389. newIfaces := make([]BabelInterface, 0, len(m.config.BabelInterfaces))
  3390. for _, iface := range m.config.BabelInterfaces {
  3391. if iface.ID != id && iface.Interface != id {
  3392. newIfaces = append(newIfaces, iface)
  3393. }
  3394. }
  3395. m.config.BabelInterfaces = newIfaces
  3396. if err := m.save(); err != nil {
  3397. return err
  3398. }
  3399. return m.applyBirdConfig()
  3400. }
  3401. func (m *Manager) SetBabelInterfaceState(id string, disabled bool) error {
  3402. m.mu.Lock()
  3403. defer m.mu.Unlock()
  3404. for i := range m.config.BabelInterfaces {
  3405. if m.config.BabelInterfaces[i].ID == id || m.config.BabelInterfaces[i].Interface == id {
  3406. m.config.BabelInterfaces[i].Disabled = disabled
  3407. break
  3408. }
  3409. }
  3410. if err := m.save(); err != nil {
  3411. return err
  3412. }
  3413. return m.applyBirdConfig()
  3414. }
  3415. func (m *Manager) resolveBabelInstanceName(protoName string) string {
  3416. protoName = strings.TrimSuffix(protoName, ":")
  3417. for _, inst := range m.config.BabelInstances {
  3418. if strings.Contains(protoName, inst.Name) {
  3419. return inst.Name
  3420. }
  3421. }
  3422. name := strings.TrimPrefix(protoName, "babel_")
  3423. if idx := strings.LastIndex(name, "_"); idx > 0 {
  3424. name = name[:idx]
  3425. }
  3426. if name == "" {
  3427. name = "default"
  3428. }
  3429. return name
  3430. }
  3431. func (m *Manager) GetBabelInterfacesLive() []BabelInterfaceLive {
  3432. m.mu.RLock()
  3433. defer m.mu.RUnlock()
  3434. var list []BabelInterfaceLive
  3435. out, err := birdcExec("show babel interfaces")
  3436. if err != nil {
  3437. return list
  3438. }
  3439. lines := strings.Split(string(out), "\n")
  3440. currentProto := ""
  3441. for _, line := range lines {
  3442. trimmed := strings.TrimSpace(line)
  3443. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Interface ") || strings.Contains(trimmed, "There is no Babel") {
  3444. continue
  3445. }
  3446. if strings.HasSuffix(trimmed, ":") {
  3447. currentProto = strings.TrimSuffix(trimmed, ":")
  3448. continue
  3449. }
  3450. fields := strings.Fields(trimmed)
  3451. if len(fields) >= 6 {
  3452. rxCost := 0
  3453. fmt.Sscanf(fields[3], "%d", &rxCost)
  3454. nbrs := 0
  3455. fmt.Sscanf(fields[4], "%d", &nbrs)
  3456. nextHopV4 := ""
  3457. nextHopV6 := ""
  3458. if len(fields) >= 7 {
  3459. nextHopV4 = fields[6]
  3460. }
  3461. if len(fields) >= 8 {
  3462. nextHopV6 = fields[7]
  3463. }
  3464. instName := m.resolveBabelInstanceName(currentProto)
  3465. list = append(list, BabelInterfaceLive{
  3466. Instance: instName,
  3467. Interface: fields[0],
  3468. State: fields[1],
  3469. Auth: fields[2],
  3470. RxCost: rxCost,
  3471. Neighbors: nbrs,
  3472. Timer: fields[5],
  3473. NextHopV4: nextHopV4,
  3474. NextHopV6: nextHopV6,
  3475. })
  3476. }
  3477. }
  3478. return list
  3479. }
  3480. func (m *Manager) GetBabelNeighbors() []BabelNeighbor {
  3481. var list []BabelNeighbor
  3482. out, err := birdcExec("show babel neighbors")
  3483. if err != nil {
  3484. return list
  3485. }
  3486. lines := strings.Split(string(out), "\n")
  3487. for _, line := range lines {
  3488. trimmed := strings.TrimSpace(line)
  3489. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "IP address") || strings.Contains(trimmed, "There is no Babel") || strings.HasSuffix(trimmed, ":") {
  3490. continue
  3491. }
  3492. fields := strings.Fields(trimmed)
  3493. if len(fields) >= 2 {
  3494. nbr := BabelNeighbor{
  3495. IP: fields[0],
  3496. Interface: fields[1],
  3497. }
  3498. if len(fields) >= 3 {
  3499. fmt.Sscanf(fields[2], "%d", &nbr.Metric)
  3500. }
  3501. if len(fields) >= 4 {
  3502. fmt.Sscanf(fields[3], "%d", &nbr.Routes)
  3503. }
  3504. if len(fields) >= 5 {
  3505. fmt.Sscanf(fields[4], "%d", &nbr.Hellos)
  3506. }
  3507. if len(fields) >= 6 {
  3508. nbr.Expires = fields[5]
  3509. }
  3510. if len(fields) >= 7 {
  3511. nbr.Auth = fields[6]
  3512. }
  3513. if len(fields) >= 8 {
  3514. fmt.Sscanf(fields[7], "%f", &nbr.RTT)
  3515. }
  3516. list = append(list, nbr)
  3517. }
  3518. }
  3519. return list
  3520. }
  3521. func (m *Manager) GetBabelRoutes() []BabelRoute {
  3522. var routes []BabelRoute
  3523. out, err := birdcExec("show babel routes")
  3524. if err == nil {
  3525. lines := strings.Split(string(out), "\n")
  3526. for _, line := range lines {
  3527. trimmed := strings.TrimSpace(line)
  3528. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Prefix") || strings.Contains(trimmed, "There is no Babel") || strings.HasSuffix(trimmed, ":") {
  3529. continue
  3530. }
  3531. fields := strings.Fields(trimmed)
  3532. if len(fields) >= 4 {
  3533. metric := 0
  3534. fmt.Sscanf(fields[3], "%d", &metric)
  3535. flag := ""
  3536. seqno := 0
  3537. expires := ""
  3538. if len(fields) >= 5 {
  3539. flag = fields[4]
  3540. }
  3541. if len(fields) >= 6 {
  3542. fmt.Sscanf(fields[5], "%d", &seqno)
  3543. }
  3544. if len(fields) >= 7 {
  3545. expires = fields[6]
  3546. }
  3547. routes = append(routes, BabelRoute{
  3548. Prefix: fields[0],
  3549. NextHop: fields[1],
  3550. Interface: fields[2],
  3551. Metric: metric,
  3552. Flag: flag,
  3553. Seqno: seqno,
  3554. Expires: expires,
  3555. })
  3556. }
  3557. }
  3558. }
  3559. if len(routes) == 0 {
  3560. outK, errK := birdcExec("show route where source = RTS_BABEL all")
  3561. if errK == nil {
  3562. lines := strings.Split(string(outK), "\n")
  3563. for _, line := range lines {
  3564. trimmed := strings.TrimSpace(line)
  3565. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  3566. continue
  3567. }
  3568. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  3569. fields := strings.Fields(trimmed)
  3570. if len(fields) >= 2 {
  3571. rt := BabelRoute{
  3572. Prefix: fields[0],
  3573. }
  3574. for i := 1; i < len(fields); i++ {
  3575. if fields[i] == "via" && i+1 < len(fields) {
  3576. rt.NextHop = fields[i+1]
  3577. }
  3578. if fields[i] == "dev" && i+1 < len(fields) {
  3579. rt.Interface = fields[i+1]
  3580. }
  3581. }
  3582. routes = append(routes, rt)
  3583. }
  3584. }
  3585. }
  3586. }
  3587. }
  3588. return routes
  3589. }
  3590. // -------------------------------------------------------------
  3591. // RAdv Methods (/routing radv)
  3592. // -------------------------------------------------------------
  3593. func (m *Manager) ListRAdvInstances() []RAdvInstance {
  3594. m.mu.RLock()
  3595. defer m.mu.RUnlock()
  3596. out, err := birdcExec("show protocols")
  3597. protocols := map[string]bool{}
  3598. birdRunning := false
  3599. if err == nil {
  3600. birdRunning = strings.Contains(string(out), "BIRD")
  3601. for _, line := range strings.Split(string(out), "\n") {
  3602. fields := strings.Fields(line)
  3603. if len(fields) >= 4 && (fields[1] == "RAdv" || strings.HasPrefix(fields[0], "radv_")) {
  3604. protocols[fields[0]] = fields[3] == "up"
  3605. }
  3606. }
  3607. }
  3608. res := make([]RAdvInstance, len(m.config.RAdvInstances))
  3609. copy(res, m.config.RAdvInstances)
  3610. for i := range res {
  3611. protoName := sanitizeIdentifier("radv", fmt.Sprintf("%s_%d", res[i].Name, i))
  3612. isProtoUp := protocols[protoName] || protocols[sanitizeIdentifier("radv", res[i].Name)]
  3613. res[i].Running = (isProtoUp || (birdRunning && (res[i].Enabled || !res[i].Disabled))) && !res[i].Disabled
  3614. res[i].Enabled = !res[i].Disabled
  3615. }
  3616. return res
  3617. }
  3618. func (m *Manager) SaveRAdvInstance(inst RAdvInstance) (*RAdvInstance, error) {
  3619. m.mu.Lock()
  3620. defer m.mu.Unlock()
  3621. if !inst.Disabled {
  3622. inst.Enabled = true
  3623. } else {
  3624. inst.Enabled = false
  3625. }
  3626. if inst.ID == "" {
  3627. inst.ID = fmt.Sprintf("radv-inst-%d", time.Now().UnixNano())
  3628. }
  3629. if inst.Name == "" {
  3630. inst.Name = "default"
  3631. }
  3632. found := false
  3633. for i, existing := range m.config.RAdvInstances {
  3634. if existing.ID == inst.ID || strings.EqualFold(existing.Name, inst.Name) {
  3635. m.config.RAdvInstances[i] = inst
  3636. found = true
  3637. break
  3638. }
  3639. }
  3640. if !found {
  3641. m.config.RAdvInstances = append(m.config.RAdvInstances, inst)
  3642. }
  3643. if err := m.save(); err != nil {
  3644. return nil, err
  3645. }
  3646. if err := m.applyBirdConfig(); err != nil {
  3647. return nil, err
  3648. }
  3649. return &inst, nil
  3650. }
  3651. func (m *Manager) DeleteRAdvInstance(id string) error {
  3652. m.mu.Lock()
  3653. defer m.mu.Unlock()
  3654. newInsts := make([]RAdvInstance, 0, len(m.config.RAdvInstances))
  3655. for _, inst := range m.config.RAdvInstances {
  3656. if inst.ID != id && inst.Name != id {
  3657. newInsts = append(newInsts, inst)
  3658. }
  3659. }
  3660. m.config.RAdvInstances = newInsts
  3661. if err := m.save(); err != nil {
  3662. return err
  3663. }
  3664. return m.applyBirdConfig()
  3665. }
  3666. func (m *Manager) SetRAdvInstanceState(id string, disabled bool) error {
  3667. m.mu.Lock()
  3668. defer m.mu.Unlock()
  3669. for i := range m.config.RAdvInstances {
  3670. if m.config.RAdvInstances[i].ID == id || m.config.RAdvInstances[i].Name == id {
  3671. m.config.RAdvInstances[i].Disabled = disabled
  3672. m.config.RAdvInstances[i].Enabled = !disabled
  3673. break
  3674. }
  3675. }
  3676. if err := m.save(); err != nil {
  3677. return err
  3678. }
  3679. return m.applyBirdConfig()
  3680. }
  3681. func (m *Manager) ListRAdvInterfaces() []RAdvInterface {
  3682. m.mu.RLock()
  3683. defer m.mu.RUnlock()
  3684. res := make([]RAdvInterface, len(m.config.RAdvInterfaces))
  3685. copy(res, m.config.RAdvInterfaces)
  3686. return res
  3687. }
  3688. func (m *Manager) SaveRAdvInterface(iface RAdvInterface) (*RAdvInterface, error) {
  3689. m.mu.Lock()
  3690. defer m.mu.Unlock()
  3691. if iface.ID == "" {
  3692. iface.ID = fmt.Sprintf("radv-iface-%d", time.Now().UnixNano())
  3693. }
  3694. if iface.Interface == "" {
  3695. iface.Interface = "*"
  3696. }
  3697. if iface.MinRAInterval == 0 {
  3698. iface.MinRAInterval = 200
  3699. }
  3700. if iface.MaxRAInterval == 0 {
  3701. iface.MaxRAInterval = 600
  3702. }
  3703. if iface.DefaultLifetime == 0 {
  3704. iface.DefaultLifetime = 1800
  3705. }
  3706. found := false
  3707. for i, existing := range m.config.RAdvInterfaces {
  3708. if existing.ID == iface.ID {
  3709. m.config.RAdvInterfaces[i] = iface
  3710. found = true
  3711. break
  3712. }
  3713. }
  3714. if !found {
  3715. m.config.RAdvInterfaces = append(m.config.RAdvInterfaces, iface)
  3716. }
  3717. if err := m.save(); err != nil {
  3718. return nil, err
  3719. }
  3720. if err := m.applyBirdConfig(); err != nil {
  3721. return nil, err
  3722. }
  3723. return &iface, nil
  3724. }
  3725. func (m *Manager) DeleteRAdvInterface(id string) error {
  3726. m.mu.Lock()
  3727. defer m.mu.Unlock()
  3728. newIfaces := make([]RAdvInterface, 0, len(m.config.RAdvInterfaces))
  3729. for _, iface := range m.config.RAdvInterfaces {
  3730. if iface.ID != id && iface.Interface != id {
  3731. newIfaces = append(newIfaces, iface)
  3732. }
  3733. }
  3734. m.config.RAdvInterfaces = newIfaces
  3735. if err := m.save(); err != nil {
  3736. return err
  3737. }
  3738. return m.applyBirdConfig()
  3739. }
  3740. func (m *Manager) SetRAdvInterfaceState(id string, disabled bool) error {
  3741. m.mu.Lock()
  3742. defer m.mu.Unlock()
  3743. for i := range m.config.RAdvInterfaces {
  3744. if m.config.RAdvInterfaces[i].ID == id || m.config.RAdvInterfaces[i].Interface == id {
  3745. m.config.RAdvInterfaces[i].Disabled = disabled
  3746. break
  3747. }
  3748. }
  3749. if err := m.save(); err != nil {
  3750. return err
  3751. }
  3752. return m.applyBirdConfig()
  3753. }
  3754. // -------------------------------------------------------------
  3755. // Summary Telemetry
  3756. // -------------------------------------------------------------
  3757. func (m *Manager) GetSummary() DynamicRoutingSummary {
  3758. m.mu.RLock()
  3759. defer m.mu.RUnlock()
  3760. ospfEnabled := (m.config.OSPFInstance.Enabled || !m.config.OSPFInstance.Disabled) && !m.config.OSPFInstance.Disabled
  3761. for _, inst := range m.config.OSPFInstances {
  3762. if (inst.Enabled || !inst.Disabled) && !inst.Disabled {
  3763. ospfEnabled = true
  3764. break
  3765. }
  3766. }
  3767. bgpEnabled := m.config.BGPInstance.Enabled
  3768. if !bgpEnabled && len(m.config.BGPPeers) > 0 {
  3769. for _, p := range m.config.BGPPeers {
  3770. if !p.Disabled {
  3771. bgpEnabled = true
  3772. break
  3773. }
  3774. }
  3775. }
  3776. summary := DynamicRoutingSummary{
  3777. BGPEnabled: bgpEnabled,
  3778. OSPFEnabled: ospfEnabled,
  3779. BGPPeerCount: len(m.config.BGPPeers),
  3780. RoutingFilterCount: len(m.config.RoutingFilters),
  3781. }
  3782. out, err := birdcExec("show status")
  3783. birdRunning := err == nil && strings.Contains(string(out), "Daemon is up and running")
  3784. if birdRunning && summary.BGPEnabled {
  3785. summary.BGPRunning = true
  3786. peers := m.ListBGPPeers()
  3787. est := 0
  3788. for _, p := range peers {
  3789. if strings.EqualFold(p.State, "Established") || strings.EqualFold(p.State, "Up") {
  3790. est++
  3791. }
  3792. }
  3793. summary.BGPEstablishedCount = est
  3794. }
  3795. if birdRunning && summary.OSPFEnabled {
  3796. summary.OSPFRunning = true
  3797. nbrs := m.GetOSPFNeighbors()
  3798. summary.OSPFNeighborCount = len(nbrs)
  3799. adj := 0
  3800. for _, n := range nbrs {
  3801. if strings.Contains(strings.ToLower(n.State), "full") {
  3802. adj++
  3803. }
  3804. }
  3805. summary.OSPFAdjacentCount = adj
  3806. }
  3807. for _, inst := range m.config.RIPInstances {
  3808. if (inst.Enabled || !inst.Disabled) && !inst.Disabled {
  3809. summary.RIPEnabled = true
  3810. break
  3811. }
  3812. }
  3813. if summary.RIPEnabled && birdRunning {
  3814. summary.RIPRunning = true
  3815. nbrs := m.GetRIPNeighbors()
  3816. summary.RIPNeighborCount = len(nbrs)
  3817. }
  3818. pOut, pErr := birdcExec("show protocols bfd_main")
  3819. bfdUp := pErr == nil && strings.Contains(string(pOut), "up")
  3820. summary.BFDEnabled = (m.config.BFDInstance.Enabled || len(m.config.BFDInterfaces) > 0 || len(m.config.BFDNeighbors) > 0) && !m.config.BFDInstance.Disabled
  3821. summary.BFDRunning = (bfdUp || (birdRunning && summary.BFDEnabled)) && !m.config.BFDInstance.Disabled
  3822. if summary.BFDRunning {
  3823. sessions := m.GetBFDSessions()
  3824. summary.BFDSessionCount = len(sessions)
  3825. }
  3826. for _, inst := range m.config.BabelInstances {
  3827. if (inst.Enabled || !inst.Disabled) && !inst.Disabled {
  3828. summary.BabelEnabled = true
  3829. break
  3830. }
  3831. }
  3832. if summary.BabelEnabled && birdRunning {
  3833. summary.BabelRunning = true
  3834. nbrs := m.GetBabelNeighbors()
  3835. summary.BabelNeighborCount = len(nbrs)
  3836. }
  3837. for _, inst := range m.config.RAdvInstances {
  3838. if (inst.Enabled || !inst.Disabled) && !inst.Disabled {
  3839. summary.RAdvEnabled = true
  3840. break
  3841. }
  3842. }
  3843. if summary.RAdvEnabled && birdRunning {
  3844. summary.RAdvRunning = true
  3845. }
  3846. for _, inst := range m.config.EIGRPInstances {
  3847. if (inst.Enabled || !inst.Disabled) && !inst.Disabled {
  3848. summary.EIGRPEnabled = true
  3849. break
  3850. }
  3851. }
  3852. if summary.EIGRPEnabled {
  3853. out, err := exec.Command("vtysh", "-c", "show ip eigrp interfaces").CombinedOutput()
  3854. if err == nil && strings.Contains(string(out), "EIGRP interfaces for AS") {
  3855. summary.EIGRPRunning = true
  3856. nbrs := m.ListEIGRPNeighborsLive()
  3857. summary.EIGRPNeighborCount = len(nbrs)
  3858. }
  3859. }
  3860. return summary
  3861. }
  3862. // ==========================================
  3863. // EIGRP Management (FRRouting eigrpd backend)
  3864. // ==========================================
  3865. func generateFRRPrefixList(name string, rules []RoutingFilterRule) string {
  3866. sortedRules := make([]RoutingFilterRule, len(rules))
  3867. copy(sortedRules, rules)
  3868. sort.SliceStable(sortedRules, func(i, j int) bool {
  3869. return sortedRules[i].RuleOrder < sortedRules[j].RuleOrder
  3870. })
  3871. var sb strings.Builder
  3872. seq := 10
  3873. reDstRange := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)\{([0-9]+),([0-9]+)\}`)
  3874. reDstIn := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)`)
  3875. reDstEq := regexp.MustCompile(`\bdst\s*={1,2}\s*([0-9\.\/]+)`)
  3876. for _, r := range sortedRules {
  3877. if r.Disabled {
  3878. continue
  3879. }
  3880. action := "permit"
  3881. if strings.EqualFold(r.Action, "reject") || strings.EqualFold(r.Action, "discard") || strings.EqualFold(r.Action, "deny") || strings.Contains(r.Rule, "reject") || strings.Contains(r.Rule, "discard") {
  3882. action = "deny"
  3883. }
  3884. prefix := r.Prefix
  3885. if prefix == "" {
  3886. if m := reDstRange.FindStringSubmatch(r.Rule); len(m) == 4 {
  3887. prefix = fmt.Sprintf("%s ge %s le %s", m[1], m[2], m[3])
  3888. } else if m := reDstIn.FindStringSubmatch(r.Rule); len(m) == 2 {
  3889. prefix = fmt.Sprintf("%s le 32", m[1])
  3890. } else if m := reDstEq.FindStringSubmatch(r.Rule); len(m) == 2 {
  3891. prefix = m[1]
  3892. }
  3893. } else {
  3894. if r.PrefixLen != "" {
  3895. prefix = fmt.Sprintf("%s %s", prefix, r.PrefixLen)
  3896. }
  3897. }
  3898. if prefix != "" {
  3899. sb.WriteString(fmt.Sprintf("ip prefix-list %s seq %d %s %s\n", name, seq, action, prefix))
  3900. seq += 10
  3901. }
  3902. }
  3903. sb.WriteString(fmt.Sprintf("ip prefix-list %s seq 65535 deny 0.0.0.0/0 le 32\n", name))
  3904. return sb.String()
  3905. }
  3906. func (m *Manager) generateFRREigrpConfig() string {
  3907. var sb strings.Builder
  3908. sb.WriteString("frr version 10.3\n")
  3909. sb.WriteString("frr defaults traditional\n")
  3910. sb.WriteString("hostname DebTik\n")
  3911. sb.WriteString("log syslog informational\n")
  3912. sb.WriteString("!\n")
  3913. hasActiveEigrp := false
  3914. for _, inst := range m.config.EIGRPInstances {
  3915. if !inst.Disabled {
  3916. hasActiveEigrp = true
  3917. break
  3918. }
  3919. }
  3920. if !hasActiveEigrp {
  3921. sb.WriteString("line vty\n!\nend\n")
  3922. return sb.String()
  3923. }
  3924. chainRules := make(map[string][]RoutingFilterRule)
  3925. for _, rule := range m.config.RoutingFilters {
  3926. if rule.Disabled {
  3927. continue
  3928. }
  3929. chain := strings.TrimSpace(rule.Chain)
  3930. if chain == "" {
  3931. continue
  3932. }
  3933. chainRules[chain] = append(chainRules[chain], rule)
  3934. }
  3935. generatedPLs := make(map[string]bool)
  3936. for _, inst := range m.config.EIGRPInstances {
  3937. if inst.Disabled {
  3938. continue
  3939. }
  3940. if inst.InFilter != "" && len(chainRules[inst.InFilter]) > 0 {
  3941. plName := sanitizeIdentifier("pl_in", inst.InFilter)
  3942. if !generatedPLs[plName] {
  3943. sb.WriteString(generateFRRPrefixList(plName, chainRules[inst.InFilter]))
  3944. generatedPLs[plName] = true
  3945. }
  3946. }
  3947. if inst.OutFilter != "" && len(chainRules[inst.OutFilter]) > 0 {
  3948. plName := sanitizeIdentifier("pl_out", inst.OutFilter)
  3949. if !generatedPLs[plName] {
  3950. sb.WriteString(generateFRRPrefixList(plName, chainRules[inst.OutFilter]))
  3951. generatedPLs[plName] = true
  3952. }
  3953. }
  3954. }
  3955. sb.WriteString("!\n")
  3956. // Interface configurations
  3957. for _, iface := range m.config.EIGRPInterfaces {
  3958. if iface.Disabled || iface.Interface == "" || iface.Interface == "*" {
  3959. continue
  3960. }
  3961. sb.WriteString(fmt.Sprintf("interface %s\n", iface.Interface))
  3962. if iface.HelloInterval > 0 {
  3963. sb.WriteString(fmt.Sprintf(" ip hello-interval eigrp %d\n", iface.HelloInterval))
  3964. }
  3965. if iface.HoldTime > 0 {
  3966. sb.WriteString(fmt.Sprintf(" ip hold-time eigrp %d\n", iface.HoldTime))
  3967. }
  3968. sb.WriteString("!\n")
  3969. }
  3970. // Router EIGRP instances
  3971. for _, inst := range m.config.EIGRPInstances {
  3972. if inst.Disabled {
  3973. continue
  3974. }
  3975. as := inst.AS
  3976. if as <= 0 {
  3977. as = 100
  3978. }
  3979. sb.WriteString(fmt.Sprintf("router eigrp %d\n", as))
  3980. if inst.RouterID != "" {
  3981. sb.WriteString(fmt.Sprintf(" eigrp router-id %s\n", inst.RouterID))
  3982. }
  3983. // Passive interfaces matching this instance
  3984. for _, iface := range m.config.EIGRPInterfaces {
  3985. if iface.Disabled || !iface.Passive || iface.Interface == "" || iface.Interface == "*" {
  3986. continue
  3987. }
  3988. if iface.Instance == "" || strings.EqualFold(iface.Instance, inst.Name) || iface.Instance == fmt.Sprintf("%d", as) {
  3989. sb.WriteString(fmt.Sprintf(" passive-interface %s\n", iface.Interface))
  3990. }
  3991. }
  3992. // Networks
  3993. hasNets := false
  3994. for _, net := range m.config.EIGRPNetworks {
  3995. if net.Disabled || net.Network == "" {
  3996. continue
  3997. }
  3998. if net.Instance == "" || strings.EqualFold(net.Instance, inst.Name) || net.Instance == fmt.Sprintf("%d", as) {
  3999. sb.WriteString(fmt.Sprintf(" network %s\n", strings.TrimSpace(net.Network)))
  4000. hasNets = true
  4001. }
  4002. }
  4003. // Fallback wildcard network if none specified
  4004. if !hasNets {
  4005. sb.WriteString(" network 0.0.0.0/0\n")
  4006. }
  4007. // Redistribution
  4008. if inst.RedistributeConnected {
  4009. sb.WriteString(" redistribute connected\n")
  4010. }
  4011. if inst.RedistributeStatic {
  4012. sb.WriteString(" redistribute static\n")
  4013. }
  4014. if inst.RedistributeOSPF {
  4015. sb.WriteString(" redistribute ospf\n")
  4016. }
  4017. if inst.RedistributeBGP {
  4018. sb.WriteString(" redistribute bgp\n")
  4019. }
  4020. if inst.Variance > 1 {
  4021. sb.WriteString(fmt.Sprintf(" variance %d\n", inst.Variance))
  4022. }
  4023. if inst.MaximumPaths > 0 && inst.MaximumPaths != 4 {
  4024. sb.WriteString(fmt.Sprintf(" maximum-paths %d\n", inst.MaximumPaths))
  4025. }
  4026. if inst.DefaultMetric > 0 {
  4027. sb.WriteString(fmt.Sprintf(" default-metric %d 100 255 1 1500\n", inst.DefaultMetric))
  4028. }
  4029. if inst.K1 != 0 || inst.K2 != 0 || inst.K3 != 0 || inst.K4 != 0 || inst.K5 != 0 {
  4030. sb.WriteString(fmt.Sprintf(" metric weights %d %d %d %d %d\n", inst.K1, inst.K2, inst.K3, inst.K4, inst.K5))
  4031. }
  4032. if inst.InFilter != "" && len(chainRules[inst.InFilter]) > 0 {
  4033. plName := sanitizeIdentifier("pl_in", inst.InFilter)
  4034. sb.WriteString(fmt.Sprintf(" distribute-list prefix %s in\n", plName))
  4035. }
  4036. if inst.OutFilter != "" && len(chainRules[inst.OutFilter]) > 0 {
  4037. plName := sanitizeIdentifier("pl_out", inst.OutFilter)
  4038. sb.WriteString(fmt.Sprintf(" distribute-list prefix %s out\n", plName))
  4039. }
  4040. sb.WriteString("!\n")
  4041. }
  4042. sb.WriteString("line vty\n!\nend\n")
  4043. return sb.String()
  4044. }
  4045. func (m *Manager) applyFRREigrpConfig() error {
  4046. hasActiveEigrp := false
  4047. for _, inst := range m.config.EIGRPInstances {
  4048. if !inst.Disabled {
  4049. hasActiveEigrp = true
  4050. break
  4051. }
  4052. }
  4053. if _, err := exec.LookPath("vtysh"); err != nil {
  4054. if hasActiveEigrp {
  4055. return fmt.Errorf("EIGRP requires vtysh: %w", err)
  4056. }
  4057. return nil
  4058. }
  4059. cfgText := m.generateFRREigrpConfig()
  4060. frrConfPath := "/etc/frr/frr.conf"
  4061. // Ensure eigrpd=yes in /etc/frr/daemons if active.
  4062. if hasActiveEigrp {
  4063. data, err := os.ReadFile("/etc/frr/daemons")
  4064. if err != nil {
  4065. return fmt.Errorf("reading FRR daemon configuration: %w", err)
  4066. }
  4067. daemonsContent := string(data)
  4068. if strings.Contains(daemonsContent, "eigrpd=no") {
  4069. newContent := strings.Replace(daemonsContent, "eigrpd=no", "eigrpd=yes", 1)
  4070. if err := os.WriteFile("/etc/frr/daemons", []byte(newContent), 0644); err != nil {
  4071. return fmt.Errorf("enabling eigrpd: %w", err)
  4072. }
  4073. if out, err := exec.Command("systemctl", "restart", "frr").CombinedOutput(); err != nil {
  4074. return fmt.Errorf("restarting FRR: %s: %w", strings.TrimSpace(string(out)), err)
  4075. }
  4076. }
  4077. }
  4078. tmpPath := frrConfPath + ".new"
  4079. if err := os.WriteFile(tmpPath, []byte(cfgText), 0640); err != nil {
  4080. return err
  4081. }
  4082. _ = exec.Command("chown", "frr:frr", tmpPath).Run()
  4083. out, err := exec.Command("vtysh", "-f", tmpPath).CombinedOutput()
  4084. if err != nil {
  4085. _ = os.Remove(tmpPath)
  4086. log.Printf("[DynamicRouting] vtysh -f error: %s (%v)", string(out), err)
  4087. return fmt.Errorf("EIGRP FRR apply failed: %s: %w", string(out), err)
  4088. }
  4089. if err := os.Rename(tmpPath, frrConfPath); err != nil {
  4090. return fmt.Errorf("FRR configuration applied but not saved: %w", err)
  4091. }
  4092. if err := os.Chmod(frrConfPath, 0640); err != nil {
  4093. return fmt.Errorf("setting FRR configuration permissions: %w", err)
  4094. }
  4095. _ = exec.Command("chown", "frr:frr", frrConfPath).Run()
  4096. return nil
  4097. }
  4098. func (m *Manager) ListEIGRPInstances() []EIGRPInstance {
  4099. m.mu.RLock()
  4100. defer m.mu.RUnlock()
  4101. out, err := exec.Command("vtysh", "-c", "show ip eigrp interfaces").CombinedOutput()
  4102. runningOutput := string(out)
  4103. res := make([]EIGRPInstance, len(m.config.EIGRPInstances))
  4104. copy(res, m.config.EIGRPInstances)
  4105. for i := range res {
  4106. as := res[i].AS
  4107. if as <= 0 {
  4108. as = 100
  4109. }
  4110. res[i].Running = (err == nil && strings.Contains(runningOutput, fmt.Sprintf("AS(%d)", as))) && !res[i].Disabled
  4111. res[i].Enabled = !res[i].Disabled
  4112. }
  4113. return res
  4114. }
  4115. func (m *Manager) SaveEIGRPInstance(inst EIGRPInstance) (*EIGRPInstance, error) {
  4116. m.mu.Lock()
  4117. defer m.mu.Unlock()
  4118. if !inst.Disabled {
  4119. inst.Enabled = true
  4120. } else {
  4121. inst.Enabled = false
  4122. }
  4123. if inst.ID == "" {
  4124. inst.ID = fmt.Sprintf("eigrp-inst-%d", time.Now().UnixNano())
  4125. }
  4126. if inst.Name == "" {
  4127. inst.Name = "default"
  4128. }
  4129. if inst.AS <= 0 {
  4130. inst.AS = 100
  4131. }
  4132. if inst.Variance <= 0 {
  4133. inst.Variance = 1
  4134. }
  4135. if inst.MaximumPaths <= 0 {
  4136. inst.MaximumPaths = 4
  4137. }
  4138. found := false
  4139. for i, existing := range m.config.EIGRPInstances {
  4140. if existing.ID == inst.ID || strings.EqualFold(existing.Name, inst.Name) {
  4141. m.config.EIGRPInstances[i] = inst
  4142. found = true
  4143. break
  4144. }
  4145. }
  4146. if !found {
  4147. m.config.EIGRPInstances = append(m.config.EIGRPInstances, inst)
  4148. }
  4149. if err := m.save(); err != nil {
  4150. return nil, err
  4151. }
  4152. if err := m.applyFRREigrpConfig(); err != nil {
  4153. return nil, err
  4154. }
  4155. return &inst, nil
  4156. }
  4157. func (m *Manager) DeleteEIGRPInstance(id string) error {
  4158. m.mu.Lock()
  4159. defer m.mu.Unlock()
  4160. newInsts := make([]EIGRPInstance, 0, len(m.config.EIGRPInstances))
  4161. for _, inst := range m.config.EIGRPInstances {
  4162. if inst.ID == id || inst.Name == id {
  4163. continue
  4164. }
  4165. newInsts = append(newInsts, inst)
  4166. }
  4167. m.config.EIGRPInstances = newInsts
  4168. if err := m.save(); err != nil {
  4169. return err
  4170. }
  4171. return m.applyFRREigrpConfig()
  4172. }
  4173. func (m *Manager) SetEIGRPInstanceState(id string, disabled bool) error {
  4174. m.mu.Lock()
  4175. defer m.mu.Unlock()
  4176. for i := range m.config.EIGRPInstances {
  4177. if m.config.EIGRPInstances[i].ID == id || m.config.EIGRPInstances[i].Name == id {
  4178. m.config.EIGRPInstances[i].Disabled = disabled
  4179. m.config.EIGRPInstances[i].Enabled = !disabled
  4180. break
  4181. }
  4182. }
  4183. if err := m.save(); err != nil {
  4184. return err
  4185. }
  4186. return m.applyFRREigrpConfig()
  4187. }
  4188. func (m *Manager) ListEIGRPInterfaces() []EIGRPInterface {
  4189. m.mu.RLock()
  4190. defer m.mu.RUnlock()
  4191. res := make([]EIGRPInterface, len(m.config.EIGRPInterfaces))
  4192. copy(res, m.config.EIGRPInterfaces)
  4193. return res
  4194. }
  4195. func (m *Manager) SaveEIGRPInterface(iface EIGRPInterface) (*EIGRPInterface, error) {
  4196. m.mu.Lock()
  4197. defer m.mu.Unlock()
  4198. if iface.ID == "" {
  4199. iface.ID = fmt.Sprintf("eigrp-iface-%d", time.Now().UnixNano())
  4200. }
  4201. if iface.Interface == "" {
  4202. iface.Interface = "*"
  4203. }
  4204. if iface.HelloInterval <= 0 {
  4205. iface.HelloInterval = 5
  4206. }
  4207. if iface.HoldTime <= 0 {
  4208. iface.HoldTime = 15
  4209. }
  4210. found := false
  4211. for i, existing := range m.config.EIGRPInterfaces {
  4212. if existing.ID == iface.ID {
  4213. m.config.EIGRPInterfaces[i] = iface
  4214. found = true
  4215. break
  4216. }
  4217. }
  4218. if !found {
  4219. m.config.EIGRPInterfaces = append(m.config.EIGRPInterfaces, iface)
  4220. }
  4221. if err := m.save(); err != nil {
  4222. return nil, err
  4223. }
  4224. if err := m.applyFRREigrpConfig(); err != nil {
  4225. return nil, err
  4226. }
  4227. return &iface, nil
  4228. }
  4229. func (m *Manager) DeleteEIGRPInterface(id string) error {
  4230. m.mu.Lock()
  4231. defer m.mu.Unlock()
  4232. newIfaces := make([]EIGRPInterface, 0, len(m.config.EIGRPInterfaces))
  4233. for _, iface := range m.config.EIGRPInterfaces {
  4234. if iface.ID == id {
  4235. continue
  4236. }
  4237. newIfaces = append(newIfaces, iface)
  4238. }
  4239. m.config.EIGRPInterfaces = newIfaces
  4240. if err := m.save(); err != nil {
  4241. return err
  4242. }
  4243. return m.applyFRREigrpConfig()
  4244. }
  4245. func (m *Manager) SetEIGRPInterfaceState(id string, disabled bool) error {
  4246. m.mu.Lock()
  4247. defer m.mu.Unlock()
  4248. for i := range m.config.EIGRPInterfaces {
  4249. if m.config.EIGRPInterfaces[i].ID == id {
  4250. m.config.EIGRPInterfaces[i].Disabled = disabled
  4251. break
  4252. }
  4253. }
  4254. if err := m.save(); err != nil {
  4255. return err
  4256. }
  4257. return m.applyFRREigrpConfig()
  4258. }
  4259. func (m *Manager) ListEIGRPNetworks() []EIGRPNetwork {
  4260. m.mu.RLock()
  4261. defer m.mu.RUnlock()
  4262. res := make([]EIGRPNetwork, len(m.config.EIGRPNetworks))
  4263. copy(res, m.config.EIGRPNetworks)
  4264. return res
  4265. }
  4266. func (m *Manager) SaveEIGRPNetwork(net EIGRPNetwork) (*EIGRPNetwork, error) {
  4267. m.mu.Lock()
  4268. defer m.mu.Unlock()
  4269. if net.ID == "" {
  4270. net.ID = fmt.Sprintf("eigrp-net-%d", time.Now().UnixNano())
  4271. }
  4272. found := false
  4273. for i, existing := range m.config.EIGRPNetworks {
  4274. if existing.ID == net.ID {
  4275. m.config.EIGRPNetworks[i] = net
  4276. found = true
  4277. break
  4278. }
  4279. }
  4280. if !found {
  4281. m.config.EIGRPNetworks = append(m.config.EIGRPNetworks, net)
  4282. }
  4283. if err := m.save(); err != nil {
  4284. return nil, err
  4285. }
  4286. if err := m.applyFRREigrpConfig(); err != nil {
  4287. return nil, err
  4288. }
  4289. return &net, nil
  4290. }
  4291. func (m *Manager) DeleteEIGRPNetwork(id string) error {
  4292. m.mu.Lock()
  4293. defer m.mu.Unlock()
  4294. newNets := make([]EIGRPNetwork, 0, len(m.config.EIGRPNetworks))
  4295. for _, net := range m.config.EIGRPNetworks {
  4296. if net.ID == id {
  4297. continue
  4298. }
  4299. newNets = append(newNets, net)
  4300. }
  4301. m.config.EIGRPNetworks = newNets
  4302. if err := m.save(); err != nil {
  4303. return err
  4304. }
  4305. return m.applyFRREigrpConfig()
  4306. }
  4307. func (m *Manager) ListEIGRPNeighborsLive() []EIGRPNeighborLive {
  4308. if _, err := exec.LookPath("vtysh"); err != nil {
  4309. return []EIGRPNeighborLive{}
  4310. }
  4311. out, err := exec.Command("vtysh", "-c", "show ip eigrp neighbors").CombinedOutput()
  4312. if err != nil {
  4313. return []EIGRPNeighborLive{}
  4314. }
  4315. lines := strings.Split(string(out), "\n")
  4316. var res []EIGRPNeighborLive
  4317. curAS := 0
  4318. for _, line := range lines {
  4319. trimmed := strings.TrimSpace(line)
  4320. if strings.Contains(trimmed, "AS(") {
  4321. if idx := strings.Index(trimmed, "AS("); idx != -1 {
  4322. sub := trimmed[idx+3:]
  4323. if endIdx := strings.Index(sub, ")"); endIdx != -1 {
  4324. fmt.Sscanf(sub[:endIdx], "%d", &curAS)
  4325. }
  4326. }
  4327. continue
  4328. }
  4329. fields := strings.Fields(trimmed)
  4330. if len(fields) >= 7 && len(fields[0]) > 0 && fields[0][0] >= '0' && fields[0][0] <= '9' {
  4331. nbr := EIGRPNeighborLive{
  4332. AS: curAS,
  4333. Address: fields[1],
  4334. Interface: fields[2],
  4335. Uptime: fields[4],
  4336. }
  4337. fmt.Sscanf(fields[3], "%d", &nbr.HoldTime)
  4338. fmt.Sscanf(fields[5], "%d", &nbr.SRTT)
  4339. fmt.Sscanf(fields[6], "%d", &nbr.RTO)
  4340. if len(fields) >= 9 {
  4341. fmt.Sscanf(fields[8], "%d", &nbr.SeqNum)
  4342. }
  4343. res = append(res, nbr)
  4344. }
  4345. }
  4346. return res
  4347. }
  4348. func (m *Manager) ListEIGRPTopologyLive() []EIGRPRouteLive {
  4349. if _, err := exec.LookPath("vtysh"); err != nil {
  4350. return []EIGRPRouteLive{}
  4351. }
  4352. out, err := exec.Command("vtysh", "-c", "show ip eigrp topology").CombinedOutput()
  4353. if err != nil {
  4354. return []EIGRPRouteLive{}
  4355. }
  4356. lines := strings.Split(string(out), "\n")
  4357. var res []EIGRPRouteLive
  4358. curAS := 0
  4359. var curRoute *EIGRPRouteLive
  4360. for _, line := range lines {
  4361. trimmed := strings.TrimSpace(line)
  4362. if strings.Contains(trimmed, "AS(") {
  4363. if idx := strings.Index(trimmed, "AS("); idx != -1 {
  4364. sub := trimmed[idx+3:]
  4365. if endIdx := strings.Index(sub, ")"); endIdx != -1 {
  4366. fmt.Sscanf(sub[:endIdx], "%d", &curAS)
  4367. }
  4368. }
  4369. continue
  4370. }
  4371. if strings.HasPrefix(trimmed, "P ") || strings.HasPrefix(trimmed, "A ") {
  4372. fields := strings.Fields(trimmed)
  4373. if len(fields) >= 2 {
  4374. r := EIGRPRouteLive{
  4375. AS: curAS,
  4376. State: fields[0],
  4377. Prefix: strings.TrimSuffix(fields[1], ","),
  4378. }
  4379. for i := 2; i < len(fields)-1; i++ {
  4380. if fields[i] == "successors," && i > 0 {
  4381. fmt.Sscanf(fields[i-1], "%d", &r.Successors)
  4382. }
  4383. if fields[i] == "is" && i < len(fields)-1 {
  4384. fmt.Sscanf(strings.TrimSuffix(fields[i+1], ","), "%d", &r.Distance)
  4385. }
  4386. }
  4387. curRoute = &r
  4388. }
  4389. continue
  4390. }
  4391. if strings.HasPrefix(trimmed, "via ") && curRoute != nil {
  4392. sub := strings.TrimPrefix(trimmed, "via ")
  4393. parts := strings.Split(sub, ",")
  4394. if len(parts) >= 2 {
  4395. curRoute.NextHop = strings.TrimSpace(parts[0])
  4396. curRoute.Interface = strings.TrimSpace(parts[1])
  4397. } else {
  4398. curRoute.NextHop = strings.TrimSpace(sub)
  4399. }
  4400. res = append(res, *curRoute)
  4401. curRoute = nil
  4402. }
  4403. }
  4404. return res
  4405. }