| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178 |
- package dynamicrouting
- import (
- "encoding/json"
- "fmt"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- const (
- defaultConfigPath = "/etc/proxmox-router/routing/dynamic.json"
- birdConfigPath = "/etc/bird/bird.conf"
- )
- type Manager struct {
- mu sync.RWMutex
- configPath string
- config DynamicConfig
- }
- func NewManager(configPath string) *Manager {
- if configPath == "" {
- configPath = defaultConfigPath
- }
- m := &Manager{
- configPath: configPath,
- }
- if err := m.load(); err != nil {
- log.Printf("[DynamicRouting] Config load warning: %v, initializing defaults", err)
- m.initDefaults()
- _ = m.save()
- }
- // Apply initial configuration to BIRD 2
- if err := m.applyBirdConfig(); err != nil {
- log.Printf("[DynamicRouting] Initial BIRD apply warning: %v", err)
- }
- return m
- }
- func (m *Manager) initDefaults() {
- m.config = DynamicConfig{
- BGPInstance: BGPInstance{
- Enabled: false,
- AS: 65001,
- RouterID: "192.168.131.56",
- HoldTime: 180,
- KeepaliveTime: 60,
- RedistributeConnected: false,
- RedistributeStatic: false,
- RedistributeOSPF: false,
- },
- BGPPeers: []BGPPeer{},
- BGPNetworks: []BGPNetwork{},
- OSPFInstance: OSPFInstance{
- Enabled: false,
- RouterID: "192.168.131.56",
- RedistributeConnected: false,
- RedistributeStatic: false,
- RedistributeBGP: false,
- DefaultMetric: 10,
- },
- OSPFAreas: []OSPFArea{
- {
- ID: "area-backbone",
- Name: "backbone",
- AreaID: "0.0.0.0",
- AreaType: "default",
- Comment: "Default OSPF Backbone Area",
- },
- },
- OSPFInterfaces: []OSPFInterface{},
- RoutingFilters: []RoutingFilterRule{},
- }
- }
- func (m *Manager) load() error {
- m.mu.Lock()
- defer m.mu.Unlock()
- data, err := os.ReadFile(m.configPath)
- if err != nil {
- return err
- }
- return json.Unmarshal(data, &m.config)
- }
- func (m *Manager) save() error {
- dir := filepath.Dir(m.configPath)
- if err := os.MkdirAll(dir, 0755); err != nil {
- return err
- }
- data, err := json.MarshalIndent(m.config, "", " ")
- if err != nil {
- return err
- }
- return os.WriteFile(m.configPath, data, 0644)
- }
- // sanitizeIdentifier creates a valid BIRD protocol/function identifier: [a-zA-Z][a-zA-Z0-9_]*
- func sanitizeIdentifier(prefix, raw string) string {
- reg := regexp.MustCompile("[^a-zA-Z0-9_]+")
- cleaned := reg.ReplaceAllString(raw, "_")
- cleaned = strings.Trim(cleaned, "_")
- if cleaned == "" {
- cleaned = "inst"
- }
- res := prefix + "_" + cleaned
- if len(res) > 32 {
- res = res[:32]
- }
- return res
- }
- // applyBirdConfig generates /etc/bird/bird.conf and live reloads BIRD daemon
- func (m *Manager) applyBirdConfig() error {
- var sb strings.Builder
- routerID := "192.168.131.56"
- if m.config.BGPInstance.RouterID != "" {
- routerID = m.config.BGPInstance.RouterID
- } else if m.config.OSPFInstance.RouterID != "" {
- routerID = m.config.OSPFInstance.RouterID
- }
- sb.WriteString("# /etc/bird/bird.conf\n")
- sb.WriteString("# Generated dynamically by Proxmox Router (BIRD 2 Engine)\n\n")
- sb.WriteString("log syslog all;\n")
- sb.WriteString(fmt.Sprintf("router id %s;\n\n", routerID))
- // Base system protocols
- sb.WriteString("protocol device {\n")
- sb.WriteString(" scan time 10;\n")
- sb.WriteString("}\n\n")
- sb.WriteString("protocol direct {\n")
- sb.WriteString(" ipv4;\n")
- sb.WriteString("}\n\n")
- sb.WriteString("protocol kernel {\n")
- sb.WriteString(" ipv4 {\n")
- sb.WriteString(" export all;\n")
- sb.WriteString(" };\n")
- sb.WriteString(" learn;\n")
- sb.WriteString("}\n\n")
- // Static BGP Networks announcements
- var activeNets []string
- if m.config.BGPInstance.Enabled {
- for _, net := range m.config.BGPNetworks {
- if !net.Disabled && strings.TrimSpace(net.Network) != "" {
- activeNets = append(activeNets, strings.TrimSpace(net.Network))
- }
- }
- }
- if len(activeNets) > 0 {
- sb.WriteString("protocol static bgp_static_nets {\n")
- sb.WriteString(" ipv4;\n")
- for _, n := range activeNets {
- sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", n))
- }
- sb.WriteString("}\n\n")
- }
- // Routing Filters (/routing filter)
- chainRules := make(map[string][]RoutingFilterRule)
- for _, rule := range m.config.RoutingFilters {
- if rule.Disabled || strings.TrimSpace(rule.Chain) == "" {
- continue
- }
- chain := strings.TrimSpace(rule.Chain)
- chainRules[chain] = append(chainRules[chain], rule)
- }
- for chain, rules := range chainRules {
- sort.Slice(rules, func(i, j int) bool {
- return rules[i].RuleOrder < rules[j].RuleOrder
- })
- filterName := sanitizeIdentifier("filter", chain)
- sb.WriteString(fmt.Sprintf("filter %s {\n", filterName))
- for _, r := range rules {
- var conditions []string
- if r.Prefix != "" {
- pfx := strings.TrimSpace(r.Prefix)
- pfxLen := strings.TrimSpace(r.PrefixLen)
- if pfxLen != "" {
- if strings.Contains(pfxLen, "-") {
- parts := strings.Split(pfxLen, "-")
- if len(parts) == 2 {
- conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,%s} ]", pfx, strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
- }
- } else {
- conditions = append(conditions, fmt.Sprintf("net ~ [ %s{%s,32} ]", pfx, pfxLen))
- }
- } else {
- conditions = append(conditions, fmt.Sprintf("net ~ [ %s+ ]", pfx))
- }
- }
- if r.MatchASPath != "" {
- conditions = append(conditions, fmt.Sprintf("bgp_path ~ [= %s =]", strings.TrimSpace(r.MatchASPath)))
- }
- if r.MatchCommunity != "" {
- comm := strings.TrimSpace(r.MatchCommunity)
- if strings.Contains(comm, ":") {
- parts := strings.Split(comm, ":")
- conditions = append(conditions, fmt.Sprintf("(%s, %s) ~ bgp_community", parts[0], parts[1]))
- }
- }
- condStr := "true"
- if len(conditions) > 0 {
- condStr = strings.Join(conditions, " && ")
- }
- sb.WriteString(fmt.Sprintf(" if %s then {\n", condStr))
- if r.SetLocalPref > 0 {
- sb.WriteString(fmt.Sprintf(" bgp_local_pref = %d;\n", r.SetLocalPref))
- }
- if r.SetMetric > 0 {
- sb.WriteString(fmt.Sprintf(" bgp_med = %d;\n", r.SetMetric))
- }
- if r.SetCommunity != "" {
- comm := strings.TrimSpace(r.SetCommunity)
- if strings.Contains(comm, ":") {
- parts := strings.Split(comm, ":")
- sb.WriteString(fmt.Sprintf(" bgp_community.add((%s, %s));\n", parts[0], parts[1]))
- }
- }
- if r.SetNextHop != "" {
- sb.WriteString(fmt.Sprintf(" bgp_next_hop = %s;\n", strings.TrimSpace(r.SetNextHop)))
- }
- if r.Action == "discard" || r.Action == "reject" {
- sb.WriteString(" reject;\n")
- } else {
- sb.WriteString(" accept;\n")
- }
- sb.WriteString(" }\n")
- }
- sb.WriteString(" accept;\n")
- sb.WriteString("}\n\n")
- }
- // BGP Protocols (True Multi-Instance / Multi-AS support!)
- if m.config.BGPInstance.Enabled {
- for i, peer := range m.config.BGPPeers {
- if peer.RemoteAddress == "" || peer.RemoteAS == 0 {
- continue
- }
- // Local AS determination: peer.LocalAS if set, otherwise global AS
- localAS := m.config.BGPInstance.AS
- if peer.LocalAS > 0 {
- localAS = peer.LocalAS
- }
- protoName := sanitizeIdentifier("bgp", fmt.Sprintf("%s_%d", peer.ID, i))
- // Per-peer Output Networks (RouterOS v7 output.network)
- var peerNets []string
- for _, on := range peer.OutputNetworks {
- on = strings.TrimSpace(on)
- if on != "" {
- peerNets = append(peerNets, on)
- }
- }
- if peer.DefaultOriginate {
- peerNets = append(peerNets, "0.0.0.0/0")
- }
- peerNetsProto := ""
- if len(peerNets) > 0 {
- peerNetsProto = fmt.Sprintf("bgp_nets_%s", protoName)
- sb.WriteString(fmt.Sprintf("protocol static %s {\n", peerNetsProto))
- sb.WriteString(" ipv4;\n")
- for _, pn := range peerNets {
- sb.WriteString(fmt.Sprintf(" route %s blackhole;\n", pn))
- }
- sb.WriteString("}\n\n")
- }
- sb.WriteString(fmt.Sprintf("protocol bgp %s {\n", protoName))
- if peer.Name != "" {
- sb.WriteString(fmt.Sprintf(" description \"%s\";\n", peer.Name))
- }
- if peer.Disabled {
- sb.WriteString(" disabled;\n")
- }
- if peer.LocalAddress != "" {
- if peer.LocalPort > 0 {
- sb.WriteString(fmt.Sprintf(" local %s port %d as %d;\n", peer.LocalAddress, peer.LocalPort, localAS))
- } else {
- sb.WriteString(fmt.Sprintf(" local %s as %d;\n", peer.LocalAddress, localAS))
- }
- } else {
- if peer.LocalPort > 0 {
- sb.WriteString(fmt.Sprintf(" local port %d as %d;\n", peer.LocalPort, localAS))
- } else {
- sb.WriteString(fmt.Sprintf(" local as %d;\n", localAS))
- }
- }
- if peer.RemotePort > 0 {
- sb.WriteString(fmt.Sprintf(" neighbor %s port %d as %d;\n", peer.RemoteAddress, peer.RemotePort, peer.RemoteAS))
- } else {
- sb.WriteString(fmt.Sprintf(" neighbor %s as %d;\n", peer.RemoteAddress, peer.RemoteAS))
- }
- if peer.Multihop {
- sb.WriteString(" multihop;\n")
- }
- if peer.Passive || (!peer.Connect && peer.Listen) {
- sb.WriteString(" passive;\n")
- }
- if peer.Password != "" {
- sb.WriteString(fmt.Sprintf(" password \"%s\";\n", peer.Password))
- }
- holdTime := 180
- if peer.HoldTime > 0 {
- holdTime = peer.HoldTime
- } else if m.config.BGPInstance.HoldTime > 0 {
- holdTime = m.config.BGPInstance.HoldTime
- }
- sb.WriteString(fmt.Sprintf(" hold time %d;\n", holdTime))
- if peer.KeepaliveTime > 0 {
- sb.WriteString(fmt.Sprintf(" keepalive time %d;\n", peer.KeepaliveTime))
- }
- // IPv4 Channel
- sb.WriteString(" ipv4 {\n")
- if peer.NexthopSelf || peer.NexthopChoice == "force-self" {
- sb.WriteString(" next hop self;\n")
- }
- // Import Filter
- if peer.InFilter != "" && len(chainRules[peer.InFilter]) > 0 {
- sb.WriteString(fmt.Sprintf(" import filter %s;\n", sanitizeIdentifier("filter", peer.InFilter)))
- } else {
- sb.WriteString(" import all;\n")
- }
- // Export Filter
- if peer.OutFilter != "" && len(chainRules[peer.OutFilter]) > 0 {
- sb.WriteString(fmt.Sprintf(" export filter %s;\n", sanitizeIdentifier("filter", peer.OutFilter)))
- } else {
- var exportSources []string
- if peerNetsProto != "" {
- exportSources = append(exportSources, fmt.Sprintf(`proto = "%s"`, peerNetsProto))
- }
- if len(activeNets) > 0 {
- exportSources = append(exportSources, `proto = "bgp_static_nets"`)
- }
- exportSources = append(exportSources, `source = RTS_BGP`)
- if peer.RedistConnected || m.config.BGPInstance.RedistributeConnected {
- exportSources = append(exportSources, `source = RTS_DEVICE`)
- }
- if peer.RedistStatic || m.config.BGPInstance.RedistributeStatic {
- exportSources = append(exportSources, `source = RTS_STATIC`)
- }
- if peer.RedistOSPF || m.config.BGPInstance.RedistributeOSPF {
- exportSources = append(exportSources, `source = RTS_OSPF`)
- }
- if len(exportSources) > 0 {
- sb.WriteString(fmt.Sprintf(" export where (%s);\n", strings.Join(exportSources, ") || (")))
- } else {
- sb.WriteString(" export none;\n")
- }
- }
- sb.WriteString(" };\n")
- sb.WriteString("}\n\n")
- }
- }
- // OSPFv2 Protocol
- if m.config.OSPFInstance.Enabled {
- ospfRouterID := routerID
- if m.config.OSPFInstance.RouterID != "" {
- ospfRouterID = m.config.OSPFInstance.RouterID
- }
- sb.WriteString("protocol ospf v2 ospf_main {\n")
- sb.WriteString(fmt.Sprintf(" router id %s;\n", ospfRouterID))
- sb.WriteString(" ipv4 {\n")
- sb.WriteString(" import all;\n")
- var ospfExports []string
- ospfExports = append(ospfExports, "RTS_STATIC")
- if m.config.OSPFInstance.RedistributeConnected {
- ospfExports = append(ospfExports, "RTS_DEVICE")
- }
- if m.config.OSPFInstance.RedistributeBGP {
- ospfExports = append(ospfExports, "RTS_BGP")
- }
- if len(ospfExports) > 0 {
- sb.WriteString(fmt.Sprintf(" export where source ~ [ %s ];\n", strings.Join(ospfExports, ", ")))
- } else {
- sb.WriteString(" export none;\n")
- }
- sb.WriteString(" };\n\n")
- // Group interfaces by area
- areaIfaces := make(map[string][]OSPFInterface)
- for _, iface := range m.config.OSPFInterfaces {
- if iface.Disabled {
- continue
- }
- area := strings.TrimSpace(iface.Area)
- if area == "" {
- area = "0.0.0.0"
- }
- areaIfaces[area] = append(areaIfaces[area], iface)
- }
- // Ensure backbone area always exists
- if _, ok := areaIfaces["0.0.0.0"]; !ok {
- areaIfaces["0.0.0.0"] = []OSPFInterface{}
- }
- areas := m.config.OSPFAreas
- if len(areas) == 0 {
- areas = []OSPFArea{
- {
- Name: "backbone",
- AreaID: "0.0.0.0",
- AreaType: "default",
- },
- }
- }
- for _, area := range areas {
- areaID := strings.TrimSpace(area.AreaID)
- if areaID == "" {
- areaID = "0.0.0.0"
- }
- ifaces := areaIfaces[areaID]
- sb.WriteString(fmt.Sprintf(" area %s {\n", areaID))
- if area.AreaType == "stub" {
- sb.WriteString(" stub;\n")
- } else if area.AreaType == "nssa" {
- sb.WriteString(" nssa;\n")
- }
- for _, iface := range ifaces {
- target := iface.Interface
- if target == "" {
- target = iface.Network
- }
- if target == "" {
- continue
- }
- sb.WriteString(fmt.Sprintf(" interface \"%s\" {\n", target))
- if iface.Cost > 0 {
- sb.WriteString(fmt.Sprintf(" cost %d;\n", iface.Cost))
- }
- if iface.Priority > 0 {
- sb.WriteString(fmt.Sprintf(" priority %d;\n", iface.Priority))
- }
- if iface.HelloInterval > 0 {
- sb.WriteString(fmt.Sprintf(" hello %d;\n", iface.HelloInterval))
- }
- if iface.DeadInterval > 0 {
- sb.WriteString(fmt.Sprintf(" dead %d;\n", iface.DeadInterval))
- }
- if iface.Passive {
- sb.WriteString(" stub;\n")
- } else {
- sb.WriteString(" type broadcast;\n")
- }
- if iface.AuthType == "md5" && iface.AuthKey != "" {
- sb.WriteString(" authentication cryptographic;\n")
- sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
- } else if iface.AuthType == "simple" && iface.AuthKey != "" {
- sb.WriteString(" authentication simple;\n")
- sb.WriteString(fmt.Sprintf(" password \"%s\";\n", iface.AuthKey))
- }
- sb.WriteString(" };\n")
- }
- sb.WriteString(" };\n")
- }
- sb.WriteString("}\n\n")
- }
- // Write candidate configuration to temporary file
- tmpPath := birdConfigPath + ".new"
- if err := os.WriteFile(tmpPath, []byte(sb.String()), 0644); err != nil {
- return fmt.Errorf("failed to write %s: %w", tmpPath, err)
- }
- // Validate syntax with bird -p
- out, err := exec.Command("bird", "-p", "-c", tmpPath).CombinedOutput()
- if err != nil {
- _ = os.Remove(tmpPath)
- return fmt.Errorf("bird syntax check failed: %s: %w", string(out), err)
- }
- // Replace active config
- if err := os.Rename(tmpPath, birdConfigPath); err != nil {
- return fmt.Errorf("failed to replace %s: %w", birdConfigPath, err)
- }
- // Ensure BIRD systemd service is active
- _ = exec.Command("systemctl", "start", "bird").Run()
- // Live reload without packet loss
- reloadOut, reloadErr := birdcExec("configure")
- if reloadErr != nil {
- log.Printf("[DynamicRouting] birdc configure notice: %s", string(reloadOut))
- }
- return nil
- }
- func birdcExec(cmd string) ([]byte, error) {
- return exec.Command("birdc", cmd).CombinedOutput()
- }
- // -------------------------------------------------------------
- // BGP API & Operations (Multi-Instance BGP)
- // -------------------------------------------------------------
- func (m *Manager) GetBGPInstance() BGPInstance {
- m.mu.RLock()
- defer m.mu.RUnlock()
- inst := m.config.BGPInstance
- out, err := birdcExec("show status")
- if err == nil && strings.Contains(string(out), "Daemon is up and running") && inst.Enabled {
- inst.Running = true
- }
- return inst
- }
- func (m *Manager) UpdateBGPInstance(inst BGPInstance) error {
- m.mu.Lock()
- m.config.BGPInstance = inst
- _ = m.save()
- m.mu.Unlock()
- return m.applyBirdConfig()
- }
- func (m *Manager) ListBGPPeers() []BGPPeer {
- m.mu.RLock()
- defer m.mu.RUnlock()
- peers := make([]BGPPeer, len(m.config.BGPPeers))
- copy(peers, m.config.BGPPeers)
- // Fetch live peer telemetry from birdc
- out, err := birdcExec("show protocols all")
- if err == nil {
- type livePeerData struct {
- State string
- RemoteAddr string
- RemoteAS uint32
- LocalAS uint32
- PfxRcd int
- PfxSnt int
- Uptime string
- }
- liveMap := make(map[string]*livePeerData)
- lines := strings.Split(string(out), "\n")
- var cur *livePeerData
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if strings.Contains(line, " BGP ") {
- cur = &livePeerData{}
- fields := strings.Fields(line)
- if len(fields) >= 5 {
- cur.Uptime = fields[4]
- }
- }
- if cur == nil {
- continue
- }
- if strings.HasPrefix(trimmed, "BGP state:") {
- cur.State = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP state:"))
- } else if strings.HasPrefix(trimmed, "Neighbor address:") {
- cur.RemoteAddr = strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor address:"))
- liveMap[cur.RemoteAddr] = cur
- } else if strings.HasPrefix(trimmed, "Neighbor AS:") {
- v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Neighbor AS:")), 10, 32)
- cur.RemoteAS = uint32(v)
- } else if strings.HasPrefix(trimmed, "Local AS:") {
- v, _ := strconv.ParseUint(strings.TrimSpace(strings.TrimPrefix(trimmed, "Local AS:")), 10, 32)
- cur.LocalAS = uint32(v)
- } else if strings.HasPrefix(trimmed, "Routes:") {
- parts := strings.Split(trimmed, ",")
- for _, p := range parts {
- p = strings.TrimSpace(p)
- if strings.Contains(p, "imported") {
- f := strings.Fields(p)
- if len(f) >= 2 {
- cur.PfxRcd, _ = strconv.Atoi(f[len(f)-2])
- }
- } else if strings.Contains(p, "exported") {
- f := strings.Fields(p)
- if len(f) >= 2 {
- cur.PfxSnt, _ = strconv.Atoi(f[0])
- }
- }
- }
- }
- }
- for i := range peers {
- if live, ok := liveMap[peers[i].RemoteAddress]; ok {
- peers[i].State = live.State
- peers[i].Uptime = live.Uptime
- peers[i].PrefixReceived = live.PfxRcd
- peers[i].PrefixSent = live.PfxSnt
- if peers[i].LocalAS == 0 && live.LocalAS > 0 {
- peers[i].LocalAS = live.LocalAS
- }
- } else if peers[i].Disabled {
- peers[i].State = "Disabled"
- } else {
- peers[i].State = "Idle"
- }
- }
- }
- return peers
- }
- func (m *Manager) SaveBGPPeer(peer *BGPPeer) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if peer.ID == "" {
- peer.ID = fmt.Sprintf("bgp-peer-%d", time.Now().UnixNano())
- }
- found := false
- for i, p := range m.config.BGPPeers {
- if p.ID == peer.ID {
- m.config.BGPPeers[i] = *peer
- found = true
- break
- }
- }
- if !found {
- m.config.BGPPeers = append(m.config.BGPPeers, *peer)
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) DeleteBGPPeer(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- newPeers := make([]BGPPeer, 0, len(m.config.BGPPeers))
- for _, p := range m.config.BGPPeers {
- if p.ID != id {
- newPeers = append(newPeers, p)
- }
- }
- m.config.BGPPeers = newPeers
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) SetBGPPeerState(id string, disabled bool) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- for i := range m.config.BGPPeers {
- if m.config.BGPPeers[i].ID == id {
- m.config.BGPPeers[i].Disabled = disabled
- break
- }
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) ListBGPNetworks() []BGPNetwork {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return m.config.BGPNetworks
- }
- func (m *Manager) SaveBGPNetwork(net BGPNetwork) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if net.ID == "" {
- net.ID = fmt.Sprintf("bgp-net-%d", time.Now().UnixNano())
- }
- found := false
- for i, n := range m.config.BGPNetworks {
- if n.ID == net.ID {
- m.config.BGPNetworks[i] = net
- found = true
- break
- }
- }
- if !found {
- m.config.BGPNetworks = append(m.config.BGPNetworks, net)
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) DeleteBGPNetwork(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- newNets := make([]BGPNetwork, 0, len(m.config.BGPNetworks))
- for _, n := range m.config.BGPNetworks {
- if n.ID != id {
- newNets = append(newNets, n)
- }
- }
- m.config.BGPNetworks = newNets
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) GetBGPRoutes() []BGPRoute {
- var routes []BGPRoute
- out, err := birdcExec("show route where source = RTS_BGP all")
- if err != nil {
- return routes
- }
- lines := strings.Split(string(out), "\n")
- var cur *BGPRoute
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
- continue
- }
- if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
- fields := strings.Fields(trimmed)
- if len(fields) >= 2 {
- routes = append(routes, BGPRoute{
- Prefix: fields[0],
- Best: strings.Contains(line, "*"),
- Origin: "IGP",
- })
- cur = &routes[len(routes)-1]
- }
- continue
- }
- if cur == nil {
- continue
- }
- if strings.HasPrefix(trimmed, "via ") {
- parts := strings.Fields(trimmed)
- if len(parts) >= 2 {
- cur.NextHop = parts[1]
- }
- } else if strings.HasPrefix(trimmed, "BGP.as_path:") {
- cur.Path = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.as_path:"))
- } else if strings.HasPrefix(trimmed, "BGP.origin:") {
- cur.Origin = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.origin:"))
- } else if strings.HasPrefix(trimmed, "BGP.next_hop:") {
- cur.NextHop = strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.next_hop:"))
- } else if strings.HasPrefix(trimmed, "BGP.med:") {
- cur.Metric, _ = strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(trimmed, "BGP.med:")))
- }
- }
- return routes
- }
- // -------------------------------------------------------------
- // OSPF API & Operations
- // -------------------------------------------------------------
- func (m *Manager) GetOSPFInstance() OSPFInstance {
- m.mu.RLock()
- defer m.mu.RUnlock()
- inst := m.config.OSPFInstance
- out, err := birdcExec("show protocols")
- if err == nil && strings.Contains(string(out), "OSPF") && strings.Contains(string(out), "up") && inst.Enabled {
- inst.Running = true
- }
- return inst
- }
- func (m *Manager) UpdateOSPFInstance(inst OSPFInstance) error {
- m.mu.Lock()
- m.config.OSPFInstance = inst
- _ = m.save()
- m.mu.Unlock()
- return m.applyBirdConfig()
- }
- func (m *Manager) ListOSPFAreas() []OSPFArea {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return m.config.OSPFAreas
- }
- func (m *Manager) SaveOSPFArea(area OSPFArea) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if area.ID == "" {
- area.ID = fmt.Sprintf("area-%d", time.Now().UnixNano())
- }
- found := false
- for i, a := range m.config.OSPFAreas {
- if a.ID == area.ID {
- m.config.OSPFAreas[i] = area
- found = true
- break
- }
- }
- if !found {
- m.config.OSPFAreas = append(m.config.OSPFAreas, area)
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) DeleteOSPFArea(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- newAreas := make([]OSPFArea, 0, len(m.config.OSPFAreas))
- for _, a := range m.config.OSPFAreas {
- if a.ID != id {
- newAreas = append(newAreas, a)
- }
- }
- m.config.OSPFAreas = newAreas
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) ListOSPFInterfaces() []OSPFInterface {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return m.config.OSPFInterfaces
- }
- func (m *Manager) SaveOSPFInterface(iface OSPFInterface) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if iface.ID == "" {
- iface.ID = fmt.Sprintf("ospf-iface-%d", time.Now().UnixNano())
- }
- if iface.Cost <= 0 {
- iface.Cost = 10
- }
- if iface.Priority <= 0 {
- iface.Priority = 1
- }
- if iface.HelloInterval <= 0 {
- iface.HelloInterval = 10
- }
- if iface.DeadInterval <= 0 {
- iface.DeadInterval = 40
- }
- found := false
- for i, item := range m.config.OSPFInterfaces {
- if item.ID == iface.ID {
- m.config.OSPFInterfaces[i] = iface
- found = true
- break
- }
- }
- if !found {
- m.config.OSPFInterfaces = append(m.config.OSPFInterfaces, iface)
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) DeleteOSPFInterface(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- newInterfaces := make([]OSPFInterface, 0, len(m.config.OSPFInterfaces))
- for _, item := range m.config.OSPFInterfaces {
- if item.ID != id {
- newInterfaces = append(newInterfaces, item)
- }
- }
- m.config.OSPFInterfaces = newInterfaces
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) SetOSPFInterfaceState(id string, disabled bool) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- for i := range m.config.OSPFInterfaces {
- if m.config.OSPFInterfaces[i].ID == id {
- m.config.OSPFInterfaces[i].Disabled = disabled
- break
- }
- }
- if err := m.save(); err != nil {
- return err
- }
- return m.applyBirdConfig()
- }
- func (m *Manager) GetOSPFNeighbors() []OSPFNeighbor {
- var neighbors []OSPFNeighbor
- out, err := birdcExec("show ospf neighbors")
- if err != nil {
- return neighbors
- }
- lines := strings.Split(string(out), "\n")
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Router ID") || strings.HasSuffix(trimmed, ":") {
- continue
- }
- fields := strings.Fields(trimmed)
- if len(fields) >= 5 {
- nbr := OSPFNeighbor{
- NeighborID: fields[0],
- State: fields[2],
- DeadTimer: fields[3],
- Interface: fields[4],
- }
- if len(fields) >= 6 {
- nbr.Address = fields[5]
- } else {
- nbr.Address = fields[0]
- }
- neighbors = append(neighbors, nbr)
- }
- }
- return neighbors
- }
- func (m *Manager) GetOSPFRoutes() []OSPFRoute {
- var routes []OSPFRoute
- out, err := birdcExec("show route where source = RTS_OSPF all")
- if err != nil {
- return routes
- }
- lines := strings.Split(string(out), "\n")
- var cur *OSPFRoute
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "BIRD") || strings.HasPrefix(trimmed, "Table") {
- continue
- }
- if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
- fields := strings.Fields(trimmed)
- if len(fields) >= 2 {
- cost := 10
- if idx := strings.Index(line, "/"); idx != -1 {
- sub := line[idx+1:]
- if end := strings.Index(sub, ")"); end != -1 {
- cost, _ = strconv.Atoi(sub[:end])
- }
- }
- routes = append(routes, OSPFRoute{
- Prefix: fields[0],
- Cost: cost,
- RouteType: "Intra-Area",
- })
- cur = &routes[len(routes)-1]
- }
- continue
- }
- if cur == nil {
- continue
- }
- if strings.HasPrefix(trimmed, "via ") {
- parts := strings.Fields(trimmed)
- if len(parts) >= 2 {
- cur.NextHop = parts[1]
- }
- if len(parts) >= 4 && parts[2] == "on" {
- cur.Interface = parts[3]
- }
- } else if strings.HasPrefix(trimmed, "Type:") {
- cur.RouteType = strings.TrimSpace(strings.TrimPrefix(trimmed, "Type:"))
- }
- }
- return routes
- }
- // -------------------------------------------------------------
- // Routing Filter API & Operations (/routing filter)
- // -------------------------------------------------------------
- func (m *Manager) ListRoutingFilters() []RoutingFilterRule {
- m.mu.RLock()
- defer m.mu.RUnlock()
- filters := make([]RoutingFilterRule, len(m.config.RoutingFilters))
- copy(filters, m.config.RoutingFilters)
- return filters
- }
- func (m *Manager) SaveRoutingFilter(rule *RoutingFilterRule) error {
- m.mu.Lock()
- if rule.ID == "" {
- rule.ID = fmt.Sprintf("rf-%d", time.Now().UnixNano()/1e6)
- }
- if rule.RuleOrder <= 0 {
- rule.RuleOrder = (len(m.config.RoutingFilters) + 1) * 10
- }
- found := false
- for i, r := range m.config.RoutingFilters {
- if r.ID == rule.ID {
- m.config.RoutingFilters[i] = *rule
- found = true
- break
- }
- }
- if !found {
- m.config.RoutingFilters = append(m.config.RoutingFilters, *rule)
- }
- _ = m.save()
- m.mu.Unlock()
- return m.applyBirdConfig()
- }
- func (m *Manager) DeleteRoutingFilter(id string) error {
- m.mu.Lock()
- newRules := make([]RoutingFilterRule, 0, len(m.config.RoutingFilters))
- for _, r := range m.config.RoutingFilters {
- if r.ID != id {
- newRules = append(newRules, r)
- }
- }
- m.config.RoutingFilters = newRules
- _ = m.save()
- m.mu.Unlock()
- return m.applyBirdConfig()
- }
- func (m *Manager) SetRoutingFilterState(id string, disabled bool) error {
- m.mu.Lock()
- for i := range m.config.RoutingFilters {
- if m.config.RoutingFilters[i].ID == id {
- m.config.RoutingFilters[i].Disabled = disabled
- break
- }
- }
- _ = m.save()
- m.mu.Unlock()
- return m.applyBirdConfig()
- }
- // -------------------------------------------------------------
- // Summary Telemetry
- // -------------------------------------------------------------
- func (m *Manager) GetSummary() DynamicRoutingSummary {
- m.mu.RLock()
- defer m.mu.RUnlock()
- summary := DynamicRoutingSummary{
- BGPEnabled: m.config.BGPInstance.Enabled,
- OSPFEnabled: m.config.OSPFInstance.Enabled,
- BGPPeerCount: len(m.config.BGPPeers),
- RoutingFilterCount: len(m.config.RoutingFilters),
- }
- out, err := birdcExec("show status")
- birdRunning := err == nil && strings.Contains(string(out), "Daemon is up and running")
- if birdRunning && summary.BGPEnabled {
- summary.BGPRunning = true
- peers := m.ListBGPPeers()
- est := 0
- for _, p := range peers {
- if strings.EqualFold(p.State, "Established") || strings.EqualFold(p.State, "Up") {
- est++
- }
- }
- summary.BGPEstablishedCount = est
- }
- if birdRunning && summary.OSPFEnabled {
- summary.OSPFRunning = true
- nbrs := m.GetOSPFNeighbors()
- summary.OSPFNeighborCount = len(nbrs)
- adj := 0
- for _, n := range nbrs {
- if strings.Contains(strings.ToLower(n.State), "full") {
- adj++
- }
- }
- summary.OSPFAdjacentCount = adj
- }
- return summary
- }
|