manager.go 103 KB

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