manager.go 105 KB

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