manager.go 135 KB

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