server_manager.go 23 KB

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