manager.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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/proxmox-router/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. DefaultMetric: 10,
  79. },
  80. OSPFAreas: []OSPFArea{
  81. {
  82. ID: "area-default",
  83. Name: "Default",
  84. Instance: "Default",
  85. AreaID: "0.0.0.0",
  86. AreaType: "default",
  87. },
  88. },
  89. OSPFAreaRanges: []OSPFAreaRange{},
  90. OSPFInterfaces: []OSPFInterface{},
  91. OSPFStaticNbrs: []OSPFStaticNeighbor{},
  92. RoutingFilters: []RoutingFilterRule{},
  93. RoutingCommunityLists: []RoutingFilterCommunityList{},
  94. RoutingASLists: []RoutingFilterASList{},
  95. }
  96. }
  97. func (m *Manager) load() error {
  98. m.mu.Lock()
  99. defer m.mu.Unlock()
  100. data, err := os.ReadFile(m.configPath)
  101. if err != nil {
  102. return err
  103. }
  104. if err := json.Unmarshal(data, &m.config); err != nil {
  105. return err
  106. }
  107. if m.config.RoutingCommunityLists == nil {
  108. m.config.RoutingCommunityLists = []RoutingFilterCommunityList{}
  109. }
  110. if m.config.RoutingASLists == nil {
  111. m.config.RoutingASLists = []RoutingFilterASList{}
  112. }
  113. if len(m.config.OSPFInstances) == 0 {
  114. rID := m.config.OSPFInstance.RouterID
  115. if rID == "" {
  116. rID = "192.168.131.56"
  117. }
  118. m.config.OSPFInstances = []OSPFInstance{
  119. {
  120. ID: "ospf-inst-default",
  121. Name: "Default",
  122. Version: 2,
  123. VRF: "main",
  124. RouterID: rID,
  125. RoutingTable: "main",
  126. Enabled: true,
  127. },
  128. }
  129. }
  130. if len(m.config.OSPFAreas) == 0 {
  131. m.config.OSPFAreas = []OSPFArea{
  132. {
  133. ID: "area-default",
  134. Name: "Default",
  135. Instance: "Default",
  136. AreaID: "0.0.0.0",
  137. AreaType: "default",
  138. },
  139. }
  140. }
  141. return nil
  142. }
  143. func (m *Manager) save() error {
  144. dir := filepath.Dir(m.configPath)
  145. if err := os.MkdirAll(dir, 0755); err != nil {
  146. return err
  147. }
  148. data, err := json.MarshalIndent(m.config, "", " ")
  149. if err != nil {
  150. return err
  151. }
  152. return os.WriteFile(m.configPath, data, 0644)
  153. }
  154. // sanitizeIdentifier creates a valid BIRD protocol/function identifier: [a-zA-Z][a-zA-Z0-9_]*
  155. func sanitizeIdentifier(prefix, raw string) string {
  156. reg := regexp.MustCompile("[^a-zA-Z0-9_]+")
  157. cleaned := reg.ReplaceAllString(raw, "_")
  158. cleaned = strings.Trim(cleaned, "_")
  159. if cleaned == "" {
  160. cleaned = "inst"
  161. }
  162. res := cleaned
  163. if prefix != "" {
  164. res = prefix + "_" + cleaned
  165. }
  166. if len(res) > 32 {
  167. res = res[:32]
  168. }
  169. return res
  170. }
  171. // applyBirdConfig generates /etc/bird/bird.conf and live reloads BIRD daemon
  172. func (m *Manager) applyBirdConfig() error {
  173. var sb strings.Builder
  174. routerID := "192.168.131.56"
  175. if m.config.BGPInstance.RouterID != "" {
  176. routerID = m.config.BGPInstance.RouterID
  177. } else if m.config.OSPFInstance.RouterID != "" {
  178. routerID = m.config.OSPFInstance.RouterID
  179. }
  180. sb.WriteString("# /etc/bird/bird.conf\n")
  181. sb.WriteString("# Generated dynamically by Proxmox Router (BIRD 2 Engine)\n\n")
  182. sb.WriteString("timeformat protocol iso long;\n")
  183. sb.WriteString("timeformat base iso long;\n")
  184. sb.WriteString("timeformat log iso long;\n")
  185. sb.WriteString("log syslog all;\n")
  186. sb.WriteString(fmt.Sprintf("router id %s;\n\n", routerID))
  187. // Base system protocols
  188. sb.WriteString("protocol device {\n")
  189. sb.WriteString(" scan time 10;\n")
  190. sb.WriteString("}\n\n")
  191. sb.WriteString("protocol direct {\n")
  192. sb.WriteString(" ipv4;\n")
  193. sb.WriteString("}\n\n")
  194. sb.WriteString("protocol kernel {\n")
  195. sb.WriteString(" metric 0;\n")
  196. sb.WriteString(" ipv4 {\n")
  197. sb.WriteString(" export filter {\n")
  198. sb.WriteString(" if source = RTS_DEVICE then reject;\n")
  199. sb.WriteString(" if source = RTS_BGP then {\n")
  200. sb.WriteString(" if bgp_path.first = bgp_path.last && bgp_path.len = 0 then\n")
  201. sb.WriteString(" krt_metric = 200;\n")
  202. sb.WriteString(" else\n")
  203. sb.WriteString(" krt_metric = 20;\n")
  204. sb.WriteString(" }\n")
  205. sb.WriteString(" if source = RTS_OSPF then {\n")
  206. sb.WriteString(" krt_metric = 110;\n")
  207. sb.WriteString(" }\n")
  208. sb.WriteString(" if source = RTS_RIP then {\n")
  209. sb.WriteString(" krt_metric = 120;\n")
  210. sb.WriteString(" }\n")
  211. sb.WriteString(" if source ~ [ RTS_STATIC, RTS_INHERIT ] then {\n")
  212. sb.WriteString(" krt_metric = 255;\n")
  213. sb.WriteString(" }\n")
  214. sb.WriteString(" accept;\n")
  215. sb.WriteString(" };\n")
  216. sb.WriteString(" };\n")
  217. sb.WriteString(" learn;\n")
  218. sb.WriteString("}\n\n")
  219. // Static BGP Networks announcements
  220. var activeNets []string
  221. if m.config.BGPInstance.Enabled {
  222. for _, net := range m.config.BGPNetworks {
  223. if !net.Disabled && strings.TrimSpace(net.Network) != "" {
  224. activeNets = append(activeNets, strings.TrimSpace(net.Network))
  225. }
  226. }
  227. }
  228. if len(activeNets) > 0 {
  229. sb.WriteString("protocol static bgp_static_nets {\n")
  230. sb.WriteString(" ipv4;\n")
  231. for _, n := range activeNets {
  232. sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", n))
  233. }
  234. sb.WriteString("}\n\n")
  235. }
  236. // Community Lists (/routing filter community-list)
  237. for _, cl := range m.config.RoutingCommunityLists {
  238. if cl.Disabled || strings.TrimSpace(cl.Name) == "" || len(cl.Communities) == 0 {
  239. continue
  240. }
  241. var items []string
  242. for _, c := range cl.Communities {
  243. c = strings.TrimSpace(c)
  244. if strings.Contains(c, ":") {
  245. parts := strings.Split(c, ":")
  246. items = append(items, fmt.Sprintf("(%s, %s)", strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
  247. }
  248. }
  249. if len(items) > 0 {
  250. sb.WriteString(fmt.Sprintf("define comm_%s = [ %s ];\n", sanitizeIdentifier("", cl.Name), strings.Join(items, ", ")))
  251. }
  252. }
  253. // AS Lists (/routing filter num-list)
  254. for _, al := range m.config.RoutingASLists {
  255. if al.Disabled || strings.TrimSpace(al.Name) == "" || strings.TrimSpace(al.Range) == "" {
  256. continue
  257. }
  258. rng := strings.TrimSpace(al.Range)
  259. rng = regexp.MustCompile(`(\d+)\s*-\s*(\d+)`).ReplaceAllString(rng, "$1..$2")
  260. sb.WriteString(fmt.Sprintf("define aslist_%s = [ %s ];\n", sanitizeIdentifier("", al.Name), rng))
  261. }
  262. sb.WriteString("\n")
  263. // Routing Filters (/routing filter)
  264. chainRules := make(map[string][]RoutingFilterRule)
  265. for _, rule := range m.config.RoutingFilters {
  266. if rule.Disabled || strings.TrimSpace(rule.Chain) == "" {
  267. continue
  268. }
  269. chain := strings.TrimSpace(rule.Chain)
  270. chainRules[chain] = append(chainRules[chain], rule)
  271. }
  272. for chain, rules := range chainRules {
  273. sort.Slice(rules, func(i, j int) bool {
  274. return rules[i].RuleOrder < rules[j].RuleOrder
  275. })
  276. filterName := sanitizeIdentifier("filter", chain)
  277. fnName := fmt.Sprintf("fn_%s", filterName)
  278. // Procedural function for this chain
  279. sb.WriteString(fmt.Sprintf("function %s() {\n", fnName))
  280. for _, r := range rules {
  281. rendered := translateRos7RuleToBird(&r)
  282. if rendered != "" {
  283. sb.WriteString(fmt.Sprintf(" # rule %d\n", r.RuleOrder))
  284. lines := strings.Split(rendered, "\n")
  285. for _, l := range lines {
  286. if strings.TrimSpace(l) != "" {
  287. sb.WriteString(" " + l + "\n")
  288. }
  289. }
  290. }
  291. }
  292. sb.WriteString("}\n\n")
  293. // Standalone filter for import and general use (unmatched routes rejected by default)
  294. sb.WriteString(fmt.Sprintf("filter %s {\n", filterName))
  295. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  296. sb.WriteString(" reject;\n")
  297. sb.WriteString("}\n\n")
  298. }
  299. // BGP Protocols (True Multi-Instance / Multi-AS support!)
  300. if m.config.BGPInstance.Enabled {
  301. for i, peer := range m.config.BGPPeers {
  302. if peer.RemoteAddress == "" || peer.RemoteAS == 0 {
  303. continue
  304. }
  305. // Local AS determination: peer.LocalAS if set, otherwise global AS
  306. localAS := m.config.BGPInstance.AS
  307. if peer.LocalAS > 0 {
  308. localAS = peer.LocalAS
  309. }
  310. protoName := sanitizeIdentifier("bgp", fmt.Sprintf("%s_%d", peer.ID, i))
  311. // Per-peer Output Networks (RouterOS v7 output.network)
  312. var peerNets []string
  313. for _, on := range peer.OutputNetworks {
  314. on = strings.TrimSpace(on)
  315. if on != "" {
  316. peerNets = append(peerNets, on)
  317. }
  318. }
  319. if peer.DefaultOriginate {
  320. peerNets = append(peerNets, "0.0.0.0/0")
  321. }
  322. peerNetsProto := ""
  323. if len(peerNets) > 0 {
  324. peerNetsProto = fmt.Sprintf("bgp_nets_%s", protoName)
  325. sb.WriteString(fmt.Sprintf("protocol static %s {\n", peerNetsProto))
  326. sb.WriteString(" ipv4;\n")
  327. for _, pn := range peerNets {
  328. sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", pn))
  329. }
  330. sb.WriteString("}\n\n")
  331. }
  332. sb.WriteString(fmt.Sprintf("protocol bgp %s {\n", protoName))
  333. if peer.Name != "" {
  334. sb.WriteString(fmt.Sprintf(" description \"%s\";\n", peer.Name))
  335. }
  336. if peer.Disabled {
  337. sb.WriteString(" disabled;\n")
  338. }
  339. if peer.LocalAddress != "" {
  340. if peer.LocalPort > 0 {
  341. sb.WriteString(fmt.Sprintf(" local %s port %d as %d;\n", peer.LocalAddress, peer.LocalPort, localAS))
  342. } else {
  343. sb.WriteString(fmt.Sprintf(" local %s as %d;\n", peer.LocalAddress, localAS))
  344. }
  345. } else {
  346. if peer.LocalPort > 0 {
  347. sb.WriteString(fmt.Sprintf(" local port %d as %d;\n", peer.LocalPort, localAS))
  348. } else {
  349. sb.WriteString(fmt.Sprintf(" local as %d;\n", localAS))
  350. }
  351. }
  352. if peer.RemotePort > 0 {
  353. sb.WriteString(fmt.Sprintf(" neighbor %s port %d as %d;\n", peer.RemoteAddress, peer.RemotePort, peer.RemoteAS))
  354. } else {
  355. sb.WriteString(fmt.Sprintf(" neighbor %s as %d;\n", peer.RemoteAddress, peer.RemoteAS))
  356. }
  357. if peer.Multihop {
  358. sb.WriteString(" multihop;\n")
  359. }
  360. if peer.Passive || (!peer.Connect && peer.Listen) {
  361. sb.WriteString(" passive;\n")
  362. }
  363. if peer.Password != "" {
  364. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", peer.Password))
  365. }
  366. holdTime := 180
  367. if peer.HoldTime > 0 {
  368. holdTime = peer.HoldTime
  369. } else if m.config.BGPInstance.HoldTime > 0 {
  370. holdTime = m.config.BGPInstance.HoldTime
  371. }
  372. sb.WriteString(fmt.Sprintf(" hold time %d;\n", holdTime))
  373. if peer.KeepaliveTime > 0 {
  374. sb.WriteString(fmt.Sprintf(" keepalive time %d;\n", peer.KeepaliveTime))
  375. }
  376. // IPv4 Channel
  377. sb.WriteString(" ipv4 {\n")
  378. if peer.NexthopSelf || peer.NexthopChoice == "force-self" {
  379. sb.WriteString(" next hop self;\n")
  380. }
  381. // Import Filter
  382. defaultAD := 20
  383. if peer.LocalRole == "ibgp" || (localAS > 0 && peer.RemoteAS > 0 && localAS == peer.RemoteAS) {
  384. defaultAD = 200
  385. }
  386. if peer.InFilter != "" && len(chainRules[peer.InFilter]) > 0 {
  387. sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", peer.InFilter)))
  388. } else {
  389. sb.WriteString(fmt.Sprintf(" import filter { krt_metric = %d; accept; };\n", defaultAD))
  390. }
  391. // Export Filter
  392. if peer.OutFilter != "" && len(chainRules[peer.OutFilter]) > 0 {
  393. fnName := fmt.Sprintf("fn_%s", sanitizeIdentifier("filter", peer.OutFilter))
  394. sb.WriteString(" export filter {\n")
  395. sb.WriteString(fmt.Sprintf(" %s();\n", fnName))
  396. if peerNetsProto != "" {
  397. sb.WriteString(fmt.Sprintf(" if proto = \"%s\" then accept;\n", peerNetsProto))
  398. }
  399. if len(activeNets) > 0 {
  400. sb.WriteString(" if proto = \"bgp_static_nets\" then accept;\n")
  401. }
  402. if peer.RedistConnected || m.config.BGPInstance.RedistributeConnected {
  403. sb.WriteString(" if source = RTS_DEVICE then accept;\n")
  404. }
  405. if peer.RedistStatic || m.config.BGPInstance.RedistributeStatic {
  406. sb.WriteString(" if source ~ [ RTS_STATIC, RTS_INHERIT ] then accept;\n")
  407. }
  408. if peer.RedistOSPF || m.config.BGPInstance.RedistributeOSPF {
  409. sb.WriteString(" if source = RTS_OSPF then accept;\n")
  410. }
  411. sb.WriteString(" reject;\n")
  412. sb.WriteString(" };\n")
  413. } else {
  414. var exportSources []string
  415. if peerNetsProto != "" {
  416. exportSources = append(exportSources, fmt.Sprintf(`proto = "%s"`, peerNetsProto))
  417. }
  418. if len(activeNets) > 0 {
  419. exportSources = append(exportSources, `proto = "bgp_static_nets"`)
  420. }
  421. exportSources = append(exportSources, `source = RTS_BGP`)
  422. if peer.RedistConnected || m.config.BGPInstance.RedistributeConnected {
  423. exportSources = append(exportSources, `source = RTS_DEVICE`)
  424. }
  425. if peer.RedistStatic || m.config.BGPInstance.RedistributeStatic {
  426. exportSources = append(exportSources, `source ~ [ RTS_STATIC, RTS_INHERIT ]`)
  427. }
  428. if peer.RedistOSPF || m.config.BGPInstance.RedistributeOSPF {
  429. exportSources = append(exportSources, `source = RTS_OSPF`)
  430. }
  431. if len(exportSources) > 0 {
  432. sb.WriteString(fmt.Sprintf(" export where (%s);\n", strings.Join(exportSources, ") || (")))
  433. } else {
  434. sb.WriteString(" export none;\n")
  435. }
  436. }
  437. sb.WriteString(" };\n")
  438. sb.WriteString("}\n\n")
  439. }
  440. }
  441. // OSPFv2 Protocols (RouterOS v7 Multi-Instance OSPF)
  442. ospfInstances := m.config.OSPFInstances
  443. if len(ospfInstances) == 0 {
  444. ospfInstances = []OSPFInstance{
  445. {
  446. ID: "ospf-inst-default",
  447. Name: "Default",
  448. Version: 2,
  449. VRF: "main",
  450. RouterID: routerID,
  451. RoutingTable: "main",
  452. Enabled: true,
  453. },
  454. }
  455. }
  456. for _, inst := range ospfInstances {
  457. if inst.Disabled {
  458. continue
  459. }
  460. instRouterID := inst.RouterID
  461. if instRouterID == "" {
  462. instRouterID = routerID
  463. }
  464. instProtoName := sanitizeIdentifier("ospf", inst.Name)
  465. sb.WriteString(fmt.Sprintf("protocol ospf v%d %s {\n", inst.Version, instProtoName))
  466. sb.WriteString(fmt.Sprintf(" router id %s;\n", instRouterID))
  467. sb.WriteString(" ipv4 {\n")
  468. sb.WriteString(" import filter { krt_metric = 110; accept; };\n")
  469. var ospfExports []string
  470. ospfExports = append(ospfExports, "RTS_STATIC", "RTS_INHERIT")
  471. if inst.RedistributeConnected || m.config.OSPFInstance.RedistributeConnected {
  472. ospfExports = append(ospfExports, "RTS_DEVICE")
  473. }
  474. if inst.RedistributeBGP || m.config.OSPFInstance.RedistributeBGP {
  475. ospfExports = append(ospfExports, "RTS_BGP")
  476. }
  477. if len(ospfExports) > 0 {
  478. sb.WriteString(fmt.Sprintf(" export where source ~ [ %s ];\n", strings.Join(ospfExports, ", ")))
  479. } else {
  480. sb.WriteString(" export none;\n")
  481. }
  482. sb.WriteString(" };\n\n")
  483. // Areas for this instance
  484. areas := m.config.OSPFAreas
  485. if len(areas) == 0 {
  486. areas = []OSPFArea{
  487. {
  488. Name: "Default",
  489. Instance: inst.Name,
  490. AreaID: "0.0.0.0",
  491. AreaType: "default",
  492. },
  493. }
  494. }
  495. for _, area := range areas {
  496. if area.Disabled {
  497. continue
  498. }
  499. if area.Instance != "" && !strings.EqualFold(area.Instance, inst.Name) && !strings.EqualFold(area.Instance, "Default") {
  500. continue
  501. }
  502. areaID := strings.TrimSpace(area.AreaID)
  503. if areaID == "" {
  504. areaID = "0.0.0.0"
  505. }
  506. sb.WriteString(fmt.Sprintf(" area %s {\n", areaID))
  507. if area.AreaType == "stub" {
  508. sb.WriteString(" stub;\n")
  509. } else if area.AreaType == "nssa" {
  510. sb.WriteString(" nssa;\n")
  511. }
  512. // Area ranges (stubnet)
  513. for _, ar := range m.config.OSPFAreaRanges {
  514. if ar.Disabled {
  515. continue
  516. }
  517. if strings.EqualFold(ar.Area, area.Name) || strings.EqualFold(ar.Area, area.AreaID) || ar.Area == "" {
  518. prefix := strings.TrimSpace(ar.Prefix)
  519. if prefix != "" {
  520. if ar.Cost > 0 {
  521. sb.WriteString(fmt.Sprintf(" stubnet %s { cost %d; };\n", prefix, ar.Cost))
  522. } else {
  523. sb.WriteString(fmt.Sprintf(" stubnet %s;\n", prefix))
  524. }
  525. }
  526. }
  527. }
  528. // Interface templates matching this area
  529. for _, iface := range m.config.OSPFInterfaces {
  530. if iface.Disabled {
  531. continue
  532. }
  533. if iface.Area != "" && !strings.EqualFold(iface.Area, area.Name) && !strings.EqualFold(iface.Area, area.AreaID) && iface.Area != "Default" {
  534. continue
  535. }
  536. ifaceName := strings.TrimSpace(iface.Interfaces)
  537. if ifaceName == "" {
  538. ifaceName = strings.TrimSpace(iface.Interface)
  539. }
  540. netName := strings.TrimSpace(iface.Networks)
  541. if netName == "" {
  542. netName = strings.TrimSpace(iface.Network)
  543. }
  544. var target string
  545. if ifaceName != "" && netName != "" {
  546. target = fmt.Sprintf("\"%s\", %s", ifaceName, netName)
  547. } else if ifaceName != "" {
  548. target = fmt.Sprintf("\"%s\"", ifaceName)
  549. } else if netName != "" {
  550. target = netName
  551. } else {
  552. target = "\"*\""
  553. }
  554. sb.WriteString(fmt.Sprintf(" interface %s {\n", target))
  555. if iface.Cost > 0 {
  556. sb.WriteString(fmt.Sprintf(" cost %d;\n", iface.Cost))
  557. }
  558. if iface.Priority > 0 {
  559. sb.WriteString(fmt.Sprintf(" priority %d;\n", iface.Priority))
  560. }
  561. if iface.HelloInterval > 0 {
  562. sb.WriteString(fmt.Sprintf(" hello %d;\n", iface.HelloInterval))
  563. }
  564. if iface.DeadInterval > 0 {
  565. sb.WriteString(fmt.Sprintf(" dead %d;\n", iface.DeadInterval))
  566. }
  567. if iface.Passive {
  568. sb.WriteString(" stub;\n")
  569. } else {
  570. netType := strings.ToLower(strings.TrimSpace(iface.NetworkType))
  571. if netType == "ptp" || netType == "point-to-point" {
  572. sb.WriteString(" type ptp;\n")
  573. } else {
  574. sb.WriteString(" type broadcast;\n")
  575. }
  576. }
  577. auth := strings.ToLower(iface.Auth)
  578. if auth == "" {
  579. auth = strings.ToLower(iface.AuthType)
  580. }
  581. if auth == "md5" && iface.AuthKey != "" {
  582. sb.WriteString(" authentication cryptographic;\n")
  583. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  584. } else if auth == "simple" && iface.AuthKey != "" {
  585. sb.WriteString(" authentication simple;\n")
  586. sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
  587. }
  588. sb.WriteString(" };\n")
  589. }
  590. sb.WriteString(" };\n")
  591. }
  592. sb.WriteString("}\n\n")
  593. }
  594. // Ensure directory exists with proper permissions
  595. dir := filepath.Dir(birdConfigPath)
  596. if err := os.MkdirAll(dir, 0775); err == nil {
  597. _ = os.Chmod(dir, 0775)
  598. _ = exec.Command("chown", "root:bird", dir).Run()
  599. }
  600. // Write candidate configuration to temporary file
  601. tmpPath := birdConfigPath + ".new"
  602. if err := os.WriteFile(tmpPath, []byte(sb.String()), 0664); err != nil {
  603. return fmt.Errorf("failed to write %s: %w", tmpPath, err)
  604. }
  605. _ = exec.Command("chown", "root:bird", tmpPath).Run()
  606. // Validate syntax with bird -p
  607. out, err := exec.Command("bird", "-p", "-c", tmpPath).CombinedOutput()
  608. if err != nil {
  609. _ = os.Remove(tmpPath)
  610. return fmt.Errorf("bird syntax check failed: %s: %w", string(out), err)
  611. }
  612. // Replace active config
  613. if err := os.Rename(tmpPath, birdConfigPath); err != nil {
  614. return fmt.Errorf("failed to replace %s: %w", birdConfigPath, err)
  615. }
  616. _ = os.Chmod(birdConfigPath, 0664)
  617. _ = exec.Command("chown", "root:bird", birdConfigPath).Run()
  618. // Ensure BIRD systemd service is active
  619. _ = exec.Command("systemctl", "start", "bird").Run()
  620. // Live reload without packet loss
  621. reloadOut, reloadErr := birdcExec("configure")
  622. if reloadErr != nil {
  623. return fmt.Errorf("BIRD reload failed: %s: %w", string(reloadOut), reloadErr)
  624. }
  625. // Synchronize kernel blackhole routes (distance 255) for all active advertised prefixes
  626. m.syncKernelBlackholeRoutes()
  627. return nil
  628. }
  629. func birdcExec(cmd string) ([]byte, error) {
  630. return exec.Command("birdc", cmd).CombinedOutput()
  631. }
  632. // syncKernelBlackholeRoutes ensures all BGP advertised networks (global BGP networks and peer OutputNetworks)
  633. // have corresponding blackhole routes with metric 255 installed in the Linux kernel routing table.
  634. // This guarantees that BGP can announce these prefixes reliably into the RIB/FIB, while ensuring any active
  635. // connected/local routes take precedence (metric 0 < metric 255) and prevents routing loops if subnets are incomplete.
  636. func (m *Manager) syncKernelBlackholeRoutes() {
  637. desired := make(map[string]bool)
  638. if m.config.BGPInstance.Enabled {
  639. for _, n := range m.config.BGPNetworks {
  640. cidr := strings.TrimSpace(n.Network)
  641. if !n.Disabled && cidr != "" {
  642. if _, _, err := net.ParseCIDR(cidr); err == nil {
  643. desired[cidr] = true
  644. }
  645. }
  646. }
  647. for _, p := range m.config.BGPPeers {
  648. if p.Disabled {
  649. continue
  650. }
  651. for _, on := range p.OutputNetworks {
  652. cidr := strings.TrimSpace(on)
  653. if cidr != "" {
  654. if _, _, err := net.ParseCIDR(cidr); err == nil {
  655. desired[cidr] = true
  656. }
  657. }
  658. }
  659. }
  660. }
  661. // Query existing kernel blackhole routes with metric 255
  662. out, err := exec.Command("ip", "route", "show", "type", "blackhole").Output()
  663. existing := make(map[string]bool)
  664. if err == nil {
  665. lines := strings.Split(string(out), "\n")
  666. for _, line := range lines {
  667. line = strings.TrimSpace(line)
  668. if line == "" {
  669. continue
  670. }
  671. parts := strings.Fields(line)
  672. if len(parts) >= 2 && parts[0] == "blackhole" {
  673. dst := parts[1]
  674. if strings.Contains(line, "metric 255") {
  675. existing[dst] = true
  676. }
  677. }
  678. }
  679. }
  680. // Install desired blackhole routes with metric 255 proto static
  681. for cidr := range desired {
  682. if !existing[cidr] {
  683. cmd := exec.Command("ip", "route", "replace", "blackhole", cidr, "metric", "255", "proto", "static")
  684. if out, err := cmd.CombinedOutput(); err != nil {
  685. log.Printf("[DynamicRouting] Warning: failed to install kernel blackhole route %s: %s (%v)", cidr, string(out), err)
  686. } else {
  687. log.Printf("[DynamicRouting] Installed kernel blackhole route %s with metric 255 (BGP advertised)", cidr)
  688. }
  689. }
  690. }
  691. // Cleanup any obsolete blackhole routes that were previously installed with metric 255
  692. // Check static_routes.json first to ensure we don't delete user's manual static routes
  693. userManualStaticBlackholes := make(map[string]bool)
  694. if data, err := os.ReadFile("/etc/proxmox-router/routing/static_routes.json"); err == nil {
  695. var userRoutes []struct {
  696. DstAddress string `json:"dst_address"`
  697. Gateway string `json:"gateway"`
  698. Action string `json:"action"`
  699. Disabled bool `json:"disabled"`
  700. }
  701. if json.Unmarshal(data, &userRoutes) == nil {
  702. for _, ur := range userRoutes {
  703. if !ur.Disabled && (strings.EqualFold(ur.Gateway, "blackhole") || strings.EqualFold(ur.Action, "blackhole")) {
  704. userManualStaticBlackholes[strings.TrimSpace(ur.DstAddress)] = true
  705. }
  706. }
  707. }
  708. }
  709. for cidr := range existing {
  710. if !desired[cidr] && !userManualStaticBlackholes[cidr] {
  711. _ = exec.Command("ip", "route", "del", "blackhole", cidr, "metric", "255").Run()
  712. log.Printf("[DynamicRouting] Removed obsolete kernel blackhole route %s metric 255", cidr)
  713. }
  714. }
  715. }
  716. // -------------------------------------------------------------
  717. // BGP API & Operations (Multi-Instance BGP)
  718. // -------------------------------------------------------------
  719. func (m *Manager) GetBGPInstance() BGPInstance {
  720. m.mu.RLock()
  721. defer m.mu.RUnlock()
  722. inst := m.config.BGPInstance
  723. out, err := birdcExec("show status")
  724. if err == nil && strings.Contains(string(out), "Daemon is up and running") && inst.Enabled {
  725. inst.Running = true
  726. }
  727. return inst
  728. }
  729. func (m *Manager) UpdateBGPInstance(inst BGPInstance) error {
  730. m.mu.Lock()
  731. m.config.BGPInstance = inst
  732. _ = m.save()
  733. m.mu.Unlock()
  734. return m.applyBirdConfig()
  735. }
  736. func (m *Manager) ListBGPPeers() []BGPPeer {
  737. m.mu.RLock()
  738. defer m.mu.RUnlock()
  739. peers := make([]BGPPeer, len(m.config.BGPPeers))
  740. copy(peers, m.config.BGPPeers)
  741. // Fetch live peer telemetry from birdc
  742. out, err := birdcExec("show protocols all")
  743. if err == nil {
  744. type livePeerData struct {
  745. State string
  746. RemoteAddr string
  747. RemoteAS uint32
  748. LocalAS uint32
  749. PfxRcd int
  750. PfxSnt int
  751. Uptime string
  752. }
  753. liveMap := make(map[string]*livePeerData)
  754. lines := strings.Split(string(out), "\n")
  755. var cur *livePeerData
  756. now := time.Now()
  757. for _, line := range lines {
  758. trimmed := strings.TrimSpace(line)
  759. // A protocol header line in BIRD is unindented and has "BGP" in column 2
  760. if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
  761. fields := strings.Fields(line)
  762. if len(fields) >= 2 && fields[1] == "BGP" {
  763. cur = &livePeerData{}
  764. var sinceStr string
  765. if len(fields) >= 6 && strings.Contains(fields[4], "-") && strings.Contains(fields[5], ":") {
  766. sinceStr = fields[4] + " " + fields[5]
  767. } else if len(fields) >= 5 {
  768. sinceStr = fields[4]
  769. }
  770. cur.Uptime = parseBirdSinceToUptime(sinceStr, now)
  771. } else {
  772. cur = nil
  773. }
  774. }
  775. if cur == nil {
  776. continue
  777. }
  778. if strings.HasPrefix(trimmed, "BGP state:") {
  779. cur.State = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP state:"))
  780. } else if strings.HasPrefix(trimmed, "Neighbor address:") {
  781. cur.RemoteAddr = strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor address:"))
  782. liveMap[cur.RemoteAddr] = cur
  783. } else if strings.HasPrefix(trimmed, "Neighbor AS:") {
  784. v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor AS:")), 10, 32)
  785. cur.RemoteAS = uint32(v)
  786. } else if strings.HasPrefix(trimmed, "Local AS:") {
  787. v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Local AS:")), 10, 32)
  788. cur.LocalAS = uint32(v)
  789. } else if strings.HasPrefix(trimmed, "Routes:") {
  790. parts := strings.Split(trimmed, ",")
  791. for _, p := range parts {
  792. p = strings.TrimSpace(p)
  793. if strings.Contains(p, "imported") {
  794. f := strings.Fields(p)
  795. if len(f) >= 2 {
  796. cur.PfxRcd, _ = strconv.Atoi(f[len(f)-2])
  797. }
  798. } else if strings.Contains(p, "exported") {
  799. f := strings.Fields(p)
  800. if len(f) >= 2 {
  801. cur.PfxSnt, _ = strconv.Atoi(f[0])
  802. }
  803. }
  804. }
  805. }
  806. }
  807. for i := range peers {
  808. if live, ok := liveMap[peers[i].RemoteAddress]; ok {
  809. peers[i].State = live.State
  810. if live.State == "Established" {
  811. peers[i].Uptime = live.Uptime
  812. } else {
  813. peers[i].Uptime = ""
  814. }
  815. peers[i].PrefixReceived = live.PfxRcd
  816. peers[i].PrefixSent = live.PfxSnt
  817. if peers[i].LocalAS == 0 && live.LocalAS > 0 {
  818. peers[i].LocalAS = live.LocalAS
  819. }
  820. } else if peers[i].Disabled {
  821. peers[i].State = "Disabled"
  822. peers[i].Uptime = ""
  823. } else {
  824. peers[i].State = "Idle"
  825. peers[i].Uptime = ""
  826. }
  827. }
  828. }
  829. return peers
  830. }
  831. func parseBirdSinceToUptime(sinceStr string, now time.Time) string {
  832. sinceStr = strings.TrimSpace(sinceStr)
  833. if sinceStr == "" {
  834. return ""
  835. }
  836. // Case 1: "2006-01-02 15:04:05" (ISO long)
  837. if t, err := time.ParseInLocation("2006-01-02 15:04:05", sinceStr, time.Local); err == nil {
  838. return formatDuration(now.Sub(t))
  839. }
  840. // Case 2: "2006-01-02 15:04:05.999" (ISO long with milliseconds)
  841. if t, err := time.ParseInLocation("2006-01-02 15:04:05.999", sinceStr, time.Local); err == nil {
  842. return formatDuration(now.Sub(t))
  843. }
  844. // Case 3: "2006-01-02" (date only)
  845. if t, err := time.ParseInLocation("2006-01-02", sinceStr, time.Local); err == nil {
  846. return formatDuration(now.Sub(t))
  847. }
  848. // Case 4: "15:04:05" or "15:04:05.123" (time only, happened today)
  849. timeOnly := sinceStr
  850. if idx := strings.IndexByte(timeOnly, '.'); idx != -1 {
  851. timeOnly = timeOnly[:idx]
  852. }
  853. if t, err := time.ParseInLocation("15:04:05", timeOnly, time.Local); err == nil {
  854. tToday := time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
  855. if tToday.After(now) {
  856. tToday = tToday.AddDate(0, 0, -1)
  857. }
  858. return formatDuration(now.Sub(tToday))
  859. }
  860. return ""
  861. }
  862. func formatDuration(d time.Duration) string {
  863. if d < 0 {
  864. d = 0
  865. }
  866. sec := int64(d.Seconds())
  867. days := sec / 86400
  868. hours := (sec % 86400) / 3600
  869. mins := (sec % 3600) / 60
  870. secs := sec % 60
  871. if days > 0 {
  872. return fmt.Sprintf("%dd %02dh %02dm %02ds", days, hours, mins, secs)
  873. }
  874. return fmt.Sprintf("%02dh %02dm %02ds", hours, mins, secs)
  875. }
  876. func (m *Manager) SaveBGPPeer(peer *BGPPeer) error {
  877. m.mu.Lock()
  878. defer m.mu.Unlock()
  879. if peer.ID == "" {
  880. peer.ID = fmt.Sprintf("bgp-peer-%d", time.Now().UnixNano())
  881. }
  882. found := false
  883. for i, p := range m.config.BGPPeers {
  884. if p.ID == peer.ID {
  885. m.config.BGPPeers[i] = *peer
  886. found = true
  887. break
  888. }
  889. }
  890. if !found {
  891. m.config.BGPPeers = append(m.config.BGPPeers, *peer)
  892. }
  893. if err := m.save(); err != nil {
  894. return err
  895. }
  896. return m.applyBirdConfig()
  897. }
  898. func (m *Manager) DeleteBGPPeer(id string) error {
  899. m.mu.Lock()
  900. defer m.mu.Unlock()
  901. newPeers := make([]BGPPeer, 0, len(m.config.BGPPeers))
  902. for _, p := range m.config.BGPPeers {
  903. if p.ID != id {
  904. newPeers = append(newPeers, p)
  905. }
  906. }
  907. m.config.BGPPeers = newPeers
  908. if err := m.save(); err != nil {
  909. return err
  910. }
  911. return m.applyBirdConfig()
  912. }
  913. func (m *Manager) SetBGPPeerState(id string, disabled bool) error {
  914. m.mu.Lock()
  915. defer m.mu.Unlock()
  916. for i := range m.config.BGPPeers {
  917. if m.config.BGPPeers[i].ID == id {
  918. m.config.BGPPeers[i].Disabled = disabled
  919. break
  920. }
  921. }
  922. if err := m.save(); err != nil {
  923. return err
  924. }
  925. return m.applyBirdConfig()
  926. }
  927. func (m *Manager) ListBGPNetworks() []BGPNetwork {
  928. m.mu.RLock()
  929. defer m.mu.RUnlock()
  930. return m.config.BGPNetworks
  931. }
  932. func (m *Manager) SaveBGPNetwork(net BGPNetwork) error {
  933. m.mu.Lock()
  934. defer m.mu.Unlock()
  935. if net.ID == "" {
  936. net.ID = fmt.Sprintf("bgp-net-%d", time.Now().UnixNano())
  937. }
  938. found := false
  939. for i, n := range m.config.BGPNetworks {
  940. if n.ID == net.ID {
  941. m.config.BGPNetworks[i] = net
  942. found = true
  943. break
  944. }
  945. }
  946. if !found {
  947. m.config.BGPNetworks = append(m.config.BGPNetworks, net)
  948. }
  949. if err := m.save(); err != nil {
  950. return err
  951. }
  952. return m.applyBirdConfig()
  953. }
  954. func (m *Manager) DeleteBGPNetwork(id string) error {
  955. m.mu.Lock()
  956. defer m.mu.Unlock()
  957. newNets := make([]BGPNetwork, 0, len(m.config.BGPNetworks))
  958. for _, n := range m.config.BGPNetworks {
  959. if n.ID != id {
  960. newNets = append(newNets, n)
  961. }
  962. }
  963. m.config.BGPNetworks = newNets
  964. if err := m.save(); err != nil {
  965. return err
  966. }
  967. return m.applyBirdConfig()
  968. }
  969. func (m *Manager) GetBGPRoutes() []BGPRoute {
  970. var routes []BGPRoute
  971. out, err := birdcExec("show route where source = RTS_BGP all")
  972. if err != nil {
  973. return routes
  974. }
  975. lines := strings.Split(string(out), "\n")
  976. var cur *BGPRoute
  977. for _, line := range lines {
  978. trimmed := strings.TrimSpace(line)
  979. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  980. continue
  981. }
  982. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  983. fields := strings.Fields(trimmed)
  984. if len(fields) >= 2 {
  985. routes = append(routes, BGPRoute{
  986. Prefix: fields[0],
  987. Best: strings.Contains(line, "*"),
  988. Origin: "IGP",
  989. })
  990. cur = &routes[len(routes)-1]
  991. }
  992. continue
  993. }
  994. if cur == nil {
  995. continue
  996. }
  997. if strings.HasPrefix(trimmed, "via ") {
  998. parts := strings.Fields(trimmed)
  999. if len(parts) >= 2 {
  1000. cur.NextHop = parts[1]
  1001. }
  1002. } else if strings.HasPrefix(trimmed, "BGP.as_path:") {
  1003. cur.Path = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.as_path:"))
  1004. } else if strings.HasPrefix(trimmed, "BGP.origin:") {
  1005. cur.Origin = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.origin:"))
  1006. } else if strings.HasPrefix(trimmed, "BGP.next_hop:") {
  1007. cur.NextHop = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.next_hop:"))
  1008. } else if strings.HasPrefix(trimmed, "BGP.med:") {
  1009. cur.Metric, _ = strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.med:")))
  1010. }
  1011. }
  1012. return routes
  1013. }
  1014. // -------------------------------------------------------------
  1015. // OSPF API & Operations (RouterOS v7 Style OSPF)
  1016. // -------------------------------------------------------------
  1017. func (m *Manager) ListOSPFInstances() []OSPFInstance {
  1018. m.mu.RLock()
  1019. defer m.mu.RUnlock()
  1020. out, err := birdcExec("show protocols")
  1021. protocols := map[string]bool{}
  1022. if err == nil {
  1023. for _, line := range strings.Split(string(out), "\n") {
  1024. fields := strings.Fields(line)
  1025. if len(fields) >= 4 && fields[1] == "OSPF" {
  1026. protocols[fields[0]] = fields[3] == "up"
  1027. }
  1028. }
  1029. }
  1030. res := make([]OSPFInstance, len(m.config.OSPFInstances))
  1031. for i, inst := range m.config.OSPFInstances {
  1032. instCopy := inst
  1033. instCopy.Running = false
  1034. if protocols[sanitizeIdentifier("ospf", inst.Name)] && !inst.Disabled {
  1035. instCopy.Running = true
  1036. }
  1037. res[i] = instCopy
  1038. }
  1039. return res
  1040. }
  1041. func (m *Manager) SaveOSPFInstance(inst *OSPFInstance) error {
  1042. m.mu.Lock()
  1043. defer m.mu.Unlock()
  1044. if inst.ID == "" {
  1045. inst.ID = fmt.Sprintf("ospf-inst-%d", time.Now().UnixNano())
  1046. }
  1047. if inst.Name == "" {
  1048. inst.Name = "Default"
  1049. }
  1050. if inst.Version <= 0 {
  1051. inst.Version = 2
  1052. }
  1053. if inst.VRF == "" {
  1054. inst.VRF = "main"
  1055. }
  1056. if inst.RoutingTable == "" {
  1057. inst.RoutingTable = "main"
  1058. }
  1059. found := false
  1060. for i, it := range m.config.OSPFInstances {
  1061. if it.ID == inst.ID {
  1062. m.config.OSPFInstances[i] = *inst
  1063. found = true
  1064. break
  1065. }
  1066. }
  1067. if !found {
  1068. m.config.OSPFInstances = append(m.config.OSPFInstances, *inst)
  1069. }
  1070. // Update legacy instance holder as well
  1071. m.config.OSPFInstance = *inst
  1072. if err := m.save(); err != nil {
  1073. return err
  1074. }
  1075. return m.applyBirdConfig()
  1076. }
  1077. func (m *Manager) DeleteOSPFInstance(id string) error {
  1078. m.mu.Lock()
  1079. defer m.mu.Unlock()
  1080. var newInst []OSPFInstance
  1081. for _, it := range m.config.OSPFInstances {
  1082. if it.ID != id {
  1083. newInst = append(newInst, it)
  1084. }
  1085. }
  1086. m.config.OSPFInstances = newInst
  1087. if err := m.save(); err != nil {
  1088. return err
  1089. }
  1090. return m.applyBirdConfig()
  1091. }
  1092. func (m *Manager) SetOSPFInstanceState(id string, disabled bool) error {
  1093. m.mu.Lock()
  1094. defer m.mu.Unlock()
  1095. for i := range m.config.OSPFInstances {
  1096. if m.config.OSPFInstances[i].ID == id {
  1097. m.config.OSPFInstances[i].Disabled = disabled
  1098. break
  1099. }
  1100. }
  1101. if err := m.save(); err != nil {
  1102. return err
  1103. }
  1104. return m.applyBirdConfig()
  1105. }
  1106. func (m *Manager) GetOSPFInstance() OSPFInstance {
  1107. m.mu.RLock()
  1108. defer m.mu.RUnlock()
  1109. if len(m.config.OSPFInstances) > 0 {
  1110. inst := m.config.OSPFInstances[0]
  1111. out, err := birdcExec("show protocols")
  1112. if err == nil && strings.Contains(string(out), "OSPF") && strings.Contains(string(out), "up") && !inst.Disabled {
  1113. inst.Running = true
  1114. }
  1115. return inst
  1116. }
  1117. inst := m.config.OSPFInstance
  1118. out, err := birdcExec("show protocols")
  1119. if err == nil && strings.Contains(string(out), "OSPF") && strings.Contains(string(out), "up") && inst.Enabled {
  1120. inst.Running = true
  1121. }
  1122. return inst
  1123. }
  1124. func (m *Manager) UpdateOSPFInstance(inst OSPFInstance) error {
  1125. return m.SaveOSPFInstance(&inst)
  1126. }
  1127. func (m *Manager) ListOSPFAreas() []OSPFArea {
  1128. m.mu.RLock()
  1129. defer m.mu.RUnlock()
  1130. return m.config.OSPFAreas
  1131. }
  1132. func (m *Manager) SaveOSPFArea(area OSPFArea) error {
  1133. m.mu.Lock()
  1134. defer m.mu.Unlock()
  1135. if area.ID == "" {
  1136. area.ID = fmt.Sprintf("area-%d", time.Now().UnixNano())
  1137. }
  1138. if area.Name == "" {
  1139. area.Name = "Default"
  1140. }
  1141. if area.Instance == "" {
  1142. area.Instance = "Default"
  1143. }
  1144. if area.AreaID == "" {
  1145. area.AreaID = "0.0.0.0"
  1146. }
  1147. if area.AreaType == "" {
  1148. area.AreaType = "default"
  1149. }
  1150. found := false
  1151. for i, a := range m.config.OSPFAreas {
  1152. if a.ID == area.ID {
  1153. m.config.OSPFAreas[i] = area
  1154. found = true
  1155. break
  1156. }
  1157. }
  1158. if !found {
  1159. m.config.OSPFAreas = append(m.config.OSPFAreas, area)
  1160. }
  1161. if err := m.save(); err != nil {
  1162. return err
  1163. }
  1164. return m.applyBirdConfig()
  1165. }
  1166. func (m *Manager) DeleteOSPFArea(id string) error {
  1167. m.mu.Lock()
  1168. defer m.mu.Unlock()
  1169. newAreas := make([]OSPFArea, 0, len(m.config.OSPFAreas))
  1170. for _, a := range m.config.OSPFAreas {
  1171. if a.ID != id {
  1172. newAreas = append(newAreas, a)
  1173. }
  1174. }
  1175. m.config.OSPFAreas = newAreas
  1176. if err := m.save(); err != nil {
  1177. return err
  1178. }
  1179. return m.applyBirdConfig()
  1180. }
  1181. func (m *Manager) SetOSPFAreaState(id string, disabled bool) error {
  1182. m.mu.Lock()
  1183. defer m.mu.Unlock()
  1184. for i := range m.config.OSPFAreas {
  1185. if m.config.OSPFAreas[i].ID == id {
  1186. m.config.OSPFAreas[i].Disabled = disabled
  1187. break
  1188. }
  1189. }
  1190. if err := m.save(); err != nil {
  1191. return err
  1192. }
  1193. return m.applyBirdConfig()
  1194. }
  1195. func (m *Manager) ListOSPFAreaRanges() []OSPFAreaRange {
  1196. m.mu.RLock()
  1197. defer m.mu.RUnlock()
  1198. return m.config.OSPFAreaRanges
  1199. }
  1200. func (m *Manager) SaveOSPFAreaRange(ar OSPFAreaRange) error {
  1201. m.mu.Lock()
  1202. defer m.mu.Unlock()
  1203. if ar.ID == "" {
  1204. ar.ID = fmt.Sprintf("range-%d", time.Now().UnixNano())
  1205. }
  1206. if ar.Area == "" {
  1207. ar.Area = "Default"
  1208. }
  1209. found := false
  1210. for i, item := range m.config.OSPFAreaRanges {
  1211. if item.ID == ar.ID {
  1212. m.config.OSPFAreaRanges[i] = ar
  1213. found = true
  1214. break
  1215. }
  1216. }
  1217. if !found {
  1218. m.config.OSPFAreaRanges = append(m.config.OSPFAreaRanges, ar)
  1219. }
  1220. if err := m.save(); err != nil {
  1221. return err
  1222. }
  1223. return m.applyBirdConfig()
  1224. }
  1225. func (m *Manager) DeleteOSPFAreaRange(id string) error {
  1226. m.mu.Lock()
  1227. defer m.mu.Unlock()
  1228. newRanges := make([]OSPFAreaRange, 0, len(m.config.OSPFAreaRanges))
  1229. for _, item := range m.config.OSPFAreaRanges {
  1230. if item.ID != id {
  1231. newRanges = append(newRanges, item)
  1232. }
  1233. }
  1234. m.config.OSPFAreaRanges = newRanges
  1235. if err := m.save(); err != nil {
  1236. return err
  1237. }
  1238. return m.applyBirdConfig()
  1239. }
  1240. func (m *Manager) ListOSPFInterfaces() []OSPFInterface {
  1241. m.mu.RLock()
  1242. defer m.mu.RUnlock()
  1243. return m.config.OSPFInterfaces
  1244. }
  1245. func (m *Manager) SaveOSPFInterface(iface OSPFInterface) error {
  1246. m.mu.Lock()
  1247. defer m.mu.Unlock()
  1248. if iface.ID == "" {
  1249. iface.ID = fmt.Sprintf("ospf-tmpl-%d", time.Now().UnixNano())
  1250. }
  1251. if iface.Area == "" {
  1252. iface.Area = "Default"
  1253. }
  1254. if iface.Cost <= 0 {
  1255. iface.Cost = 1
  1256. }
  1257. if iface.Priority <= 0 {
  1258. iface.Priority = 128
  1259. }
  1260. if iface.NetworkType == "" {
  1261. iface.NetworkType = "broadcast"
  1262. }
  1263. if iface.HelloInterval <= 0 {
  1264. iface.HelloInterval = 10
  1265. }
  1266. if iface.DeadInterval <= 0 {
  1267. iface.DeadInterval = 40
  1268. }
  1269. found := false
  1270. for i, item := range m.config.OSPFInterfaces {
  1271. if item.ID == iface.ID {
  1272. m.config.OSPFInterfaces[i] = iface
  1273. found = true
  1274. break
  1275. }
  1276. }
  1277. if !found {
  1278. m.config.OSPFInterfaces = append(m.config.OSPFInterfaces, iface)
  1279. }
  1280. if err := m.save(); err != nil {
  1281. return err
  1282. }
  1283. return m.applyBirdConfig()
  1284. }
  1285. func (m *Manager) DeleteOSPFInterface(id string) error {
  1286. m.mu.Lock()
  1287. defer m.mu.Unlock()
  1288. newInterfaces := make([]OSPFInterface, 0, len(m.config.OSPFInterfaces))
  1289. for _, item := range m.config.OSPFInterfaces {
  1290. if item.ID != id {
  1291. newInterfaces = append(newInterfaces, item)
  1292. }
  1293. }
  1294. m.config.OSPFInterfaces = newInterfaces
  1295. if err := m.save(); err != nil {
  1296. return err
  1297. }
  1298. return m.applyBirdConfig()
  1299. }
  1300. func (m *Manager) SetOSPFInterfaceState(id string, disabled bool) error {
  1301. m.mu.Lock()
  1302. defer m.mu.Unlock()
  1303. for i := range m.config.OSPFInterfaces {
  1304. if m.config.OSPFInterfaces[i].ID == id {
  1305. m.config.OSPFInterfaces[i].Disabled = disabled
  1306. break
  1307. }
  1308. }
  1309. if err := m.save(); err != nil {
  1310. return err
  1311. }
  1312. return m.applyBirdConfig()
  1313. }
  1314. func (m *Manager) GetOSPFInterfacesLive() []OSPFInterfaceLive {
  1315. var list []OSPFInterfaceLive
  1316. out, err := birdcExec("show ospf interface")
  1317. if err != nil {
  1318. return list
  1319. }
  1320. lines := strings.Split(string(out), "\n")
  1321. var cur *OSPFInterfaceLive
  1322. for _, line := range lines {
  1323. trimmed := strings.TrimSpace(line)
  1324. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasSuffix(trimmed, ":") {
  1325. continue
  1326. }
  1327. if strings.HasPrefix(trimmed, "Interface ") {
  1328. if cur != nil {
  1329. list = append(list, *cur)
  1330. }
  1331. parts := strings.SplitN(strings.TrimPrefix(trimmed, "Interface "), " ", 2)
  1332. ifName := parts[0]
  1333. addr := ""
  1334. if len(parts) > 1 {
  1335. addr = strings.Trim(parts[1], "()")
  1336. }
  1337. cur = &OSPFInterfaceLive{
  1338. Flags: "D",
  1339. Interface: ifName,
  1340. Address: addr,
  1341. Area: "Default",
  1342. InstanceID: 0,
  1343. Cost: 1,
  1344. Priority: 128,
  1345. State: "waiting",
  1346. }
  1347. continue
  1348. }
  1349. if cur == nil {
  1350. continue
  1351. }
  1352. if strings.HasPrefix(trimmed, "Area: ") {
  1353. val := strings.TrimPrefix(trimmed, "Area: ")
  1354. areaParts := strings.Fields(val)
  1355. if len(areaParts) > 0 {
  1356. cur.Area = areaParts[0]
  1357. }
  1358. } else if strings.HasPrefix(trimmed, "State: ") {
  1359. cur.State = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(trimmed, "State: ")))
  1360. } else if strings.HasPrefix(trimmed, "Priority: ") {
  1361. fmt.Sscanf(strings.TrimPrefix(trimmed, "Priority: "), "%d", &cur.Priority)
  1362. } else if strings.HasPrefix(trimmed, "Cost: ") {
  1363. fmt.Sscanf(strings.TrimPrefix(trimmed, "Cost: "), "%d", &cur.Cost)
  1364. }
  1365. }
  1366. if cur != nil {
  1367. list = append(list, *cur)
  1368. }
  1369. return list
  1370. }
  1371. func (m *Manager) ListOSPFStaticNeighbors() []OSPFStaticNeighbor {
  1372. m.mu.RLock()
  1373. defer m.mu.RUnlock()
  1374. return m.config.OSPFStaticNbrs
  1375. }
  1376. func (m *Manager) SaveOSPFStaticNeighbor(nbr OSPFStaticNeighbor) error {
  1377. m.mu.Lock()
  1378. defer m.mu.Unlock()
  1379. if nbr.ID == "" {
  1380. nbr.ID = fmt.Sprintf("snbr-%d", time.Now().UnixNano())
  1381. }
  1382. if nbr.Area == "" {
  1383. nbr.Area = "Default"
  1384. }
  1385. found := false
  1386. for i, item := range m.config.OSPFStaticNbrs {
  1387. if item.ID == nbr.ID {
  1388. m.config.OSPFStaticNbrs[i] = nbr
  1389. found = true
  1390. break
  1391. }
  1392. }
  1393. if !found {
  1394. m.config.OSPFStaticNbrs = append(m.config.OSPFStaticNbrs, nbr)
  1395. }
  1396. return m.save()
  1397. }
  1398. func (m *Manager) DeleteOSPFStaticNeighbor(id string) error {
  1399. m.mu.Lock()
  1400. defer m.mu.Unlock()
  1401. newNbrs := make([]OSPFStaticNeighbor, 0, len(m.config.OSPFStaticNbrs))
  1402. for _, item := range m.config.OSPFStaticNbrs {
  1403. if item.ID != id {
  1404. newNbrs = append(newNbrs, item)
  1405. }
  1406. }
  1407. m.config.OSPFStaticNbrs = newNbrs
  1408. return m.save()
  1409. }
  1410. func (m *Manager) GetOSPFNeighbors() []OSPFNeighbor {
  1411. var neighbors []OSPFNeighbor
  1412. out, err := birdcExec("show ospf neighbors")
  1413. if err != nil {
  1414. return neighbors
  1415. }
  1416. lines := strings.Split(string(out), "\n")
  1417. for _, line := range lines {
  1418. trimmed := strings.TrimSpace(line)
  1419. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Router ID") || strings.HasSuffix(trimmed, ":") {
  1420. continue
  1421. }
  1422. fields := strings.Fields(trimmed)
  1423. if len(fields) >= 5 {
  1424. rID := fields[0]
  1425. pri := 0
  1426. fmt.Sscanf(fields[1], "%d", &pri)
  1427. rawState := fields[2]
  1428. state := rawState
  1429. if idx := strings.Index(rawState, "/"); idx != -1 {
  1430. state = rawState[:idx]
  1431. }
  1432. dTime := fields[3]
  1433. iface := fields[4]
  1434. ip := rID
  1435. if len(fields) >= 6 {
  1436. ip = fields[5]
  1437. }
  1438. neighbors = append(neighbors, OSPFNeighbor{
  1439. Flags: "D",
  1440. Comment: "",
  1441. Instance: "Default",
  1442. Area: "Default",
  1443. Address: ip,
  1444. State: state,
  1445. StateChanges: 6,
  1446. NeighborID: rID,
  1447. Interface: iface,
  1448. DeadTimer: dTime,
  1449. Priority: pri,
  1450. })
  1451. }
  1452. }
  1453. return neighbors
  1454. }
  1455. func (m *Manager) GetOSPFLSA() []OSPFLSA {
  1456. var lsaList []OSPFLSA
  1457. out, err := birdcExec("show ospf lsadb")
  1458. if err != nil {
  1459. return lsaList
  1460. }
  1461. localRouterID := "192.168.131.56"
  1462. if len(m.config.OSPFInstances) > 0 && m.config.OSPFInstances[0].RouterID != "" {
  1463. localRouterID = m.config.OSPFInstances[0].RouterID
  1464. }
  1465. lines := strings.Split(string(out), "\n")
  1466. currentArea := "Default"
  1467. for _, line := range lines {
  1468. trimmed := strings.TrimSpace(line)
  1469. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") {
  1470. continue
  1471. }
  1472. if strings.HasPrefix(trimmed, "Area ") {
  1473. currentArea = strings.TrimSpace(strings.TrimPrefix(trimmed, "Area "))
  1474. continue
  1475. } else if strings.EqualFold(trimmed, "Global") {
  1476. currentArea = "Default"
  1477. continue
  1478. }
  1479. if strings.HasPrefix(trimmed, "Type") || strings.HasPrefix(trimmed, "ospf_") {
  1480. continue
  1481. }
  1482. fields := strings.Fields(trimmed)
  1483. if len(fields) >= 5 {
  1484. rawType := fields[0]
  1485. typeName := "router"
  1486. switch rawType {
  1487. case "0001":
  1488. typeName = "router"
  1489. case "0002":
  1490. typeName = "network"
  1491. case "0003":
  1492. typeName = "summary-net"
  1493. case "0004":
  1494. typeName = "summary-asbr"
  1495. case "0005":
  1496. typeName = "as-external"
  1497. default:
  1498. typeName = rawType
  1499. }
  1500. lsID := fields[1]
  1501. router := fields[2]
  1502. seq := fields[3]
  1503. age := 0
  1504. fmt.Sscanf(fields[4], "%d", &age)
  1505. flags := "D"
  1506. if router == localRouterID {
  1507. flags = "SD"
  1508. }
  1509. lsaList = append(lsaList, OSPFLSA{
  1510. Flags: flags,
  1511. Instance: "Default",
  1512. Area: currentArea,
  1513. Type: typeName,
  1514. Originator: router,
  1515. ID: lsID,
  1516. Link: "",
  1517. LinkIndex: 0,
  1518. Sequence: seq,
  1519. Age: age,
  1520. })
  1521. }
  1522. }
  1523. return lsaList
  1524. }
  1525. func (m *Manager) GetOSPFRoutes() []OSPFRoute {
  1526. var routes []OSPFRoute
  1527. out, err := birdcExec("show route where source = RTS_OSPF all")
  1528. if err != nil {
  1529. return routes
  1530. }
  1531. lines := strings.Split(string(out), "\n")
  1532. var cur *OSPFRoute
  1533. for _, line := range lines {
  1534. trimmed := strings.TrimSpace(line)
  1535. if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
  1536. continue
  1537. }
  1538. if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
  1539. fields := strings.Fields(trimmed)
  1540. if len(fields) >= 2 {
  1541. cost := 10
  1542. if idx := strings.Index(line, "/"); idx != -1 {
  1543. sub := line[idx+1:]
  1544. if end := strings.Index(sub, ")"); end != -1 {
  1545. cost, _ = strconv.Atoi(sub[:end])
  1546. }
  1547. }
  1548. routes = append(routes, OSPFRoute{
  1549. Prefix: fields[0],
  1550. Cost: cost,
  1551. RouteType: "Intra-Area",
  1552. })
  1553. cur = &routes[len(routes)-1]
  1554. }
  1555. continue
  1556. }
  1557. if cur == nil {
  1558. continue
  1559. }
  1560. if strings.HasPrefix(trimmed, "via ") {
  1561. parts := strings.Fields(trimmed)
  1562. if len(parts) >= 2 {
  1563. cur.NextHop = parts[1]
  1564. }
  1565. if len(parts) >= 4 && parts[2] == "on" {
  1566. cur.Interface = parts[3]
  1567. }
  1568. } else if strings.HasPrefix(trimmed, "Type:") {
  1569. cur.RouteType = strings.TrimSpace(strings.TrimPrefix(trimmed, "Type:"))
  1570. }
  1571. }
  1572. return routes
  1573. }
  1574. // -------------------------------------------------------------
  1575. // Routing Filter API & Operations (/routing filter)
  1576. // -------------------------------------------------------------
  1577. func (m *Manager) ListRoutingFilters() []RoutingFilterRule {
  1578. m.mu.RLock()
  1579. defer m.mu.RUnlock()
  1580. filters := make([]RoutingFilterRule, len(m.config.RoutingFilters))
  1581. copy(filters, m.config.RoutingFilters)
  1582. return filters
  1583. }
  1584. func (m *Manager) SaveRoutingFilter(rule *RoutingFilterRule) error {
  1585. m.mu.Lock()
  1586. if rule.ID == "" {
  1587. rule.ID = fmt.Sprintf("rf-%d", time.Now().UnixNano()/1e6)
  1588. }
  1589. if rule.RuleOrder <= 0 {
  1590. rule.RuleOrder = (len(m.config.RoutingFilters) + 1) * 10
  1591. }
  1592. found := false
  1593. for i, r := range m.config.RoutingFilters {
  1594. if r.ID == rule.ID {
  1595. m.config.RoutingFilters[i] = *rule
  1596. found = true
  1597. break
  1598. }
  1599. }
  1600. if !found {
  1601. m.config.RoutingFilters = append(m.config.RoutingFilters, *rule)
  1602. }
  1603. _ = m.save()
  1604. m.mu.Unlock()
  1605. return m.applyBirdConfig()
  1606. }
  1607. func (m *Manager) DeleteRoutingFilter(id string) error {
  1608. m.mu.Lock()
  1609. newRules := make([]RoutingFilterRule, 0, len(m.config.RoutingFilters))
  1610. for _, r := range m.config.RoutingFilters {
  1611. if r.ID != id {
  1612. newRules = append(newRules, r)
  1613. }
  1614. }
  1615. m.config.RoutingFilters = newRules
  1616. _ = m.save()
  1617. m.mu.Unlock()
  1618. return m.applyBirdConfig()
  1619. }
  1620. func (m *Manager) SetRoutingFilterState(id string, disabled bool) error {
  1621. m.mu.Lock()
  1622. for i := range m.config.RoutingFilters {
  1623. if m.config.RoutingFilters[i].ID == id {
  1624. m.config.RoutingFilters[i].Disabled = disabled
  1625. break
  1626. }
  1627. }
  1628. _ = m.save()
  1629. m.mu.Unlock()
  1630. return m.applyBirdConfig()
  1631. }
  1632. // translateRos7RuleToBird converts a RouterOS v7 rule script (or fallback fields) to valid BIRD 2 syntax
  1633. func translateRos7RuleToBird(r *RoutingFilterRule) string {
  1634. script := strings.TrimSpace(r.Rule)
  1635. if script != "" {
  1636. s := script
  1637. // 0. Convert double-equals (==) to single-equals (=) for BIRD 2, preserving !=, <=, >=, ~=
  1638. reDoubleEq := regexp.MustCompile(`([^!<>~=])\s*==\s*([^=])`)
  1639. for reDoubleEq.MatchString(s) {
  1640. s = reDoubleEq.ReplaceAllString(s, "$1 = $2")
  1641. }
  1642. // 1. Convert dst in A.B.C.D/M{L,H} -> net ~ [ A.B.C.D/M{L,H} ]
  1643. reDstRange := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)\{([0-9]+),([0-9]+)\}`)
  1644. s = reDstRange.ReplaceAllString(s, "net ~ [ $1{$2,$3} ]")
  1645. // 2. Convert dst in A.B.C.D/M -> net ~ [ A.B.C.D/M+ ]
  1646. reDstIn := regexp.MustCompile(`dst\s+in\s+([0-9\.\/]+)`)
  1647. s = reDstIn.ReplaceAllString(s, "net ~ [ $1+ ]")
  1648. // 3. Convert dst = A.B.C.D/M or dst == A.B.C.D/M -> net = A.B.C.D/M
  1649. reDstEq := regexp.MustCompile(`\bdst\s*=\s*([0-9\.\/]+)`)
  1650. s = reDstEq.ReplaceAllString(s, "net = $1")
  1651. // 4. Convert dst != A.B.C.D/M -> net != A.B.C.D/M
  1652. reDstNeq := regexp.MustCompile(`\bdst\s*!=\s*([0-9\.\/]+)`)
  1653. s = reDstNeq.ReplaceAllString(s, "net != $1")
  1654. // 5. Convert dst-len -> net.len
  1655. s = regexp.MustCompile(`\bdst-len\b`).ReplaceAllString(s, "net.len")
  1656. // 6. Convert protocol matches
  1657. s = regexp.MustCompile(`protocol\s+bgp\b`).ReplaceAllString(s, "source = RTS_BGP")
  1658. s = regexp.MustCompile(`protocol\s+ospf\b`).ReplaceAllString(s, "source = RTS_OSPF")
  1659. s = regexp.MustCompile(`protocol\s+connected\b`).ReplaceAllString(s, "source = RTS_DEVICE")
  1660. s = regexp.MustCompile(`protocol\s+static\b`).ReplaceAllString(s, "source = RTS_STATIC")
  1661. s = regexp.MustCompile(`protocol\s+rip\b`).ReplaceAllString(s, "source = RTS_RIP")
  1662. // 7. Convert bgp-communities includes A:B -> (A, B) ~ bgp_community
  1663. reCommInc := regexp.MustCompile(`bgp-communities\s+includes\s+([0-9]+):([0-9]+)`)
  1664. s = reCommInc.ReplaceAllString(s, "($1, $2) ~ bgp_community")
  1665. // 8. Convert bgp-communities (in|equal-list) ListName -> bgp_community ~ comm_ListName
  1666. reCommList := regexp.MustCompile(`bgp-communities\s+(?:in|equal-list)\s+([A-Za-z0-9_]+)`)
  1667. s = reCommList.ReplaceAllString(s, "bgp_community ~ comm_$1")
  1668. // 9. Convert bgp-as-path in ListName -> bgp_path.last ~ aslist_ListName
  1669. reASList := regexp.MustCompile(`bgp-as-path\s+in\s+([A-Za-z0-9_]+)`)
  1670. s = reASList.ReplaceAllString(s, "bgp_path.last ~ aslist_$1")
  1671. // 10. Convert bgp-as-path "pattern" -> bgp_path ~ [= * pattern * =]
  1672. reASPattern := regexp.MustCompile(`bgp-as-path\s+"([^"]+)"`)
  1673. s = reASPattern.ReplaceAllStringFunc(s, func(match string) string {
  1674. sub := reASPattern.FindStringSubmatch(match)
  1675. if len(sub) == 2 {
  1676. pat := strings.Trim(sub[1], "^$")
  1677. return fmt.Sprintf("bgp_path ~ [= * %s * =]", pat)
  1678. }
  1679. return match
  1680. })
  1681. // 11. Convert actions:
  1682. reSetLP := regexp.MustCompile(`set\s+bgp-local-pref\s*=?\s*([0-9]+);?`)
  1683. s = reSetLP.ReplaceAllString(s, "bgp_local_pref = $1;")
  1684. reSetMed := regexp.MustCompile(`set\s+bgp-med\s*=?\s*([0-9]+);?`)
  1685. s = reSetMed.ReplaceAllString(s, "bgp_med = $1;")
  1686. reSetDist := regexp.MustCompile(`set\s+distance\s*=?\s*([0-9]+);?`)
  1687. s = reSetDist.ReplaceAllString(s, "preference = $1;")
  1688. reSetGW := regexp.MustCompile(`set\s+gw\s*=?\s*([0-9\.]+);?`)
  1689. s = reSetGW.ReplaceAllString(s, "gw = $1;")
  1690. reSetPrepend := regexp.MustCompile(`set\s+bgp-path-prepend\s*=?\s*([0-9]+);?`)
  1691. s = reSetPrepend.ReplaceAllStringFunc(s, func(match string) string {
  1692. sub := reSetPrepend.FindStringSubmatch(match)
  1693. if len(sub) == 2 {
  1694. n, _ := strconv.Atoi(sub[1])
  1695. if n > 0 && n <= 10 {
  1696. var b strings.Builder
  1697. for i := 0; i < n; i++ {
  1698. b.WriteString("bgp_path.prepend(bgp_path.first); ")
  1699. }
  1700. return b.String()
  1701. } else if n > 10 {
  1702. return fmt.Sprintf("bgp_path.prepend(%d);", n)
  1703. }
  1704. }
  1705. return match
  1706. })
  1707. reSetCommAdd := regexp.MustCompile(`set\s+bgp-communities\.add\s+([0-9]+):([0-9]+);?`)
  1708. s = reSetCommAdd.ReplaceAllString(s, "bgp_community.add(($1, $2));")
  1709. reSetCommDel := regexp.MustCompile(`set\s+bgp-communities\.delete\s+([0-9]+):([0-9]+);?`)
  1710. s = reSetCommDel.ReplaceAllString(s, "bgp_community.delete(($1, $2));")
  1711. // Ensure semicolons on accept and reject
  1712. s = regexp.MustCompile(`\baccept(?:\s*;)?`).ReplaceAllString(s, "accept;")
  1713. s = regexp.MustCompile(`\b(reject|discard)(?:\s*;)?`).ReplaceAllString(s, "reject;")
  1714. // Convert passthrough keyword to no-op
  1715. s = regexp.MustCompile(`\bpassthrough(?:\s*;)?`).ReplaceAllString(s, "")
  1716. // Ensure "then" before opening brace of if statement
  1717. reIfThen := regexp.MustCompile(`\)\s*\{`)
  1718. s = reIfThen.ReplaceAllString(s, ") then {")
  1719. s = strings.ReplaceAll(s, ") then then {", ") then {")
  1720. return s
  1721. }
  1722. // Fallback for rules configured with structured UI form
  1723. var conditions []string
  1724. if r.Prefix != "" {
  1725. pfx := strings.TrimSpace(r.Prefix)
  1726. pfxLen := strings.TrimSpace(r.PrefixLen)
  1727. if pfxLen != "" {
  1728. if strings.Contains(pfxLen, "-") {
  1729. parts := strings.Split(pfxLen, "-")
  1730. if len(parts) == 2 {
  1731. conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,%s} ]", pfx, strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
  1732. }
  1733. } else {
  1734. conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,32} ]", pfx, pfxLen))
  1735. }
  1736. } else {
  1737. conditions = append(conditions, fmt.Sprintf("net ~ [ %s+ ]", pfx))
  1738. }
  1739. }
  1740. if r.MatchProtocol != "" && r.MatchProtocol != "any" {
  1741. switch strings.ToLower(r.MatchProtocol) {
  1742. case "bgp":
  1743. conditions = append(conditions, "source = RTS_BGP")
  1744. case "ospf":
  1745. conditions = append(conditions, "source = RTS_OSPF")
  1746. case "connected":
  1747. conditions = append(conditions, "source = RTS_DEVICE")
  1748. case "static":
  1749. conditions = append(conditions, "source = RTS_STATIC")
  1750. }
  1751. }
  1752. if r.MatchASPath != "" {
  1753. conditions = append(conditions, fmt.Sprintf("bgp_path ~ [= * %s * =]", strings.Trim(strings.TrimSpace(r.MatchASPath), "^$")))
  1754. }
  1755. if r.MatchCommunity != "" {
  1756. comm := strings.TrimSpace(r.MatchCommunity)
  1757. if strings.Contains(comm, ":") {
  1758. parts := strings.Split(comm, ":")
  1759. conditions = append(conditions, fmt.Sprintf("(%s, %s) ~ bgp_community", parts[0], parts[1]))
  1760. }
  1761. }
  1762. condStr := "true"
  1763. if len(conditions) > 0 {
  1764. condStr = strings.Join(conditions, " && ")
  1765. }
  1766. var sb strings.Builder
  1767. sb.WriteString(fmt.Sprintf("if %s then {\n", condStr))
  1768. if r.SetLocalPref > 0 {
  1769. sb.WriteString(fmt.Sprintf(" bgp_local_pref = %d;\n", r.SetLocalPref))
  1770. }
  1771. if r.SetMetric > 0 {
  1772. sb.WriteString(fmt.Sprintf(" bgp_med = %d;\n", r.SetMetric))
  1773. }
  1774. if r.SetASPrepend > 0 {
  1775. for i := 0; i < r.SetASPrepend; i++ {
  1776. sb.WriteString(" bgp_path.prepend(bgp_path.first);\n")
  1777. }
  1778. }
  1779. if r.SetCommunity != "" {
  1780. comm := strings.TrimSpace(r.SetCommunity)
  1781. if strings.Contains(comm, ":") {
  1782. parts := strings.Split(comm, ":")
  1783. sb.WriteString(fmt.Sprintf(" bgp_community.add((%s, %s));\n", parts[0], parts[1]))
  1784. }
  1785. }
  1786. if r.SetNextHop != "" {
  1787. sb.WriteString(fmt.Sprintf(" bgp_next_hop = %s;\n", strings.TrimSpace(r.SetNextHop)))
  1788. }
  1789. if r.SetDistance > 0 {
  1790. sb.WriteString(fmt.Sprintf(" preference = %d;\n", r.SetDistance))
  1791. }
  1792. if r.Action == "discard" || r.Action == "reject" {
  1793. sb.WriteString(" reject;\n")
  1794. } else if r.Action == "passthrough" {
  1795. // Passthrough: do not emit terminating accept or reject
  1796. } else {
  1797. sb.WriteString(" accept;\n")
  1798. }
  1799. sb.WriteString("}")
  1800. return sb.String()
  1801. }
  1802. // -------------------------------------------------------------
  1803. // Community Lists (/routing filter community-list)
  1804. // -------------------------------------------------------------
  1805. func (m *Manager) ListCommunityLists() []RoutingFilterCommunityList {
  1806. m.mu.RLock()
  1807. defer m.mu.RUnlock()
  1808. res := make([]RoutingFilterCommunityList, len(m.config.RoutingCommunityLists))
  1809. copy(res, m.config.RoutingCommunityLists)
  1810. return res
  1811. }
  1812. func (m *Manager) SaveCommunityList(cl *RoutingFilterCommunityList) error {
  1813. m.mu.Lock()
  1814. if cl.ID == "" {
  1815. cl.ID = fmt.Sprintf("cl-%d", time.Now().UnixNano()/1e6)
  1816. }
  1817. found := false
  1818. for i, r := range m.config.RoutingCommunityLists {
  1819. if r.ID == cl.ID {
  1820. m.config.RoutingCommunityLists[i] = *cl
  1821. found = true
  1822. break
  1823. }
  1824. }
  1825. if !found {
  1826. m.config.RoutingCommunityLists = append(m.config.RoutingCommunityLists, *cl)
  1827. }
  1828. _ = m.save()
  1829. m.mu.Unlock()
  1830. return m.applyBirdConfig()
  1831. }
  1832. func (m *Manager) DeleteCommunityList(id string) error {
  1833. m.mu.Lock()
  1834. newLists := make([]RoutingFilterCommunityList, 0, len(m.config.RoutingCommunityLists))
  1835. for _, r := range m.config.RoutingCommunityLists {
  1836. if r.ID != id {
  1837. newLists = append(newLists, r)
  1838. }
  1839. }
  1840. m.config.RoutingCommunityLists = newLists
  1841. _ = m.save()
  1842. m.mu.Unlock()
  1843. return m.applyBirdConfig()
  1844. }
  1845. func (m *Manager) SetCommunityListState(id string, disabled bool) error {
  1846. m.mu.Lock()
  1847. for i := range m.config.RoutingCommunityLists {
  1848. if m.config.RoutingCommunityLists[i].ID == id {
  1849. m.config.RoutingCommunityLists[i].Disabled = disabled
  1850. break
  1851. }
  1852. }
  1853. _ = m.save()
  1854. m.mu.Unlock()
  1855. return m.applyBirdConfig()
  1856. }
  1857. // -------------------------------------------------------------
  1858. // AS Lists (/routing filter num-list)
  1859. // -------------------------------------------------------------
  1860. func (m *Manager) ListASLists() []RoutingFilterASList {
  1861. m.mu.RLock()
  1862. defer m.mu.RUnlock()
  1863. res := make([]RoutingFilterASList, len(m.config.RoutingASLists))
  1864. copy(res, m.config.RoutingASLists)
  1865. return res
  1866. }
  1867. func (m *Manager) SaveASList(al *RoutingFilterASList) error {
  1868. m.mu.Lock()
  1869. if al.ID == "" {
  1870. al.ID = fmt.Sprintf("al-%d", time.Now().UnixNano()/1e6)
  1871. }
  1872. found := false
  1873. for i, r := range m.config.RoutingASLists {
  1874. if r.ID == al.ID {
  1875. m.config.RoutingASLists[i] = *al
  1876. found = true
  1877. break
  1878. }
  1879. }
  1880. if !found {
  1881. m.config.RoutingASLists = append(m.config.RoutingASLists, *al)
  1882. }
  1883. _ = m.save()
  1884. m.mu.Unlock()
  1885. return m.applyBirdConfig()
  1886. }
  1887. func (m *Manager) DeleteASList(id string) error {
  1888. m.mu.Lock()
  1889. newLists := make([]RoutingFilterASList, 0, len(m.config.RoutingASLists))
  1890. for _, r := range m.config.RoutingASLists {
  1891. if r.ID != id {
  1892. newLists = append(newLists, r)
  1893. }
  1894. }
  1895. m.config.RoutingASLists = newLists
  1896. _ = m.save()
  1897. m.mu.Unlock()
  1898. return m.applyBirdConfig()
  1899. }
  1900. func (m *Manager) SetASListState(id string, disabled bool) error {
  1901. m.mu.Lock()
  1902. for i := range m.config.RoutingASLists {
  1903. if m.config.RoutingASLists[i].ID == id {
  1904. m.config.RoutingASLists[i].Disabled = disabled
  1905. break
  1906. }
  1907. }
  1908. _ = m.save()
  1909. m.mu.Unlock()
  1910. return m.applyBirdConfig()
  1911. }
  1912. // -------------------------------------------------------------
  1913. // Summary Telemetry
  1914. // -------------------------------------------------------------
  1915. func (m *Manager) GetSummary() DynamicRoutingSummary {
  1916. m.mu.RLock()
  1917. defer m.mu.RUnlock()
  1918. summary := DynamicRoutingSummary{
  1919. BGPEnabled: m.config.BGPInstance.Enabled,
  1920. OSPFEnabled: m.config.OSPFInstance.Enabled,
  1921. BGPPeerCount: len(m.config.BGPPeers),
  1922. RoutingFilterCount: len(m.config.RoutingFilters),
  1923. }
  1924. out, err := birdcExec("show status")
  1925. birdRunning := err == nil && strings.Contains(string(out), "Daemon is up and running")
  1926. if birdRunning && summary.BGPEnabled {
  1927. summary.BGPRunning = true
  1928. peers := m.ListBGPPeers()
  1929. est := 0
  1930. for _, p := range peers {
  1931. if strings.EqualFold(p.State, "Established") || strings.EqualFold(p.State, "Up") {
  1932. est++
  1933. }
  1934. }
  1935. summary.BGPEstablishedCount = est
  1936. }
  1937. if birdRunning && summary.OSPFEnabled {
  1938. summary.OSPFRunning = true
  1939. nbrs := m.GetOSPFNeighbors()
  1940. summary.OSPFNeighborCount = len(nbrs)
  1941. adj := 0
  1942. for _, n := range nbrs {
  1943. if strings.Contains(strings.ToLower(n.State), "full") {
  1944. adj++
  1945. }
  1946. }
  1947. summary.OSPFAdjacentCount = adj
  1948. }
  1949. return summary
  1950. }