manager.go 108 KB

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