device_actions.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // device_actions.go — acciones directas sobre routers para un dispositivo
  2. // (issue #439): reserva DHCP estática en el gateway y bloqueo MAC en el router
  3. // de atache. Escriben /etc/config/dhcp y /etc/config/firewall vía SSH
  4. // (SSHRunner, fakeable en tests) usando uci, con `uci commit` como límite
  5. // atómico y rollback si el reinicio del servicio falla (sin config a medias).
  6. package httpapi
  7. import (
  8. "fmt"
  9. "log"
  10. "net"
  11. "net/http"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  16. )
  17. // Techos para los comandos uci sobre SSH (show = lectura, apply = escritura
  18. // + commit + reload). Son límites fijos del ejecutor, no configurables.
  19. const (
  20. uciShowTimeout = 10 * time.Second
  21. uciApplyTimeout = 20 * time.Second
  22. )
  23. var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
  24. var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
  25. // reDhcpHostname: hostname DNS (etiquetas alfanuméricas con guiones internos,
  26. // separadas por puntos). dnsmasq registra el `name` de la sección host en su
  27. // DNS local, así que cualquier otra cosa (espacios, acentos, metacaracteres)
  28. // no es un hostname válido y se rechaza (#693).
  29. var reDhcpHostname = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
  30. // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
  31. func uciValue(raw string) string {
  32. if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
  33. return m[1]
  34. }
  35. return raw
  36. }
  37. // uciQuote escapa v para incrustarlo sin riesgo entre comillas simples de un
  38. // comando uci: la única forma de salir de '...' es otra comilla simple, que se
  39. // neutraliza cerrando, escapándola con backslash y reabriendo (secuencia
  40. // POSIX clásica de cierre-escape-apertura). Sin esto, un hostname tipo
  41. // `x'; cmd; echo '` inyecta comandos que corren como root en el router vía
  42. // SSH (#693).
  43. func uciQuote(v string) string {
  44. return strings.ReplaceAll(v, "'", `'\''`)
  45. }
  46. // uciSetCmd construye `uci set <cfg>.<sect>.<opt>='<valor escapado>'`. Todo
  47. // valor dinámico de un comando uci pasa por aquí (#693).
  48. func uciSetCmd(cfg, sect, opt, value string) string {
  49. return fmt.Sprintf("uci set %s.%s.%s='%s'", cfg, sect, opt, uciQuote(value))
  50. }
  51. // validDHCPHostname acepta vacío (= no tocar el name; el alta usará la MAC) o
  52. // un hostname DNS de hasta 253 caracteres (#693).
  53. func validDHCPHostname(h string) bool {
  54. if h == "" {
  55. return true
  56. }
  57. if len(h) > 253 {
  58. return false
  59. }
  60. return reDhcpHostname.MatchString(h)
  61. }
  62. // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
  63. // si no hay gateway configurado o es agent-only. El gateway es quien sirve
  64. // DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
  65. func (s *server) gatewayHost() string {
  66. for _, r := range routerstore.ListRouters(s.db.DB) {
  67. if r.IsGateway && !r.AgentOnly && r.Host != "" {
  68. return r.SSHAddr()
  69. }
  70. }
  71. return ""
  72. }
  73. // leaseRouterResolver lo implementa el adapter live para decir qué router
  74. // reportó la MAC en su tabla de leases DHCP (issue #537). La demo no lo
  75. // implementa → la reserva cae al gateway, como antes.
  76. type leaseRouterResolver interface {
  77. RouterServingDHCP(mac string) string
  78. }
  79. // reservationTargetHost resuelve DÓNDE vive la reserva DHCP de un dispositivo
  80. // (issue #537): no siempre en el gateway global. Un dispositivo cuya IP la
  81. // concede un router con su propio dnsmasq (p. ej. una LAN separada tras un AP
  82. // con DHCP propio) debe reservarse en ESE router, que es quien reportó su
  83. // lease. Orden:
  84. // 1. Router que reportó la MAC en leases (RouterServingDHCP), si el adapter
  85. // lo soporta y el router es alcanzable por SSH.
  86. // 2. Fallback: el gateway (red gestionada clásica con un solo servidor DHCP).
  87. func (s *server) reservationTargetHost(mac string) string {
  88. if lr, ok := s.adapter.(leaseRouterResolver); ok {
  89. if routerID := lr.RouterServingDHCP(mac); routerID != "" {
  90. if host := s.hostOfRouter(routerID); host != "" {
  91. return host
  92. }
  93. }
  94. }
  95. return s.gatewayHost()
  96. }
  97. // uciShow ejecuta `uci show <config>` en un host y devuelve líneas parseables.
  98. func (s *server) uciShow(host, config string) ([]string, error) {
  99. if s.pool == nil {
  100. return nil, fmt.Errorf("no SSH pool")
  101. }
  102. out, err := s.pool.Run(host, fmt.Sprintf("uci show %s", config), uciShowTimeout)
  103. if err != nil {
  104. return nil, err
  105. }
  106. return strings.Split(out, "\n"), nil
  107. }
  108. // runUCICommands encadena comandos uci + `uci commit <config>` en UNA sesión
  109. // SSH. `uci commit` es el límite atómico: si un `uci set/delete` falla antes,
  110. // el `&&` corta y /etc/config queda intacto (staging descartado).
  111. func (s *server) runUCICommands(host, config string, commands []string) error {
  112. if s.pool == nil {
  113. return fmt.Errorf("no SSH pool")
  114. }
  115. script := strings.Join(append(commands, "uci commit "+config), " && ")
  116. _, err := s.pool.Run(host, script, uciApplyTimeout)
  117. return err
  118. }
  119. // reloadService reinicia el servicio procd que aplica la config commitada.
  120. func (s *server) reloadService(host, service string) error {
  121. if s.pool == nil {
  122. return fmt.Errorf("no SSH pool")
  123. }
  124. _, err := s.pool.Run(host, "/etc/init.d/"+service+" restart", uciApplyTimeout)
  125. return err
  126. }
  127. // ---------------------------------------------------------------------------
  128. // Reserva DHCP (host sections de /etc/config/dhcp)
  129. // ---------------------------------------------------------------------------
  130. // dhcpHost representa una sección host de dhcp UCI.
  131. type dhcpHost struct {
  132. Section string
  133. Name string
  134. MAC string
  135. IP string
  136. }
  137. // uciTypeSections devuelve el conjunto de secciones de un config cuya línea de
  138. // tipo (`cfg.<section>=<type>`) coincide con el tipo pedido.
  139. func uciTypeSections(lines []string, config, typ string) map[string]bool {
  140. sections := map[string]bool{}
  141. for _, raw := range lines {
  142. line := strings.TrimSpace(raw)
  143. m := reUciLine.FindStringSubmatch(line)
  144. if m == nil || m[1] != config {
  145. continue
  146. }
  147. if strings.Index(m[2], ".") >= 0 {
  148. continue // es una opción, no la línea de tipo
  149. }
  150. if uciValue(m[3]) == typ {
  151. sections[m[2]] = true
  152. }
  153. }
  154. return sections
  155. }
  156. // parseDhcpHosts parsea `uci show dhcp` y devuelve SOLO las secciones de tipo
  157. // host (named `dhcp.np_host_x=host` y anónimas `dhcp.@host[0]=host`), filtrando
  158. // el ruido de @dnsmasq[0], lan, wan, etc.
  159. func parseDhcpHosts(lines []string) []*dhcpHost {
  160. hostSections := uciTypeSections(lines, "dhcp", "host")
  161. var hosts []*dhcpHost
  162. bySection := map[string]*dhcpHost{}
  163. for _, raw := range lines {
  164. line := strings.TrimSpace(raw)
  165. if line == "" {
  166. continue
  167. }
  168. m := reUciLine.FindStringSubmatch(line)
  169. if m == nil || m[1] != "dhcp" {
  170. continue
  171. }
  172. dot := strings.Index(m[2], ".")
  173. if dot < 0 {
  174. continue
  175. }
  176. section, option := m[2][:dot], m[2][dot+1:]
  177. if !hostSections[section] {
  178. continue
  179. }
  180. h := bySection[section]
  181. if h == nil {
  182. h = &dhcpHost{Section: section}
  183. bySection[section] = h
  184. hosts = append(hosts, h)
  185. }
  186. switch option {
  187. case "name":
  188. h.Name = uciValue(m[3])
  189. case "mac":
  190. h.MAC = uciValue(m[3])
  191. case "ip":
  192. h.IP = uciValue(m[3])
  193. }
  194. }
  195. return hosts
  196. }
  197. // findDhcpHost busca una sección host cuya MAC coincida (sin importar el
  198. // formato; admite varias MACs separadas por coma/espacio en una misma sección).
  199. func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
  200. macNorm := normalizeMAC(mac)
  201. for _, h := range hosts {
  202. for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' }) {
  203. if normalizeMAC(m) == macNorm {
  204. return h
  205. }
  206. }
  207. }
  208. return nil
  209. }
  210. // dhcpHostSection es el nombre de sección determinista para la reserva de una
  211. // MAC (uci set dhcp.np_host_<mac12>=host).
  212. func dhcpHostSection(mac string) string {
  213. return "np_host_" + strings.ReplaceAll(mac, ":", "")
  214. }
  215. // handleDeviceReservationGet devuelve la reserva DHCP estática de un dispositivo.
  216. func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Request) {
  217. mac := normalizeMAC(r.PathValue("mac"))
  218. if len(mac) != 17 {
  219. writeError(w, http.StatusBadRequest, "invalid_mac")
  220. return
  221. }
  222. host := s.reservationTargetHost(mac)
  223. if host == "" {
  224. writeError(w, http.StatusBadRequest, "no_gateway")
  225. return
  226. }
  227. lines, err := s.uciShow(host, "dhcp")
  228. if err != nil {
  229. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  230. return
  231. }
  232. hosts := parseDhcpHosts(lines)
  233. if h := findDhcpHost(hosts, mac); h != nil {
  234. writeJSON(w, http.StatusOK, map[string]any{
  235. "reserved": true,
  236. "ip": h.IP,
  237. "name": h.Name,
  238. })
  239. return
  240. }
  241. writeJSON(w, http.StatusOK, map[string]any{"reserved": false})
  242. }
  243. // handleDeviceReservationPut crea o actualiza una reserva DHCP estática.
  244. // Idempotente (misma MAC+IP → no-op). Rechaza con 409 si OTRA MAC ya tiene
  245. // reservada la IP pedida.
  246. func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Request) {
  247. // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
  248. setLongWriteDeadline(w, deviceActionWriteCeiling)
  249. mac := normalizeMAC(r.PathValue("mac"))
  250. if len(mac) != 17 {
  251. writeError(w, http.StatusBadRequest, "invalid_mac")
  252. return
  253. }
  254. var body struct {
  255. IP string `json:"ip"`
  256. Hostname string `json:"hostname"`
  257. }
  258. if st := readJSONBody(w, r, &body); st != 0 {
  259. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  260. return
  261. }
  262. if net.ParseIP(body.IP) == nil {
  263. writeError(w, http.StatusBadRequest, "invalid_ip")
  264. return
  265. }
  266. if !validDHCPHostname(body.Hostname) {
  267. writeError(w, http.StatusBadRequest, "invalid_hostname",
  268. "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
  269. return
  270. }
  271. host := s.reservationTargetHost(mac)
  272. if host == "" {
  273. writeError(w, http.StatusBadRequest, "no_gateway")
  274. return
  275. }
  276. lines, err := s.uciShow(host, "dhcp")
  277. if err != nil {
  278. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  279. return
  280. }
  281. hosts := parseDhcpHosts(lines)
  282. // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
  283. for _, h := range hosts {
  284. if h.IP != body.IP {
  285. continue
  286. }
  287. if findDhcpHost([]*dhcpHost{h}, mac) != nil {
  288. continue // es la sección de esta misma MAC (update idempotente)
  289. }
  290. writeError(w, http.StatusConflict, "ip_conflict",
  291. fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
  292. return
  293. }
  294. existing := findDhcpHost(hosts, mac)
  295. var apply, rollback []string
  296. if existing != nil {
  297. oldIP := existing.IP
  298. apply = append(apply, uciSetCmd("dhcp", existing.Section, "ip", body.IP))
  299. if body.Hostname != "" && body.Hostname != existing.Name {
  300. apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
  301. }
  302. rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "ip", oldIP))
  303. } else {
  304. section := dhcpHostSection(mac)
  305. name := body.Hostname
  306. if name == "" {
  307. name = mac
  308. }
  309. apply = append(apply,
  310. fmt.Sprintf("uci set dhcp.%s=host", section),
  311. uciSetCmd("dhcp", section, "name", name),
  312. uciSetCmd("dhcp", section, "mac", mac),
  313. uciSetCmd("dhcp", section, "ip", body.IP),
  314. )
  315. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
  316. }
  317. // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
  318. if r.URL.Query().Get("dry_run") == "1" {
  319. writeDevicePlan(w, mac, host, apply, rollback)
  320. return
  321. }
  322. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  323. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  324. return
  325. }
  326. if err := s.reloadService(host, "dnsmasq"); err != nil {
  327. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  328. log.Printf("[netpulse] reservation rollback for %s failed: %v", mac, rbErr)
  329. }
  330. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  331. return
  332. }
  333. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
  334. }
  335. // handleDeviceReservationHostnamePut aplica el nombre visible de NetPulse como
  336. // hostname de la reserva DHCP del dispositivo (#800): si la MAC ya tiene
  337. // reserva se actualiza solo el `name` (la IP no se toca); si no, se crea la
  338. // reserva con la IP actual del dispositivo. El hostname debe ser DNS válido y
  339. // NO vacío (#693): es el objetivo de la acción, no un opcional. La UI deriva
  340. // el hostname del nombre visible y deshabilita la acción si no es aplicable.
  341. func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *http.Request) {
  342. // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
  343. setLongWriteDeadline(w, deviceActionWriteCeiling)
  344. mac := normalizeMAC(r.PathValue("mac"))
  345. if len(mac) != 17 {
  346. writeError(w, http.StatusBadRequest, "invalid_mac")
  347. return
  348. }
  349. var body struct {
  350. IP string `json:"ip"`
  351. Hostname string `json:"hostname"`
  352. }
  353. if st := readJSONBody(w, r, &body); st != 0 {
  354. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  355. return
  356. }
  357. // A diferencia del PUT de reserva, aquí el hostname ES el objetivo de la
  358. // acción: vacío no significa "no tocar", significa petición sin sentido.
  359. if body.Hostname == "" || !validDHCPHostname(body.Hostname) {
  360. writeError(w, http.StatusBadRequest, "invalid_hostname",
  361. "el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
  362. return
  363. }
  364. if net.ParseIP(body.IP) == nil {
  365. writeError(w, http.StatusBadRequest, "invalid_ip")
  366. return
  367. }
  368. host := s.reservationTargetHost(mac)
  369. if host == "" {
  370. writeError(w, http.StatusBadRequest, "no_gateway")
  371. return
  372. }
  373. lines, err := s.uciShow(host, "dhcp")
  374. if err != nil {
  375. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  376. return
  377. }
  378. hosts := parseDhcpHosts(lines)
  379. // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
  380. for _, h := range hosts {
  381. if h.IP != body.IP {
  382. continue
  383. }
  384. if findDhcpHost([]*dhcpHost{h}, mac) != nil {
  385. continue // es la sección de esta misma MAC
  386. }
  387. writeError(w, http.StatusConflict, "ip_conflict",
  388. fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
  389. return
  390. }
  391. existing := findDhcpHost(hosts, mac)
  392. var apply, rollback []string
  393. created := false
  394. if existing != nil {
  395. if existing.Name == body.Hostname {
  396. // No-op idempotente: el router ya tiene exactamente ese hostname.
  397. writeJSON(w, http.StatusOK, map[string]any{
  398. "ok": true, "mac": mac, "ip": existing.IP, "noop": true,
  399. })
  400. return
  401. }
  402. apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
  403. if existing.Name != "" {
  404. rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "name", existing.Name))
  405. } else {
  406. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s.name", existing.Section))
  407. }
  408. } else {
  409. created = true
  410. section := dhcpHostSection(mac)
  411. apply = append(apply,
  412. fmt.Sprintf("uci set dhcp.%s=host", section),
  413. uciSetCmd("dhcp", section, "name", body.Hostname),
  414. uciSetCmd("dhcp", section, "mac", mac),
  415. uciSetCmd("dhcp", section, "ip", body.IP),
  416. )
  417. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
  418. }
  419. // Dry-run (#754): devolver el plan sin ejecutar nada en el router.
  420. if r.URL.Query().Get("dry_run") == "1" {
  421. writeDevicePlan(w, mac, host, apply, rollback)
  422. return
  423. }
  424. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  425. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  426. return
  427. }
  428. if err := s.reloadService(host, "dnsmasq"); err != nil {
  429. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  430. log.Printf("[netpulse] hostname reservation rollback for %s failed: %v", mac, rbErr)
  431. }
  432. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  433. return
  434. }
  435. writeJSON(w, http.StatusOK, map[string]any{
  436. "ok": true, "mac": mac, "ip": body.IP, "created": created,
  437. })
  438. }
  439. // writeDevicePlan responde un dry-run (#754): comandos que SE EJECUTARÍAN
  440. // (apply) y su plan de vuelta (rollback), sin tocar el router.
  441. func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []string) {
  442. writeJSON(w, http.StatusOK, map[string]any{
  443. "ok": true,
  444. "dryRun": true,
  445. "mac": mac,
  446. "host": host,
  447. "apply": apply,
  448. "rollback": rollback,
  449. })
  450. }
  451. // handleDeviceReservationDelete elimina la reserva DHCP estática.
  452. func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
  453. // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
  454. setLongWriteDeadline(w, deviceActionWriteCeiling)
  455. mac := normalizeMAC(r.PathValue("mac"))
  456. if len(mac) != 17 {
  457. writeError(w, http.StatusBadRequest, "invalid_mac")
  458. return
  459. }
  460. host := s.reservationTargetHost(mac)
  461. if host == "" {
  462. writeError(w, http.StatusBadRequest, "no_gateway")
  463. return
  464. }
  465. lines, err := s.uciShow(host, "dhcp")
  466. if err != nil {
  467. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  468. return
  469. }
  470. hosts := parseDhcpHosts(lines)
  471. h := findDhcpHost(hosts, mac)
  472. if h == nil {
  473. writeError(w, http.StatusNotFound, "not_reserved")
  474. return
  475. }
  476. // Rollback = re-crear la sección tal cual estaba (si el reload falla).
  477. var rollback []string
  478. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
  479. if h.Name != "" {
  480. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "name", h.Name))
  481. }
  482. if h.MAC != "" {
  483. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "mac", h.MAC))
  484. }
  485. if h.IP != "" {
  486. rollback = append(rollback, uciSetCmd("dhcp", h.Section, "ip", h.IP))
  487. }
  488. apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
  489. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  490. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  491. return
  492. }
  493. if err := s.reloadService(host, "dnsmasq"); err != nil {
  494. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  495. log.Printf("[netpulse] reservation deletion rollback for %s failed: %v", mac, rbErr)
  496. }
  497. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  498. return
  499. }
  500. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  501. }
  502. // ---------------------------------------------------------------------------
  503. // Bloqueo de dispositivo (rule de /etc/config/firewall, fw4)
  504. // ---------------------------------------------------------------------------
  505. // firewallRule representa una sección rule de firewall UCI.
  506. type firewallRule struct {
  507. Section string
  508. Name string
  509. SrcMAC string
  510. Target string
  511. }
  512. // parseFirewallRules parsea `uci show firewall` y devuelve las reglas (named
  513. // `firewall.np_block_x=rule` y anónimas `firewall.@rule[0]=rule`).
  514. func parseFirewallRules(lines []string) []*firewallRule {
  515. ruleSections := uciTypeSections(lines, "firewall", "rule")
  516. var rules []*firewallRule
  517. bySection := map[string]*firewallRule{}
  518. for _, raw := range lines {
  519. line := strings.TrimSpace(raw)
  520. if line == "" {
  521. continue
  522. }
  523. m := reUciLine.FindStringSubmatch(line)
  524. if m == nil || m[1] != "firewall" {
  525. continue
  526. }
  527. dot := strings.Index(m[2], ".")
  528. if dot < 0 {
  529. continue
  530. }
  531. section, option := m[2][:dot], m[2][dot+1:]
  532. if !ruleSections[section] {
  533. continue
  534. }
  535. r := bySection[section]
  536. if r == nil {
  537. r = &firewallRule{Section: section}
  538. bySection[section] = r
  539. rules = append(rules, r)
  540. }
  541. switch option {
  542. case "name":
  543. r.Name = uciValue(m[3])
  544. case "src_mac":
  545. r.SrcMAC = uciValue(m[3])
  546. case "target":
  547. r.Target = uciValue(m[3])
  548. }
  549. }
  550. return rules
  551. }
  552. // blockRuleSection es el nombre de sección determinista para el bloqueo de una
  553. // MAC (uci set firewall.np_block_<mac12>=rule).
  554. func blockRuleSection(mac string) string {
  555. return "np_block_" + strings.ReplaceAll(mac, ":", "")
  556. }
  557. // blockRuleName es el nombre legible de la regla (mostrado en LuCI).
  558. func blockRuleName(mac string) string {
  559. return "np-block-" + strings.ReplaceAll(mac, ":", "")
  560. }
  561. // findBlockRule busca la regla de bloqueo de una MAC: por sección determinista
  562. // o por nombre legado (reglas anónimas `@rule[N]` con name='np-block-<mac>').
  563. func findBlockRule(rules []*firewallRule, mac string) *firewallRule {
  564. section := blockRuleSection(mac)
  565. name := blockRuleName(mac)
  566. for _, r := range rules {
  567. if r.Section == section || r.Name == name {
  568. return r
  569. }
  570. }
  571. return nil
  572. }
  573. // blockRuleApply/blockRuleRollback construyen los comandos uci de la regla
  574. // fw4. Forma mínima correcta (drop de tráfico reenviado desde la MAC, sin
  575. // romper su lease DHCP, que es input al router): src=lan, dest=*, target=DROP,
  576. // src_mac=<mac>.
  577. func blockRuleApply(section, mac string) []string {
  578. return []string{
  579. fmt.Sprintf("uci set firewall.%s=rule", section),
  580. uciSetCmd("firewall", section, "name", blockRuleName(mac)),
  581. fmt.Sprintf("uci set firewall.%s.src='lan'", section),
  582. fmt.Sprintf("uci set firewall.%s.dest='*'", section),
  583. fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
  584. uciSetCmd("firewall", section, "src_mac", mac),
  585. }
  586. }
  587. func blockRuleRollback(section string) []string {
  588. return []string{fmt.Sprintf("uci delete firewall.%s", section)}
  589. }
  590. // handleDeviceBlockGet indica si un dispositivo está bloqueado.
  591. func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
  592. mac := normalizeMAC(r.PathValue("mac"))
  593. if len(mac) != 17 {
  594. writeError(w, http.StatusBadRequest, "invalid_mac")
  595. return
  596. }
  597. routerID := r.URL.Query().Get("router")
  598. if routerID == "" {
  599. writeError(w, http.StatusBadRequest, "missing_router")
  600. return
  601. }
  602. host := s.hostOfRouter(routerID)
  603. if host == "" {
  604. writeError(w, http.StatusBadRequest, "no_router")
  605. return
  606. }
  607. lines, err := s.uciShow(host, "firewall")
  608. if err != nil {
  609. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  610. return
  611. }
  612. rules := parseFirewallRules(lines)
  613. blocked := findBlockRule(rules, mac) != nil
  614. writeJSON(w, http.StatusOK, map[string]any{"blocked": blocked})
  615. }
  616. // handleDeviceBlockPut bloquea un dispositivo añadiendo una regla de firewall.
  617. func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
  618. // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
  619. setLongWriteDeadline(w, deviceActionWriteCeiling)
  620. mac := normalizeMAC(r.PathValue("mac"))
  621. if len(mac) != 17 {
  622. writeError(w, http.StatusBadRequest, "invalid_mac")
  623. return
  624. }
  625. var body struct {
  626. RouterID string `json:"router"`
  627. }
  628. if st := readJSONBody(w, r, &body); st != 0 {
  629. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  630. return
  631. }
  632. if body.RouterID == "" {
  633. writeError(w, http.StatusBadRequest, "missing_router")
  634. return
  635. }
  636. host := s.hostOfRouter(body.RouterID)
  637. if host == "" {
  638. writeError(w, http.StatusBadRequest, "no_router")
  639. return
  640. }
  641. lines, err := s.uciShow(host, "firewall")
  642. if err != nil {
  643. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  644. return
  645. }
  646. rules := parseFirewallRules(lines)
  647. if findBlockRule(rules, mac) != nil {
  648. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  649. return
  650. }
  651. section := blockRuleSection(mac)
  652. // Dry-run (#754): plan sin ejecutar (el check de "ya bloqueado" sí corre:
  653. // es lectura uci show, no escribe nada).
  654. if r.URL.Query().Get("dry_run") == "1" {
  655. writeDevicePlan(w, mac, host, blockRuleApply(section, mac), blockRuleRollback(section))
  656. return
  657. }
  658. if err := s.runUCICommands(host, "firewall", blockRuleApply(section, mac)); err != nil {
  659. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  660. return
  661. }
  662. if err := s.reloadService(host, "firewall"); err != nil {
  663. if rbErr := s.runUCICommands(host, "firewall", blockRuleRollback(section)); rbErr != nil {
  664. log.Printf("[netpulse] block rollback for %s failed: %v", mac, rbErr)
  665. }
  666. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  667. return
  668. }
  669. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  670. }
  671. // handleDeviceBlockDelete desbloquea un dispositivo.
  672. func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request) {
  673. // #2112: uci show + commit + restart del servicio en la unidad antes de responder.
  674. setLongWriteDeadline(w, deviceActionWriteCeiling)
  675. mac := normalizeMAC(r.PathValue("mac"))
  676. if len(mac) != 17 {
  677. writeError(w, http.StatusBadRequest, "invalid_mac")
  678. return
  679. }
  680. var body struct {
  681. RouterID string `json:"router"`
  682. }
  683. if st := readJSONBody(w, r, &body); st != 0 {
  684. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  685. return
  686. }
  687. if body.RouterID == "" {
  688. writeError(w, http.StatusBadRequest, "missing_router")
  689. return
  690. }
  691. host := s.hostOfRouter(body.RouterID)
  692. if host == "" {
  693. writeError(w, http.StatusBadRequest, "no_router")
  694. return
  695. }
  696. lines, err := s.uciShow(host, "firewall")
  697. if err != nil {
  698. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  699. return
  700. }
  701. rules := parseFirewallRules(lines)
  702. br := findBlockRule(rules, mac)
  703. if br == nil {
  704. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  705. return
  706. }
  707. apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
  708. rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
  709. if br.Name != "" {
  710. rollback = append(rollback, uciSetCmd("firewall", br.Section, "name", br.Name))
  711. }
  712. if br.SrcMAC != "" {
  713. rollback = append(rollback, uciSetCmd("firewall", br.Section, "src_mac", br.SrcMAC))
  714. }
  715. if br.Target != "" {
  716. rollback = append(rollback, uciSetCmd("firewall", br.Section, "target", br.Target))
  717. }
  718. if err := s.runUCICommands(host, "firewall", apply); err != nil {
  719. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  720. return
  721. }
  722. if err := s.reloadService(host, "firewall"); err != nil {
  723. if rbErr := s.runUCICommands(host, "firewall", rollback); rbErr != nil {
  724. log.Printf("[netpulse] unblock rollback for %s failed: %v", mac, rbErr)
  725. }
  726. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  727. return
  728. }
  729. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  730. }