manager.go 100 KB

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