manager.go 122 KB

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