server_manager.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. package dhcp
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. const (
  17. DHCPServerStoreFile = "/etc/debtik/dhcp_server.json"
  18. DnsmasqConfFile = "/etc/dnsmasq.d/debtik_dhcp.conf"
  19. DnsmasqLeasesFile = "/var/lib/misc/dnsmasq.leases"
  20. )
  21. type ServerManager struct {
  22. mu sync.RWMutex
  23. storePath string
  24. confPath string
  25. leasesPath string
  26. servers map[string]DHCPServerInstance
  27. networks map[string]DHCPNetwork
  28. staticLeases map[string]DHCPLease
  29. options map[string]DHCPOption
  30. }
  31. func NewServerManager() *ServerManager {
  32. sm := &ServerManager{
  33. storePath: DHCPServerStoreFile,
  34. confPath: DnsmasqConfFile,
  35. leasesPath: DnsmasqLeasesFile,
  36. servers: make(map[string]DHCPServerInstance),
  37. networks: make(map[string]DHCPNetwork),
  38. staticLeases: make(map[string]DHCPLease),
  39. options: make(map[string]DHCPOption),
  40. }
  41. _ = os.MkdirAll(filepath.Dir(sm.storePath), 0755)
  42. _ = os.MkdirAll(filepath.Dir(sm.confPath), 0755)
  43. if err := sm.load(); err != nil {
  44. log.Printf("[DHCP-Server] Error loading config: %v", err)
  45. }
  46. // Initial render and reload dnsmasq
  47. if err := sm.applyDnsmasqConfigLocked(); err != nil {
  48. log.Printf("[DHCP-Server] Error applying dnsmasq config: %v", err)
  49. }
  50. return sm
  51. }
  52. func (sm *ServerManager) load() error {
  53. sm.mu.Lock()
  54. defer sm.mu.Unlock()
  55. data, err := os.ReadFile(sm.storePath)
  56. if err != nil {
  57. if os.IsNotExist(err) {
  58. // Populate default option presets (MikroTik standard presets)
  59. sm.initDefaultOptions()
  60. return nil
  61. }
  62. return err
  63. }
  64. var store DHCPServerConfigStore
  65. if err := json.Unmarshal(data, &store); err != nil {
  66. return err
  67. }
  68. for _, s := range store.Servers {
  69. sm.servers[s.ID] = s
  70. }
  71. for _, n := range store.Networks {
  72. sm.networks[n.ID] = n
  73. }
  74. for _, l := range store.StaticLeases {
  75. sm.staticLeases[l.ID] = l
  76. }
  77. for _, o := range store.Options {
  78. sm.options[o.ID] = o
  79. }
  80. if len(sm.options) == 0 {
  81. sm.initDefaultOptions()
  82. }
  83. return nil
  84. }
  85. func (sm *ServerManager) initDefaultOptions() {
  86. presets := []DHCPOption{
  87. {ID: "opt-ntp", Name: "ntp-servers", Code: 42, Value: "192.168.88.1", Comment: "NTP Time Servers (Option 42)"},
  88. {ID: "opt-tftp-name", Name: "tftp-server-name", Code: 66, Value: "192.168.88.50", Comment: "TFTP Server Name / IP (Option 66)"},
  89. {ID: "opt-bootfile", Name: "bootfile-name", Code: 67, Value: "pxelinux.0", Comment: "PXE Boot File (Option 67)"},
  90. {ID: "opt-wins", Name: "wins-servers", Code: 44, Value: "192.168.88.50", Comment: "WINS NetBIOS Servers (Option 44)"},
  91. {ID: "opt-unifi", Name: "unifi-controller", Code: 43, Value: "01:04:c0:a8:58:0a", Comment: "UniFi Inform Controller (Option 43 Hex IP)"},
  92. {ID: "opt-voip", Name: "cisco-voip-tftp", Code: 150, Value: "192.168.88.50", Comment: "Cisco VoIP TFTP (Option 150)"},
  93. {ID: "opt-capwap", Name: "capwap-ac", Code: 138, Value: "192.168.88.10", Comment: "CAPWAP Access Controller (Option 138)"},
  94. {ID: "opt-wpad", Name: "wpad-url", Code: 252, Value: "\"http://wpad/wpad.dat\"", Comment: "Web Proxy Auto-Discovery (Option 252)"},
  95. }
  96. for _, p := range presets {
  97. sm.options[p.ID] = p
  98. }
  99. }
  100. func (sm *ServerManager) saveLocked() error {
  101. store := DHCPServerConfigStore{
  102. Servers: make([]DHCPServerInstance, 0, len(sm.servers)),
  103. Networks: make([]DHCPNetwork, 0, len(sm.networks)),
  104. StaticLeases: make([]DHCPLease, 0, len(sm.staticLeases)),
  105. Options: make([]DHCPOption, 0, len(sm.options)),
  106. }
  107. for _, s := range sm.servers {
  108. copyS := s
  109. copyS.Running = false
  110. copyS.ActiveLeases = 0
  111. store.Servers = append(store.Servers, copyS)
  112. }
  113. for _, n := range sm.networks {
  114. store.Networks = append(store.Networks, n)
  115. }
  116. for _, l := range sm.staticLeases {
  117. store.StaticLeases = append(store.StaticLeases, l)
  118. }
  119. for _, o := range sm.options {
  120. store.Options = append(store.Options, o)
  121. }
  122. data, err := json.MarshalIndent(store, "", " ")
  123. if err != nil {
  124. return err
  125. }
  126. return os.WriteFile(sm.storePath, data, 0644)
  127. }
  128. func (sm *ServerManager) applyDnsmasqConfigLocked() (result error) {
  129. old, readErr := os.ReadFile(sm.confPath)
  130. wasRunning := exec.Command("systemctl", "is-active", "--quiet", "dnsmasq").Run() == nil
  131. defer func() {
  132. if result != nil {
  133. if readErr == nil {
  134. _ = os.WriteFile(sm.confPath, old, 0644)
  135. } else if os.IsNotExist(readErr) {
  136. _ = os.Remove(sm.confPath)
  137. }
  138. if wasRunning {
  139. if err := exec.Command("systemctl", "restart", "dnsmasq").Run(); err != nil {
  140. result = fmt.Errorf("DHCP apply failed: %v; rollback restart failed: %w", result, err)
  141. }
  142. }
  143. }
  144. }()
  145. var sb strings.Builder
  146. sb.WriteString("# ==================================================================\n")
  147. sb.WriteString("# Enterprise DHCP Server Configuration\n")
  148. sb.WriteString("# Auto-generated by Network Appliance. DO NOT EDIT DIRECTLY.\n")
  149. sb.WriteString("# ==================================================================\n\n")
  150. sb.WriteString("dhcp-authoritative\n")
  151. sb.WriteString("dhcp-leasefile=/var/lib/misc/dnsmasq.leases\n")
  152. sb.WriteString("log-dhcp\n")
  153. sb.WriteString("bind-dynamic\n\n")
  154. activeServerCount := 0
  155. for _, srv := range sm.servers {
  156. if srv.Disabled {
  157. continue
  158. }
  159. activeServerCount++
  160. tag := sanitizeTag(srv.Name)
  161. sb.WriteString(fmt.Sprintf("# --- DHCP Server: %s on %s ---\n", srv.Name, srv.Interface))
  162. sb.WriteString(fmt.Sprintf("interface=%s\n", srv.Interface))
  163. leaseTime := srv.LeaseTime
  164. if leaseTime == "" {
  165. leaseTime = "12h"
  166. }
  167. // Find assigned network for server
  168. var assignedNet *DHCPNetwork
  169. if srv.Network != "" {
  170. for _, n := range sm.networks {
  171. if n.Address == srv.Network || n.ID == srv.Network {
  172. copyN := n
  173. assignedNet = &copyN
  174. break
  175. }
  176. }
  177. }
  178. // Parse Address Pool range (e.g. 192.168.88.10-192.168.88.254)
  179. startIP, endIP, netmask := parseAddressPool(srv.AddressPool)
  180. if netmask == "" && assignedNet != nil {
  181. if assignedNet.Netmask != "" {
  182. netmask = assignedNet.Netmask
  183. } else if _, ipNet, err := net.ParseCIDR(assignedNet.Address); err == nil && ipNet != nil {
  184. netmask = net.IP(ipNet.Mask).String()
  185. }
  186. }
  187. if startIP != "" && endIP != "" {
  188. if srv.Interface != "" {
  189. if netmask != "" {
  190. sb.WriteString(fmt.Sprintf("dhcp-range=tag:%s,set:%s,%s,%s,%s,%s\n", srv.Interface, tag, startIP, endIP, netmask, leaseTime))
  191. } else {
  192. sb.WriteString(fmt.Sprintf("dhcp-range=tag:%s,set:%s,%s,%s,%s\n", srv.Interface, tag, startIP, endIP, leaseTime))
  193. }
  194. } else {
  195. if netmask != "" {
  196. sb.WriteString(fmt.Sprintf("dhcp-range=set:%s,%s,%s,%s,%s\n", tag, startIP, endIP, netmask, leaseTime))
  197. } else {
  198. sb.WriteString(fmt.Sprintf("dhcp-range=set:%s,%s,%s,%s\n", tag, startIP, endIP, leaseTime))
  199. }
  200. }
  201. }
  202. // Emit assigned network options specifically for this DHCP server tag
  203. if assignedNet != nil {
  204. targetTag := fmt.Sprintf("tag:%s,", tag)
  205. if assignedNet.Gateway != "" {
  206. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:router,%s\n", targetTag, assignedNet.Gateway))
  207. }
  208. if len(assignedNet.DNSServers) > 0 {
  209. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:dns-server,%s\n", targetTag, strings.Join(assignedNet.DNSServers, ",")))
  210. }
  211. if assignedNet.Domain != "" {
  212. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:domain-name,%s\n", targetTag, assignedNet.Domain))
  213. }
  214. if len(assignedNet.NTPServers) > 0 {
  215. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:ntp-server,%s\n", targetTag, strings.Join(assignedNet.NTPServers, ",")))
  216. }
  217. if assignedNet.NextServer != "" {
  218. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:tftp-server,%s\n", targetTag, assignedNet.NextServer))
  219. }
  220. if assignedNet.BootFileName != "" {
  221. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:bootfile-name,%s\n", targetTag, assignedNet.BootFileName))
  222. if assignedNet.NextServer != "" {
  223. sb.WriteString(fmt.Sprintf("dhcp-boot=%s%s,,%s\n", targetTag, assignedNet.BootFileName, assignedNet.NextServer))
  224. } else {
  225. sb.WriteString(fmt.Sprintf("dhcp-boot=%s%s\n", targetTag, assignedNet.BootFileName))
  226. }
  227. }
  228. if len(assignedNet.WINSServers) > 0 {
  229. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:netbios-ns,%s\n", targetTag, strings.Join(assignedNet.WINSServers, ",")))
  230. }
  231. for _, optID := range assignedNet.DHCPOptions {
  232. if opt, exists := sm.options[optID]; exists {
  233. sb.WriteString(fmt.Sprintf("dhcp-option=%s%d,%s # %s\n", targetTag, opt.Code, opt.Value, opt.Name))
  234. }
  235. }
  236. }
  237. sb.WriteString("\n")
  238. }
  239. // Subnet Networks & Options (Fallback and IP-matching)
  240. sb.WriteString("# --- Subnet Networks Fallbacks & IP matching ---\n")
  241. for _, netw := range sm.networks {
  242. sb.WriteString(fmt.Sprintf("# Subnet: %s\n", netw.Address))
  243. _, ipNet, err := net.ParseCIDR(netw.Address)
  244. isCoveredByServer := false
  245. if ipNet != nil {
  246. for _, srv := range sm.servers {
  247. if !srv.Disabled && (srv.Network == netw.ID || srv.Network == netw.Address) {
  248. isCoveredByServer = true
  249. break
  250. }
  251. }
  252. }
  253. networkTag := ""
  254. if err == nil && ipNet != nil {
  255. networkTag = fmt.Sprintf("net_%s", strings.ReplaceAll(ipNet.IP.String(), ".", "_"))
  256. if !isCoveredByServer {
  257. sb.WriteString(fmt.Sprintf("dhcp-range=set:%s,%s,static\n", networkTag, ipNet.IP.String()))
  258. }
  259. }
  260. // Determine target tag (either network tag or global/matched)
  261. targetTag := ""
  262. if networkTag != "" {
  263. targetTag = fmt.Sprintf("tag:%s,", networkTag)
  264. }
  265. // Option 3: Gateway (Router)
  266. if netw.Gateway != "" {
  267. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:router,%s\n", targetTag, netw.Gateway))
  268. }
  269. // Option 6: DNS Servers
  270. if len(netw.DNSServers) > 0 {
  271. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:dns-server,%s\n", targetTag, strings.Join(netw.DNSServers, ",")))
  272. }
  273. // Option 15: Domain Name
  274. if netw.Domain != "" {
  275. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:domain-name,%s\n", targetTag, netw.Domain))
  276. }
  277. // Check which codes are provided via linked custom options
  278. hasLinkedOption := make(map[int]bool)
  279. for _, optID := range netw.DHCPOptions {
  280. if opt, exists := sm.options[optID]; exists {
  281. hasLinkedOption[opt.Code] = true
  282. }
  283. }
  284. // Option 42: NTP Servers (if not linked via custom option)
  285. if len(netw.NTPServers) > 0 && !hasLinkedOption[42] {
  286. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:ntp-server,%s\n", targetTag, strings.Join(netw.NTPServers, ",")))
  287. }
  288. // Option 66: TFTP Server Name / IP (if not linked via custom option)
  289. if netw.NextServer != "" && !hasLinkedOption[66] {
  290. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:tftp-server,%s\n", targetTag, netw.NextServer))
  291. }
  292. // Option 67: Boot File Name (if not linked via custom option)
  293. if netw.BootFileName != "" && !hasLinkedOption[67] {
  294. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:bootfile-name,%s\n", targetTag, netw.BootFileName))
  295. if netw.NextServer != "" {
  296. sb.WriteString(fmt.Sprintf("dhcp-boot=%s%s,,%s\n", targetTag, netw.BootFileName, netw.NextServer))
  297. } else {
  298. sb.WriteString(fmt.Sprintf("dhcp-boot=%s%s\n", targetTag, netw.BootFileName))
  299. }
  300. }
  301. // Option 44: WINS Servers (if not linked via custom option)
  302. if len(netw.WINSServers) > 0 && !hasLinkedOption[44] {
  303. sb.WriteString(fmt.Sprintf("dhcp-option=%soption:netbios-ns,%s\n", targetTag, strings.Join(netw.WINSServers, ",")))
  304. }
  305. // Linked custom DHCP options
  306. for _, optID := range netw.DHCPOptions {
  307. if opt, exists := sm.options[optID]; exists {
  308. sb.WriteString(fmt.Sprintf("dhcp-option=%s%d,%s # %s\n", targetTag, opt.Code, opt.Value, opt.Name))
  309. }
  310. }
  311. sb.WriteString("\n")
  312. }
  313. // Static Leases & Reservations
  314. sb.WriteString("# --- Static Leases & Reservations ---\n")
  315. for _, l := range sm.staticLeases {
  316. if l.Disabled {
  317. continue
  318. }
  319. mac := strings.ToLower(strings.TrimSpace(l.MACAddress))
  320. ip := strings.TrimSpace(l.Address)
  321. hostname := strings.TrimSpace(l.HostName)
  322. if hostname == "" {
  323. hostname = "reserved"
  324. }
  325. if mac != "" && ip != "" {
  326. sb.WriteString(fmt.Sprintf("dhcp-host=%s,%s,%s,infinite\n", mac, ip, hostname))
  327. }
  328. }
  329. // Write config to disk
  330. if err := os.WriteFile(sm.confPath, []byte(sb.String()), 0644); err != nil {
  331. return fmt.Errorf("failed to write dnsmasq config: %w", err)
  332. }
  333. // Restart or reload dnsmasq
  334. if activeServerCount > 0 {
  335. out, err := exec.Command("systemctl", "restart", "dnsmasq").CombinedOutput()
  336. if err != nil {
  337. return fmt.Errorf("failed to restart dnsmasq: %s: %w", string(out), err)
  338. } else {
  339. log.Printf("[DHCPServer] dnsmasq restarted successfully with %d active DHCP server(s)", activeServerCount)
  340. }
  341. } else {
  342. if err := exec.Command("systemctl", "reload", "dnsmasq").Run(); err != nil {
  343. return err
  344. }
  345. }
  346. return nil
  347. }
  348. // RenameInterface updates DHCP server interface bindings when an interface is renamed.
  349. func (sm *ServerManager) RenameInterface(oldName, newName string) {
  350. sm.mu.Lock()
  351. defer sm.mu.Unlock()
  352. changed := false
  353. for _, srv := range sm.servers {
  354. if srv.Interface == oldName {
  355. srv.Interface = newName
  356. changed = true
  357. }
  358. }
  359. if changed {
  360. _ = sm.saveLocked()
  361. _ = sm.applyDnsmasqConfigLocked()
  362. log.Printf("[DHCPServer] Updated DHCP server interface binding: %s -> %s", oldName, newName)
  363. }
  364. }
  365. func (sm *ServerManager) ListServers() []DHCPServerInstance {
  366. sm.mu.RLock()
  367. defer sm.mu.RUnlock()
  368. activeLeases := sm.countActiveLeasesByServer()
  369. list := make([]DHCPServerInstance, 0, len(sm.servers))
  370. for _, s := range sm.servers {
  371. copyS := s
  372. copyS.Running = !s.Disabled && isInterfaceUp(s.Interface)
  373. copyS.ActiveLeases = activeLeases[s.Name]
  374. list = append(list, copyS)
  375. }
  376. sort.Slice(list, func(i, j int) bool {
  377. return list[i].Name < list[j].Name
  378. })
  379. return list
  380. }
  381. func (sm *ServerManager) GetServer(id string) (DHCPServerInstance, bool) {
  382. sm.mu.RLock()
  383. defer sm.mu.RUnlock()
  384. s, ok := sm.servers[id]
  385. if !ok {
  386. return DHCPServerInstance{}, false
  387. }
  388. s.Running = !s.Disabled && isInterfaceUp(s.Interface)
  389. return s, true
  390. }
  391. func (sm *ServerManager) SaveServer(inst DHCPServerInstance) (DHCPServerInstance, error) {
  392. sm.mu.Lock()
  393. defer sm.mu.Unlock()
  394. if inst.ID == "" {
  395. inst.ID = fmt.Sprintf("dhcp-%d", time.Now().UnixNano())
  396. }
  397. if inst.Name == "" {
  398. inst.Name = fmt.Sprintf("dhcp%d", len(sm.servers)+1)
  399. }
  400. if inst.LeaseTime == "" {
  401. inst.LeaseTime = "12h"
  402. }
  403. inst.Authoritative = true
  404. sm.servers[inst.ID] = inst
  405. if err := sm.saveLocked(); err != nil {
  406. return inst, err
  407. }
  408. _ = sm.applyDnsmasqConfigLocked()
  409. return inst, nil
  410. }
  411. func (sm *ServerManager) DeleteServer(id string) error {
  412. sm.mu.Lock()
  413. defer sm.mu.Unlock()
  414. delete(sm.servers, id)
  415. if err := sm.saveLocked(); err != nil {
  416. return err
  417. }
  418. return sm.applyDnsmasqConfigLocked()
  419. }
  420. func (sm *ServerManager) ToggleServerState(id string, disabled bool) error {
  421. sm.mu.Lock()
  422. defer sm.mu.Unlock()
  423. s, exists := sm.servers[id]
  424. if !exists {
  425. return fmt.Errorf("server not found: %s", id)
  426. }
  427. s.Disabled = disabled
  428. sm.servers[id] = s
  429. if err := sm.saveLocked(); err != nil {
  430. return err
  431. }
  432. return sm.applyDnsmasqConfigLocked()
  433. }
  434. // ======================== NETWORKS ========================
  435. func (sm *ServerManager) ListNetworks() []DHCPNetwork {
  436. sm.mu.RLock()
  437. defer sm.mu.RUnlock()
  438. list := make([]DHCPNetwork, 0, len(sm.networks))
  439. for _, n := range sm.networks {
  440. list = append(list, n)
  441. }
  442. sort.Slice(list, func(i, j int) bool {
  443. return list[i].Address < list[j].Address
  444. })
  445. return list
  446. }
  447. func (sm *ServerManager) SaveNetwork(netw DHCPNetwork) (DHCPNetwork, error) {
  448. sm.mu.Lock()
  449. defer sm.mu.Unlock()
  450. if netw.ID == "" {
  451. netw.ID = fmt.Sprintf("net-%d", time.Now().UnixNano())
  452. }
  453. if netw.Address == "" {
  454. return netw, fmt.Errorf("subnet address (CIDR) is required")
  455. }
  456. sm.networks[netw.ID] = netw
  457. if err := sm.saveLocked(); err != nil {
  458. return netw, err
  459. }
  460. _ = sm.applyDnsmasqConfigLocked()
  461. return netw, nil
  462. }
  463. func (sm *ServerManager) DeleteNetwork(id string) error {
  464. sm.mu.Lock()
  465. defer sm.mu.Unlock()
  466. delete(sm.networks, id)
  467. if err := sm.saveLocked(); err != nil {
  468. return err
  469. }
  470. return sm.applyDnsmasqConfigLocked()
  471. }
  472. // ======================== LEASES ========================
  473. func (sm *ServerManager) ListLeases() []DHCPLease {
  474. sm.mu.RLock()
  475. defer sm.mu.RUnlock()
  476. dynamicLeases := sm.readDnsmasqLeasesFile()
  477. staticMap := make(map[string]DHCPLease)
  478. for _, st := range sm.staticLeases {
  479. staticMap[strings.ToLower(st.MACAddress)] = st
  480. }
  481. result := make([]DHCPLease, 0)
  482. seenMACs := make(map[string]bool)
  483. // Combine dynamic leases
  484. for _, dl := range dynamicLeases {
  485. macLower := strings.ToLower(dl.MACAddress)
  486. seenMACs[macLower] = true
  487. if st, isStatic := staticMap[macLower]; isStatic {
  488. dl.Dynamic = false
  489. dl.Status = "static"
  490. dl.Comment = st.Comment
  491. dl.Disabled = st.Disabled
  492. dl.ExpiresIn = "never (static)"
  493. } else {
  494. dl.Dynamic = true
  495. dl.Status = "bound"
  496. }
  497. result = append(result, dl)
  498. }
  499. // Add static reservations that haven't acquired lease yet
  500. for macLower, st := range staticMap {
  501. if !seenMACs[macLower] {
  502. st.Dynamic = false
  503. st.Status = "waiting"
  504. st.ExpiresIn = "never (static)"
  505. result = append(result, st)
  506. }
  507. }
  508. sort.Slice(result, func(i, j int) bool {
  509. return compareIPs(net.ParseIP(result[i].Address), net.ParseIP(result[j].Address)) < 0
  510. })
  511. return result
  512. }
  513. func (sm *ServerManager) readDnsmasqLeasesFile() []DHCPLease {
  514. data, err := os.ReadFile(sm.leasesPath)
  515. if err != nil {
  516. return nil
  517. }
  518. lines := strings.Split(string(data), "\n")
  519. leases := make([]DHCPLease, 0, len(lines))
  520. now := time.Now()
  521. for _, line := range lines {
  522. line = strings.TrimSpace(line)
  523. if line == "" {
  524. continue
  525. }
  526. // Format: <timestamp> <mac> <ip> <hostname> <client-id>
  527. parts := strings.Fields(line)
  528. if len(parts) < 3 {
  529. continue
  530. }
  531. expTimestamp, _ := strconv.ParseInt(parts[0], 10, 64)
  532. mac := parts[1]
  533. ip := parts[2]
  534. hostname := "*"
  535. if len(parts) >= 4 && parts[3] != "*" {
  536. hostname = parts[3]
  537. }
  538. clientID := ""
  539. if len(parts) >= 5 && parts[4] != "*" {
  540. clientID = parts[4]
  541. }
  542. expiresAt := time.Unix(expTimestamp, 0)
  543. expiresIn := "expired"
  544. if expiresAt.After(now) {
  545. dur := expiresAt.Sub(now).Truncate(time.Minute)
  546. hours := int(dur.Hours())
  547. mins := int(dur.Minutes()) % 60
  548. expiresIn = fmt.Sprintf("%dh %dm", hours, mins)
  549. }
  550. // Determine server by matching IP against configured networks/pools
  551. serverName := sm.matchServerForIP(ip)
  552. leases = append(leases, DHCPLease{
  553. ID: fmt.Sprintf("lease-%s", strings.ReplaceAll(mac, ":", "")),
  554. Address: ip,
  555. MACAddress: mac,
  556. HostName: hostname,
  557. ClientID: clientID,
  558. Server: serverName,
  559. ExpiresAt: expiresAt,
  560. ExpiresIn: expiresIn,
  561. Dynamic: true,
  562. Status: "bound",
  563. })
  564. }
  565. return leases
  566. }
  567. func (sm *ServerManager) matchServerForIP(ipStr string) string {
  568. targetIP := net.ParseIP(ipStr)
  569. if targetIP == nil {
  570. return "dhcp1"
  571. }
  572. for _, srv := range sm.servers {
  573. startIP, endIP, _ := parseAddressPool(srv.AddressPool)
  574. if startIP != "" && endIP != "" {
  575. s := net.ParseIP(startIP)
  576. e := net.ParseIP(endIP)
  577. if s != nil && e != nil && compareIPs(targetIP, s) >= 0 && compareIPs(targetIP, e) <= 0 {
  578. return srv.Name
  579. }
  580. }
  581. }
  582. return "dhcp1"
  583. }
  584. func (sm *ServerManager) countActiveLeasesByServer() map[string]int {
  585. counts := make(map[string]int)
  586. leases := sm.readDnsmasqLeasesFile()
  587. for _, l := range leases {
  588. counts[l.Server]++
  589. }
  590. return counts
  591. }
  592. func (sm *ServerManager) SaveStaticLease(lease DHCPLease) (DHCPLease, error) {
  593. sm.mu.Lock()
  594. defer sm.mu.Unlock()
  595. if lease.ID == "" {
  596. lease.ID = fmt.Sprintf("static-%d", time.Now().UnixNano())
  597. }
  598. if lease.MACAddress == "" || lease.Address == "" {
  599. return lease, fmt.Errorf("both MAC address and IP address are required")
  600. }
  601. lease.MACAddress = strings.ToLower(lease.MACAddress)
  602. lease.Dynamic = false
  603. lease.Status = "static"
  604. sm.staticLeases[lease.ID] = lease
  605. if err := sm.saveLocked(); err != nil {
  606. return lease, err
  607. }
  608. _ = sm.applyDnsmasqConfigLocked()
  609. return lease, nil
  610. }
  611. func (sm *ServerManager) DeleteStaticLease(id string) error {
  612. sm.mu.Lock()
  613. defer sm.mu.Unlock()
  614. delete(sm.staticLeases, id)
  615. if err := sm.saveLocked(); err != nil {
  616. return err
  617. }
  618. return sm.applyDnsmasqConfigLocked()
  619. }
  620. func (sm *ServerManager) MakeStaticLease(mac, ip, hostname, comment string) (DHCPLease, error) {
  621. sm.mu.Lock()
  622. defer sm.mu.Unlock()
  623. macLower := strings.ToLower(strings.TrimSpace(mac))
  624. // Check if already in static leases
  625. for _, st := range sm.staticLeases {
  626. if strings.ToLower(st.MACAddress) == macLower {
  627. st.Address = ip
  628. if hostname != "" && hostname != "*" {
  629. st.HostName = hostname
  630. }
  631. if comment != "" {
  632. st.Comment = comment
  633. }
  634. sm.staticLeases[st.ID] = st
  635. _ = sm.saveLocked()
  636. _ = sm.applyDnsmasqConfigLocked()
  637. return st, nil
  638. }
  639. }
  640. id := fmt.Sprintf("static-%d", time.Now().UnixNano())
  641. st := DHCPLease{
  642. ID: id,
  643. MACAddress: macLower,
  644. Address: ip,
  645. HostName: hostname,
  646. Server: "all",
  647. Comment: comment,
  648. Dynamic: false,
  649. Status: "static",
  650. }
  651. sm.staticLeases[id] = st
  652. if err := sm.saveLocked(); err != nil {
  653. return st, err
  654. }
  655. _ = sm.applyDnsmasqConfigLocked()
  656. return st, nil
  657. }
  658. // ======================== OPTIONS ========================
  659. func (sm *ServerManager) ListOptions() []DHCPOption {
  660. sm.mu.RLock()
  661. defer sm.mu.RUnlock()
  662. list := make([]DHCPOption, 0, len(sm.options))
  663. for _, o := range sm.options {
  664. list = append(list, o)
  665. }
  666. sort.Slice(list, func(i, j int) bool {
  667. return list[i].Code < list[j].Code
  668. })
  669. return list
  670. }
  671. func (sm *ServerManager) SaveOption(opt DHCPOption) (DHCPOption, error) {
  672. sm.mu.Lock()
  673. defer sm.mu.Unlock()
  674. if opt.ID == "" {
  675. opt.ID = fmt.Sprintf("opt-%d", time.Now().UnixNano())
  676. }
  677. if opt.Name == "" || opt.Code <= 0 || opt.Code > 254 {
  678. return opt, fmt.Errorf("valid option name and code (1-254) are required")
  679. }
  680. sm.options[opt.ID] = opt
  681. if err := sm.saveLocked(); err != nil {
  682. return opt, err
  683. }
  684. _ = sm.applyDnsmasqConfigLocked()
  685. return opt, nil
  686. }
  687. func (sm *ServerManager) DeleteOption(id string) error {
  688. sm.mu.Lock()
  689. defer sm.mu.Unlock()
  690. delete(sm.options, id)
  691. if err := sm.saveLocked(); err != nil {
  692. return err
  693. }
  694. return sm.applyDnsmasqConfigLocked()
  695. }
  696. // ======================== SETUP WIZARD (MikroTik style) ========================
  697. func (sm *ServerManager) RunSetupWizard(req DHCPServerSetupRequest) error {
  698. sm.mu.Lock()
  699. defer sm.mu.Unlock()
  700. if req.Interface == "" {
  701. return fmt.Errorf("interface is required")
  702. }
  703. if req.AddressSpace == "" {
  704. req.AddressSpace = "192.168.88.0/24"
  705. }
  706. if req.Gateway == "" {
  707. req.Gateway = "192.168.88.1"
  708. }
  709. if req.AddressPool == "" {
  710. req.AddressPool = "192.168.88.10-192.168.88.254"
  711. }
  712. if len(req.DNSServers) == 0 {
  713. req.DNSServers = []string{req.Gateway, "1.1.1.1"}
  714. }
  715. if req.LeaseTime == "" {
  716. req.LeaseTime = "12h"
  717. }
  718. srvID := fmt.Sprintf("dhcp-%s", req.Interface)
  719. srv := DHCPServerInstance{
  720. ID: srvID,
  721. Name: fmt.Sprintf("dhcp-%s", req.Interface),
  722. Interface: req.Interface,
  723. Network: req.AddressSpace,
  724. AddressPool: req.AddressPool,
  725. LeaseTime: req.LeaseTime,
  726. Authoritative: true,
  727. Disabled: false,
  728. Comment: "Created by DHCP Setup Wizard",
  729. }
  730. sm.servers[srvID] = srv
  731. netID := fmt.Sprintf("net-%s", strings.ReplaceAll(req.AddressSpace, "/", "_"))
  732. netw := DHCPNetwork{
  733. ID: netID,
  734. Address: req.AddressSpace,
  735. Gateway: req.Gateway,
  736. DNSServers: req.DNSServers,
  737. Domain: req.Domain,
  738. NTPServers: req.NTPServers,
  739. NextServer: req.NextServer,
  740. BootFileName: req.BootFileName,
  741. Comment: fmt.Sprintf("Network for %s", req.Interface),
  742. }
  743. sm.networks[netID] = netw
  744. if err := sm.saveLocked(); err != nil {
  745. return err
  746. }
  747. return sm.applyDnsmasqConfigLocked()
  748. }
  749. // ======================== SUMMARY ========================
  750. func (sm *ServerManager) GetSummary() DHCPServerSummary {
  751. sm.mu.RLock()
  752. defer sm.mu.RUnlock()
  753. summary := DHCPServerSummary{
  754. TotalServers: len(sm.servers),
  755. TotalNetworks: len(sm.networks),
  756. StaticLeases: len(sm.staticLeases),
  757. TotalOptions: len(sm.options),
  758. }
  759. for _, s := range sm.servers {
  760. if !s.Disabled && isInterfaceUp(s.Interface) {
  761. summary.ActiveServers++
  762. }
  763. }
  764. leases := sm.readDnsmasqLeasesFile()
  765. summary.ActiveLeases = len(leases)
  766. return summary
  767. }
  768. // ======================== HELPERS ========================
  769. func sanitizeTag(name string) string {
  770. res := strings.Map(func(r rune) rune {
  771. if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' {
  772. return r
  773. }
  774. return '_'
  775. }, name)
  776. return strings.ToLower(res)
  777. }
  778. func parseAddressPool(pool string) (startIP, endIP, netmask string) {
  779. pool = strings.TrimSpace(pool)
  780. parts := strings.Split(pool, "-")
  781. if len(parts) == 2 {
  782. return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), ""
  783. }
  784. return "", "", ""
  785. }
  786. func isInterfaceUp(ifaceName string) bool {
  787. iface, err := net.InterfaceByName(ifaceName)
  788. if err != nil {
  789. return false
  790. }
  791. return (iface.Flags & net.FlagUp) != 0
  792. }
  793. func compareIPs(a, b net.IP) int {
  794. a4 := a.To4()
  795. b4 := b.To4()
  796. if a4 == nil || b4 == nil {
  797. return 0
  798. }
  799. for i := 0; i < 4; i++ {
  800. if a4[i] < b4[i] {
  801. return -1
  802. }
  803. if a4[i] > b4[i] {
  804. return 1
  805. }
  806. }
  807. return 0
  808. }