manager.go 122 KB

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