manager.go 131 KB

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