manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package dhcp
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. "github.com/vishvananda/netlink"
  15. )
  16. const (
  17. DHCPConfigFile = "/etc/proxmox-router/dhcp_clients.json"
  18. DHCPRunDir = "/run"
  19. DHCPLeaseDir = "/var/lib/dhcp"
  20. DHCPConfDir = "/etc/dhcp"
  21. )
  22. var (
  23. leaseBlockRegex = regexp.MustCompile(`(?s)lease\s+\{([^}]+)\}`)
  24. fixedAddrRegex = regexp.MustCompile(`fixed-address\s+([0-9.]+);`)
  25. subnetMaskRegex = regexp.MustCompile(`option subnet-mask\s+([0-9.]+);`)
  26. routersRegex = regexp.MustCompile(`option routers\s+([0-9.]+);`)
  27. dhcpServerRegex = regexp.MustCompile(`option dhcp-server-identifier\s+([0-9.]+);`)
  28. dnsServersRegex = regexp.MustCompile(`option domain-name-servers\s+([^;]+);`)
  29. domainNameRegex = regexp.MustCompile(`option domain-name\s+"([^"]+)";`)
  30. leaseTimeRegex = regexp.MustCompile(`option dhcp-lease-time\s+(\d+);`)
  31. expireTimeRegex = regexp.MustCompile(`expire\s+\d+\s+([0-9/]+ [0-9:]+);`)
  32. renewTimeRegex = regexp.MustCompile(`renew\s+\d+\s+([0-9/]+ [0-9:]+);`)
  33. validInterfaceRegex = regexp.MustCompile(`^[a-zA-Z0-9.:_-]+$`)
  34. )
  35. // DHCPConfigStore wraps the persisted configuration.
  36. type DHCPConfigStore struct {
  37. Clients []*DHCPClient `json:"clients"`
  38. }
  39. // Manager orchestrates all DHCP client instances.
  40. type Manager struct {
  41. mu sync.RWMutex
  42. storePath string
  43. clients map[string]*DHCPClient
  44. }
  45. // NewManager initializes the DHCP Manager and restores saved clients.
  46. func NewManager() *Manager {
  47. _ = os.MkdirAll("/etc/proxmox-router", 0755)
  48. _ = os.MkdirAll(DHCPLeaseDir, 0755)
  49. _ = os.MkdirAll(DHCPConfDir, 0755)
  50. m := &Manager{
  51. storePath: DHCPConfigFile,
  52. clients: make(map[string]*DHCPClient),
  53. }
  54. _ = m.Load()
  55. return m
  56. }
  57. // Load loads saved clients from disk and ensures enabled clients are started.
  58. func (m *Manager) Load() error {
  59. m.mu.Lock()
  60. defer m.mu.Unlock()
  61. data, err := os.ReadFile(m.storePath)
  62. if err != nil {
  63. if os.IsNotExist(err) {
  64. return nil
  65. }
  66. return err
  67. }
  68. var store DHCPConfigStore
  69. if err := json.Unmarshal(data, &store); err != nil {
  70. return err
  71. }
  72. for _, c := range store.Clients {
  73. if c.ID == "" {
  74. c.ID = "dhcp-" + c.Interface
  75. }
  76. m.clients[c.ID] = c
  77. }
  78. // Startup active clients
  79. go func() {
  80. time.Sleep(1 * time.Second)
  81. m.SyncAll()
  82. }()
  83. return nil
  84. }
  85. // Save persists the current DHCP clients to disk.
  86. func (m *Manager) Save() error {
  87. store := DHCPConfigStore{
  88. Clients: make([]*DHCPClient, 0, len(m.clients)),
  89. }
  90. for _, c := range m.clients {
  91. store.Clients = append(store.Clients, c)
  92. }
  93. data, err := json.MarshalIndent(store, "", " ")
  94. if err != nil {
  95. return err
  96. }
  97. tmpFile := m.storePath + ".tmp"
  98. if err := os.WriteFile(tmpFile, data, 0644); err != nil {
  99. return err
  100. }
  101. return os.Rename(tmpFile, m.storePath)
  102. }
  103. // SyncAll refreshes status and launches any enabled clients that aren't running.
  104. func (m *Manager) SyncAll() {
  105. m.mu.Lock()
  106. defer m.mu.Unlock()
  107. for _, c := range m.clients {
  108. m.updateStatus(c)
  109. if c.Enabled && c.Status != "bound" && c.Status != "searching" {
  110. _ = m.startClient(c)
  111. m.updateStatus(c)
  112. }
  113. }
  114. }
  115. // ListClients returns all DHCP clients with real-time lease info.
  116. func (m *Manager) ListClients() []*DHCPClient {
  117. m.mu.Lock()
  118. defer m.mu.Unlock()
  119. res := make([]*DHCPClient, 0, len(m.clients))
  120. for _, c := range m.clients {
  121. m.updateStatus(c)
  122. res = append(res, c)
  123. }
  124. return res
  125. }
  126. // GetSummary returns summary KPIs.
  127. func (m *Manager) GetSummary() DHCPSummary {
  128. clients := m.ListClients()
  129. sum := DHCPSummary{
  130. TotalClients: len(clients),
  131. }
  132. for _, c := range clients {
  133. switch c.Status {
  134. case "bound":
  135. sum.BoundClients++
  136. case "searching":
  137. sum.Searching++
  138. case "disabled":
  139. sum.Disabled++
  140. }
  141. }
  142. return sum
  143. }
  144. // GetClient retrieves a single client by ID.
  145. func (m *Manager) GetClient(id string) (*DHCPClient, error) {
  146. m.mu.Lock()
  147. defer m.mu.Unlock()
  148. c, ok := m.clients[id]
  149. if !ok {
  150. return nil, fmt.Errorf("dhcp client %s not found", id)
  151. }
  152. m.updateStatus(c)
  153. return c, nil
  154. }
  155. // AddClient creates and optionally starts a DHCP client on an interface.
  156. func (m *Manager) AddClient(req CreateDHCPClientRequest) (*DHCPClient, error) {
  157. iface := strings.TrimSpace(req.Interface)
  158. if iface == "" || !validInterfaceRegex.MatchString(iface) {
  159. return nil, fmt.Errorf("invalid interface name")
  160. }
  161. // Verify interface exists on system
  162. if _, err := net.InterfaceByName(iface); err != nil {
  163. return nil, fmt.Errorf("interface %s does not exist on host", iface)
  164. }
  165. m.mu.Lock()
  166. defer m.mu.Unlock()
  167. id := "dhcp-" + iface
  168. if _, exists := m.clients[id]; exists {
  169. return nil, fmt.Errorf("dhcp client already exists for interface %s", iface)
  170. }
  171. dist := req.DefaultRouteDistance
  172. if dist <= 0 {
  173. dist = 1
  174. }
  175. c := &DHCPClient{
  176. ID: id,
  177. Interface: iface,
  178. Enabled: req.Enabled,
  179. AddDefaultRoute: req.AddDefaultRoute,
  180. DefaultRouteDistance: dist,
  181. UsePeerDNS: req.UsePeerDNS,
  182. UsePeerNTP: req.UsePeerNTP,
  183. Comment: req.Comment,
  184. Status: "stopped",
  185. DNSServers: []string{},
  186. }
  187. if c.Enabled {
  188. if err := m.startClient(c); err != nil {
  189. c.Status = "error"
  190. }
  191. } else {
  192. c.Status = "disabled"
  193. }
  194. m.updateStatus(c)
  195. m.clients[id] = c
  196. _ = m.Save()
  197. return c, nil
  198. }
  199. // UpdateClient modifies client settings and restarts if needed.
  200. func (m *Manager) UpdateClient(id string, req UpdateDHCPClientRequest) (*DHCPClient, error) {
  201. m.mu.Lock()
  202. defer m.mu.Unlock()
  203. c, ok := m.clients[id]
  204. if !ok {
  205. return nil, fmt.Errorf("dhcp client %s not found", id)
  206. }
  207. needsRestart := false
  208. if req.AddDefaultRoute != nil && *req.AddDefaultRoute != c.AddDefaultRoute {
  209. c.AddDefaultRoute = *req.AddDefaultRoute
  210. needsRestart = true
  211. }
  212. if req.DefaultRouteDistance != nil && *req.DefaultRouteDistance != c.DefaultRouteDistance {
  213. c.DefaultRouteDistance = *req.DefaultRouteDistance
  214. needsRestart = true
  215. }
  216. if req.UsePeerDNS != nil && *req.UsePeerDNS != c.UsePeerDNS {
  217. c.UsePeerDNS = *req.UsePeerDNS
  218. needsRestart = true
  219. }
  220. if req.UsePeerNTP != nil && *req.UsePeerNTP != c.UsePeerNTP {
  221. c.UsePeerNTP = *req.UsePeerNTP
  222. needsRestart = true
  223. }
  224. if req.Comment != nil {
  225. c.Comment = *req.Comment
  226. }
  227. if req.Enabled != nil {
  228. if *req.Enabled != c.Enabled {
  229. c.Enabled = *req.Enabled
  230. if c.Enabled {
  231. _ = m.startClient(c)
  232. } else {
  233. _ = m.stopClient(c)
  234. c.Status = "disabled"
  235. }
  236. needsRestart = false
  237. }
  238. }
  239. if needsRestart && c.Enabled {
  240. _ = m.stopClient(c)
  241. _ = m.startClient(c)
  242. }
  243. m.updateStatus(c)
  244. _ = m.Save()
  245. return c, nil
  246. }
  247. // ToggleState enables or disables a DHCP client.
  248. func (m *Manager) ToggleState(id string, enabled bool) error {
  249. m.mu.Lock()
  250. defer m.mu.Unlock()
  251. c, ok := m.clients[id]
  252. if !ok {
  253. return fmt.Errorf("dhcp client %s not found", id)
  254. }
  255. c.Enabled = enabled
  256. if enabled {
  257. if err := m.startClient(c); err != nil {
  258. c.Status = "error"
  259. }
  260. } else {
  261. _ = m.stopClient(c)
  262. c.Status = "disabled"
  263. }
  264. m.updateStatus(c)
  265. return m.Save()
  266. }
  267. // RenewLease forces dhclient to renew its lease.
  268. func (m *Manager) RenewLease(id string) error {
  269. m.mu.Lock()
  270. defer m.mu.Unlock()
  271. c, ok := m.clients[id]
  272. if !ok {
  273. return fmt.Errorf("dhcp client %s not found", id)
  274. }
  275. if !c.Enabled {
  276. return fmt.Errorf("cannot renew disabled dhcp client")
  277. }
  278. _ = m.stopClient(c)
  279. time.Sleep(200 * time.Millisecond)
  280. err := m.startClient(c)
  281. m.updateStatus(c)
  282. return err
  283. }
  284. // ReleaseLease sends DHCPRELEASE and removes the IP address.
  285. func (m *Manager) ReleaseLease(id string) error {
  286. m.mu.Lock()
  287. defer m.mu.Unlock()
  288. c, ok := m.clients[id]
  289. if !ok {
  290. return fmt.Errorf("dhcp client %s not found", id)
  291. }
  292. pidFile := fmt.Sprintf("%s/dhclient.%s.pid", DHCPRunDir, c.Interface)
  293. leaseFile := fmt.Sprintf("%s/dhclient.%s.leases", DHCPLeaseDir, c.Interface)
  294. cmd := exec.Command("dhclient", "-4", "-r", "-pf", pidFile, "-lf", leaseFile, c.Interface)
  295. _ = cmd.Run()
  296. _ = m.stopClient(c)
  297. c.Status = "stopped"
  298. c.IPAddress = ""
  299. c.Gateway = ""
  300. c.ExpiresIn = ""
  301. return m.Save()
  302. }
  303. // DeleteClient stops the client and removes it from configuration.
  304. func (m *Manager) DeleteClient(id string) error {
  305. m.mu.Lock()
  306. defer m.mu.Unlock()
  307. c, ok := m.clients[id]
  308. if !ok {
  309. return fmt.Errorf("dhcp client %s not found", id)
  310. }
  311. _ = m.stopClient(c)
  312. // Clean up conf & lease files
  313. _ = os.Remove(fmt.Sprintf("%s/dhclient.%s.pid", DHCPRunDir, c.Interface))
  314. _ = os.Remove(fmt.Sprintf("%s/dhclient-%s.conf", DHCPConfDir, c.Interface))
  315. delete(m.clients, id)
  316. return m.Save()
  317. }
  318. func (m *Manager) startClient(c *DHCPClient) error {
  319. pidFile := fmt.Sprintf("%s/dhclient.%s.pid", DHCPRunDir, c.Interface)
  320. leaseFile := fmt.Sprintf("%s/dhclient.%s.leases", DHCPLeaseDir, c.Interface)
  321. confFile := fmt.Sprintf("%s/dhclient-%s.conf", DHCPConfDir, c.Interface)
  322. // Generate custom dhclient config
  323. var sb strings.Builder
  324. sb.WriteString("# RouterOS-style dhclient configuration\n")
  325. sb.WriteString("send host-name = gethostname();\n")
  326. sb.WriteString("request subnet-mask, broadcast-address, time-offset")
  327. if c.AddDefaultRoute {
  328. sb.WriteString(", routers")
  329. }
  330. if c.UsePeerDNS {
  331. sb.WriteString(", domain-name, domain-name-servers, domain-search, host-name")
  332. }
  333. if c.UsePeerNTP {
  334. sb.WriteString(", ntp-servers")
  335. }
  336. sb.WriteString(";\n")
  337. _ = os.WriteFile(confFile, []byte(sb.String()), 0644)
  338. // If already running, kill first
  339. _ = m.stopClient(c)
  340. // Launch dhclient in background
  341. cmd := exec.Command("dhclient", "-4", "-nw", "-pf", pidFile, "-lf", leaseFile, "-cf", confFile, c.Interface)
  342. if err := cmd.Run(); err != nil {
  343. return fmt.Errorf("failed to start dhclient: %w", err)
  344. }
  345. c.Status = "searching"
  346. return nil
  347. }
  348. func (m *Manager) stopClient(c *DHCPClient) error {
  349. pidFile := fmt.Sprintf("%s/dhclient.%s.pid", DHCPRunDir, c.Interface)
  350. // Check PID file
  351. if pidBytes, err := os.ReadFile(pidFile); err == nil {
  352. if pid, err := strconv.Atoi(strings.TrimSpace(string(pidBytes))); err == nil && pid > 0 {
  353. _ = syscall.Kill(pid, syscall.SIGTERM)
  354. time.Sleep(100 * time.Millisecond)
  355. if err := syscall.Kill(pid, 0); err == nil {
  356. _ = syscall.Kill(pid, syscall.SIGKILL)
  357. }
  358. }
  359. }
  360. _ = os.Remove(pidFile)
  361. c.PID = 0
  362. return nil
  363. }
  364. func (m *Manager) updateStatus(c *DHCPClient) {
  365. pidFile := fmt.Sprintf("%s/dhclient.%s.pid", DHCPRunDir, c.Interface)
  366. leaseFile := fmt.Sprintf("%s/dhclient.%s.leases", DHCPLeaseDir, c.Interface)
  367. // Check if process is alive
  368. isRunning := false
  369. if pidBytes, err := os.ReadFile(pidFile); err == nil {
  370. if pid, err := strconv.Atoi(strings.TrimSpace(string(pidBytes))); err == nil && pid > 0 {
  371. if err := syscall.Kill(pid, 0); err == nil {
  372. isRunning = true
  373. c.PID = pid
  374. }
  375. }
  376. }
  377. if !isRunning {
  378. c.PID = 0
  379. if !c.Enabled {
  380. c.Status = "disabled"
  381. } else {
  382. c.Status = "stopped"
  383. }
  384. } else {
  385. c.Status = "searching"
  386. }
  387. // Read interface IPv4 addresses via netlink
  388. if link, err := netlink.LinkByName(c.Interface); err == nil {
  389. if addrs, err := netlink.AddrList(link, netlink.FAMILY_V4); err == nil && len(addrs) > 0 {
  390. for _, a := range addrs {
  391. ip := a.IPNet.IP.String()
  392. if !strings.HasPrefix(ip, "127.") && !strings.HasPrefix(ip, "169.254.") {
  393. c.IPAddress = a.IPNet.String()
  394. if isRunning {
  395. c.Status = "bound"
  396. }
  397. break
  398. }
  399. }
  400. }
  401. }
  402. // Parse lease file for rich metadata (gateway, dns, lease times)
  403. m.parseLeaseFile(leaseFile, c)
  404. }
  405. func (m *Manager) parseLeaseFile(leaseFile string, c *DHCPClient) {
  406. data, err := os.ReadFile(leaseFile)
  407. if err != nil {
  408. return
  409. }
  410. // Find the last lease block in the file
  411. matches := leaseBlockRegex.FindAllStringSubmatch(string(data), -1)
  412. if len(matches) == 0 {
  413. return
  414. }
  415. lastLease := matches[len(matches)-1][1]
  416. if m := fixedAddrRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  417. ip := m[1]
  418. mask := "24"
  419. if sm := subnetMaskRegex.FindStringSubmatch(lastLease); len(sm) > 1 {
  420. mask = subnetToCIDR(sm[1])
  421. }
  422. if c.IPAddress == "" {
  423. c.IPAddress = fmt.Sprintf("%s/%s", ip, mask)
  424. }
  425. }
  426. if m := routersRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  427. c.Gateway = m[1]
  428. }
  429. if m := dhcpServerRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  430. c.DHCPServer = m[1]
  431. }
  432. if m := dnsServersRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  433. raw := strings.Split(m[1], ",")
  434. dns := make([]string, 0, len(raw))
  435. for _, s := range raw {
  436. trimmed := strings.TrimSpace(s)
  437. if trimmed != "" {
  438. dns = append(dns, trimmed)
  439. }
  440. }
  441. c.DNSServers = dns
  442. }
  443. if m := domainNameRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  444. c.Domain = m[1]
  445. }
  446. if m := leaseTimeRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  447. c.LeaseTime, _ = strconv.Atoi(m[1])
  448. }
  449. if m := expireTimeRegex.FindStringSubmatch(lastLease); len(m) > 1 {
  450. // e.g. "2026/10/26 18:30:00"
  451. if t, err := time.Parse("2006/01/02 15:04:05", m[1]); err == nil {
  452. c.ExpiresAt = t
  453. rem := time.Until(t)
  454. if rem > 0 {
  455. hours := int(rem.Hours())
  456. mins := int(rem.Minutes()) % 60
  457. if hours > 24 {
  458. c.ExpiresIn = fmt.Sprintf("%dd %dh", hours/24, hours%24)
  459. } else if hours > 0 {
  460. c.ExpiresIn = fmt.Sprintf("%dh %dm", hours, mins)
  461. } else {
  462. c.ExpiresIn = fmt.Sprintf("%dm %ds", mins, int(rem.Seconds())%60)
  463. }
  464. } else {
  465. c.ExpiresIn = "Expired"
  466. }
  467. }
  468. }
  469. }
  470. func subnetToCIDR(mask string) string {
  471. parts := strings.Split(mask, ".")
  472. if len(parts) != 4 {
  473. return "24"
  474. }
  475. var count int
  476. for _, p := range parts {
  477. n, _ := strconv.Atoi(p)
  478. for n > 0 {
  479. count += n & 1
  480. n >>= 1
  481. }
  482. }
  483. return strconv.Itoa(count)
  484. }