manager.go 131 KB

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