integrations.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. // integrations.go — API de integraciones externas de routers (#1674):
  2. // pushers de routers externos (MikroTik RouterOS, Asuswrt) gestionados desde
  3. // la app con el contrato de agente externo. El slug de la integración es el
  4. // id del router external asociado, así el push del pusher (POST
  5. // /api/ingest/agent con Bearer token) se atribuye a la misma unidad.
  6. package httpapi
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "log"
  12. "net/http"
  13. "path/filepath"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/adapters"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  21. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  22. )
  23. // integrationItem es la vista HTTP de una integración (nunca la contraseña).
  24. type integrationItem struct {
  25. Slug string `json:"slug"`
  26. Vendor string `json:"vendor"`
  27. Mode string `json:"mode"`
  28. Host string `json:"host"`
  29. Username string `json:"username"`
  30. Version string `json:"version"`
  31. Arch string `json:"arch"`
  32. IntervalS int `json:"intervalS"`
  33. Enabled bool `json:"enabled"`
  34. State string `json:"state"`
  35. LastError string `json:"lastError"`
  36. // OfflineReason (#1718): código estable del motivo por el que la unidad
  37. // no está empujando (mismos códigos que la tarjeta y el detalle desde
  38. // #1714). Vacío si está empujando, pausada o sin señal clara.
  39. OfflineReason string `json:"offlineReason,omitempty"`
  40. LastStartMs int64 `json:"lastStartMs"`
  41. LastPushMs int64 `json:"lastPushMs"`
  42. Fresh bool `json:"fresh"`
  43. }
  44. // vendorView es la vista HTTP del manifiesto de un vendor.
  45. type vendorView struct {
  46. ID string `json:"id"`
  47. Mode string `json:"mode"`
  48. Arches []string `json:"arches"`
  49. TagPrefix string `json:"tagPrefix"`
  50. Description string `json:"description"`
  51. }
  52. // registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
  53. // exigen rol admin salvo el GET de vendors (solo sesión).
  54. func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
  55. mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
  56. mux.Handle("POST /api/integrations/vendors/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsVendorsRefresh)))
  57. mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
  58. mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
  59. mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
  60. mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
  61. mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
  62. mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
  63. mux.Handle("PUT /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationEdit)))
  64. mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
  65. }
  66. // vendorCatalogRefreshTimeout acota el fetch forzado del endpoint admin.
  67. const vendorCatalogRefreshTimeout = 15 * time.Second
  68. func (s *server) handleIntegrationsVendors(w http.ResponseWriter, r *http.Request) {
  69. vs := s.vendorCatalog.Vendors(r.Context())
  70. writeJSON(w, http.StatusOK, map[string]any{
  71. "vendors": vendorViews(vs),
  72. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  73. })
  74. }
  75. // handleIntegrationsVendorsRefresh fuerza el descubrimiento del catálogo
  76. // (#1697): fetch inmediato, caché actualizada y catálogo devuelto en la
  77. // misma respuesta para que la UI no encadene un segundo GET. Un fallo de
  78. // fetch o de validación deja el catálogo anterior en su sitio (502).
  79. func (s *server) handleIntegrationsVendorsRefresh(w http.ResponseWriter, r *http.Request) {
  80. if s.db == nil || s.vendorCatalog == nil {
  81. writeError(w, http.StatusServiceUnavailable, "unavailable", "vendor catalog is not available without a database")
  82. return
  83. }
  84. ctx, cancel := context.WithTimeout(r.Context(), vendorCatalogRefreshTimeout)
  85. defer cancel()
  86. if err := s.vendorCatalog.Refresh(ctx); err != nil {
  87. writeError(w, http.StatusBadGateway, "refresh_failed", err.Error())
  88. return
  89. }
  90. writeJSON(w, http.StatusOK, map[string]any{
  91. "vendors": vendorViews(s.vendorCatalog.Current()),
  92. "lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
  93. })
  94. }
  95. // vendorViews es la vista HTTP del catálogo: mismos campos que servía el
  96. // manifiesto estático para no romper el contrato con la UI.
  97. func vendorViews(vs []rintegration.Vendor) []vendorView {
  98. out := make([]vendorView, 0, len(vs))
  99. for _, v := range vs {
  100. out = append(out, vendorView{
  101. ID: v.ID, Mode: v.Mode, Arches: v.Arches,
  102. TagPrefix: v.TagPrefix, Description: v.Description,
  103. })
  104. }
  105. return out
  106. }
  107. func (s *server) integrationsStore() *rintegration.Store {
  108. return rintegration.NewStore(s.db.DB)
  109. }
  110. func (s *server) integrationFetcher() *rintegration.Fetcher {
  111. if s.integrations != nil {
  112. return s.integrations.Fetch()
  113. }
  114. return rintegration.NewFetcher()
  115. }
  116. func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
  117. if s.db == nil {
  118. return rintegration.Row{}, false
  119. }
  120. return s.integrationsStore().Get(slug)
  121. }
  122. // integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
  123. // devuelve en milisegundos, 0 si nunca empujó.
  124. func (s *server) integrationLastPushMs(slug string) int64 {
  125. if s.db == nil {
  126. return 0
  127. }
  128. sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
  129. if err != nil {
  130. return 0
  131. }
  132. return sec * 1000
  133. }
  134. func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
  135. lastPush := s.integrationLastPushMs(row.Slug)
  136. fresh := false
  137. if lastPush > 0 && row.IntervalS > 0 {
  138. fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
  139. }
  140. // #1696: reconciliar al leer. Una fila en running cuyo último push es más
  141. // viejo que 3 intervalos no puede ir de sana: la vista la reporta como
  142. // "stale". Es solo vista (la fila no se toca): en cuanto el pusher vuelva
  143. // a empujar, el propio cálculo la devuelve a "running".
  144. state := row.State
  145. if state == "running" && lastPush > 0 && row.IntervalS > 0 && !fresh {
  146. state = "stale"
  147. }
  148. return integrationItem{
  149. Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
  150. Username: row.Username, Version: row.Version, Arch: row.Arch,
  151. IntervalS: row.IntervalS, Enabled: row.Enabled, State: state,
  152. LastError: row.LastError, LastStartMs: row.LastStartMs,
  153. LastPushMs: lastPush, Fresh: fresh,
  154. OfflineReason: s.integrationOfflineReason(row, fresh),
  155. }
  156. }
  157. // integrationOfflineReason (#1718) clasifica por qué una integración no está
  158. // empujando, con los mismos códigos y la misma precedencia que StatusReasons
  159. // en el paquete rintegration (que alimenta la tarjeta y el detalle): parada
  160. // explícita, último error de instalación, o el log del pusher para fallos de
  161. // poll. Pausada o fresca no tienen motivo.
  162. func (s *server) integrationOfflineReason(row rintegration.Row, fresh bool) string {
  163. if !row.Enabled {
  164. return ""
  165. }
  166. if row.State == "stopped" {
  167. return rintegration.ReasonStopped
  168. }
  169. if fresh {
  170. return ""
  171. }
  172. code := ""
  173. if row.State == "error" && row.LastError != "" {
  174. code = rintegration.ClassifyPollError(row.LastError)
  175. }
  176. if (code == "" || code == rintegration.ReasonError) && s.integrations != nil {
  177. if msg := s.integrations.LastPollError(row.Slug); msg != "" {
  178. code = rintegration.ClassifyPollError(msg)
  179. }
  180. }
  181. return code
  182. }
  183. func (s *server) integrationList() []integrationItem {
  184. if s.db == nil {
  185. return []integrationItem{}
  186. }
  187. rows, err := s.integrationsStore().List()
  188. if err != nil {
  189. return []integrationItem{}
  190. }
  191. out := make([]integrationItem, 0, len(rows))
  192. for _, row := range rows {
  193. out = append(out, s.integrationItemOf(row))
  194. }
  195. return out
  196. }
  197. func (s *server) broadcastIntegrations() {
  198. if s.hub != nil {
  199. s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
  200. }
  201. }
  202. // watchIntegrations (#1696) registra el callback de salida inesperada de los
  203. // pushers locales (#1674) y reanuda al arrancar las integraciones habilitadas.
  204. // No-op sin supervisor o sin base de datos (demo). Los paros intencionales no
  205. // pasan por el callback: los gestiona el handler de stop.
  206. func (s *server) watchIntegrations() {
  207. if s.integrations == nil || s.db == nil {
  208. return
  209. }
  210. s.integrations.SetOnExit(func(slug string, exitErr error) {
  211. // Un pusher es un daemon de larga vida: también la salida limpia
  212. // (código 0) es inesperada y deja la fila en estado error con su
  213. // motivo, igual que un arranque fallido.
  214. reason := "pusher exited unexpectedly (exit code 0)"
  215. if exitErr != nil {
  216. reason = exitErr.Error()
  217. }
  218. _ = rintegration.NewStore(s.db.DB).SetState(slug, "error", reason)
  219. s.broadcastIntegrations()
  220. })
  221. s.resumeIntegrations()
  222. }
  223. // resumeIntegrations (#1696) reanuda al arrancar cada integración habilitada.
  224. // En modo local arranca el pusher con el binario ya instalado y el fichero de
  225. // entorno 0600 ya existente (el token y la contraseña solo viven ahí); en
  226. // modo ssh el pusher corre dentro del router y no hay nada que arrancar en el
  227. // servidor, pero el estado guardado deja de decir running (no verificado
  228. // hasta el próximo check/start). Un fallo se loga y deja la fila en estado
  229. // error: nunca tira el arranque del servidor.
  230. func (s *server) resumeIntegrations() {
  231. if s.integrations == nil || s.db == nil {
  232. return
  233. }
  234. store := s.integrationsStore()
  235. rows, err := store.List()
  236. if err != nil {
  237. log.Printf("[netpulse] aviso: integraciones: no se pudo leer la tabla al arrancar (%v)", err)
  238. return
  239. }
  240. for _, row := range rows {
  241. if !row.Enabled {
  242. continue
  243. }
  244. if row.Mode != "local" {
  245. // El proceso vive en el router: sin verificar tras el reinicio
  246. // del servidor; check/start lo reconcilian.
  247. if row.State == "running" {
  248. _ = store.SetState(row.Slug, "unverified", "")
  249. }
  250. continue
  251. }
  252. if s.integrations.Running(row.Slug) {
  253. continue
  254. }
  255. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  256. if !ok {
  257. _ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
  258. log.Printf("[netpulse] aviso: integración %s con vendor desconocido %q al arrancar", row.Slug, row.Vendor)
  259. continue
  260. }
  261. binPath := filepath.Join(s.integrations.Dir(), row.Slug, vendor.Binary)
  262. if err := s.integrations.Start(row.Slug, nil, binPath); err != nil {
  263. _ = store.SetState(row.Slug, "error", err.Error())
  264. log.Printf("[netpulse] aviso: integración %s no se reanudó al arrancar (%v)", row.Slug, err)
  265. continue
  266. }
  267. _ = store.SetState(row.Slug, "running", "")
  268. _ = store.SetLastStart(row.Slug, time.Now().UnixMilli())
  269. log.Printf("[netpulse] integración %s reanudada al arrancar", row.Slug)
  270. }
  271. s.broadcastIntegrations()
  272. }
  273. // unmanagedItem es un pusher externo que alimenta la flota sin fila en
  274. // router_integrations: se instaló a mano, antes de que la app supiera
  275. // instalarlos (#1743). Solo se describe; la app no puede arrancarlo, pararlo
  276. // ni rotarle el token.
  277. type unmanagedItem struct {
  278. Slug string `json:"slug"`
  279. Kind string `json:"kind"`
  280. Version string `json:"version,omitempty"`
  281. IntervalS int `json:"intervalS,omitempty"`
  282. LastPushMs int64 `json:"lastPushMs"`
  283. Fresh bool `json:"fresh"`
  284. }
  285. // unmanagedIntegrations lista los pushers externos vivos que la app no
  286. // gestiona (#1743). Sin esto la página de Integraciones sale vacía mientras
  287. // /api/agents muestra unidades alimentadas por ellos, y el operador no tiene
  288. // ni una pista de que el pusher existe.
  289. //
  290. // El kind solo vive en memoria (AgentRegistry), así que justo después de un
  291. // reinicio la lista queda vacía hasta el primer push de cada unidad (~30 s).
  292. func (s *server) unmanagedIntegrations() []unmanagedItem {
  293. out := []unmanagedItem{}
  294. if s.db == nil || s.agents == nil {
  295. return out
  296. }
  297. // Los slugs viven en kv como agent.token.<slug>. El cursor se cierra ANTES
  298. // de consultar la tienda de integraciones: con SetMaxOpenConns(1), un
  299. // QueryRow con las filas abiertas espera la única conexión y bloquea.
  300. slugs := []string{}
  301. rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
  302. if err != nil {
  303. return out
  304. }
  305. for rows.Next() {
  306. var key string
  307. if rows.Scan(&key) == nil {
  308. slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
  309. }
  310. }
  311. rows.Close()
  312. if err := rows.Err(); err != nil {
  313. return out
  314. }
  315. store := s.integrationsStore()
  316. for _, slug := range slugs {
  317. if slug == "" {
  318. continue
  319. }
  320. _, version, kind, interval, ok := s.agents.Info(slug)
  321. if !ok || kind != "external" {
  322. continue
  323. }
  324. if _, managed := store.Get(slug); managed {
  325. continue
  326. }
  327. lastPush := s.integrationLastPushMs(slug)
  328. fresh := lastPush > 0 && interval > 0 && time.Now().UnixMilli()-lastPush <= int64(interval)*3*1000
  329. out = append(out, unmanagedItem{
  330. Slug: slug,
  331. Kind: kind,
  332. Version: version,
  333. IntervalS: interval,
  334. LastPushMs: lastPush,
  335. Fresh: fresh,
  336. })
  337. }
  338. return out
  339. }
  340. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  341. writeJSON(w, http.StatusOK, map[string]any{
  342. "integrations": s.integrationList(),
  343. "unmanaged": s.unmanagedIntegrations(),
  344. })
  345. }
  346. type integrationCreateBody struct {
  347. Slug string `json:"slug"`
  348. Vendor string `json:"vendor"`
  349. Host string `json:"host"`
  350. Username string `json:"username"`
  351. Password string `json:"password"`
  352. IntervalS int `json:"intervalS"`
  353. Arch string `json:"arch"`
  354. }
  355. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  356. if s.db == nil {
  357. writeError(w, http.StatusInternalServerError, "db_error")
  358. return
  359. }
  360. var body integrationCreateBody
  361. if st := readJSONBody(w, r, &body); st != 0 {
  362. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  363. return
  364. }
  365. if !agentSlugRe.MatchString(body.Slug) {
  366. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  367. return
  368. }
  369. vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
  370. if !ok {
  371. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  372. return
  373. }
  374. if body.Host == "" || body.Username == "" || body.Password == "" {
  375. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  376. return
  377. }
  378. if body.IntervalS < 10 || body.IntervalS > 86400 {
  379. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  380. return
  381. }
  382. arch := body.Arch
  383. if arch == "" {
  384. arch = vendor.Arches[0]
  385. } else if !vendorSupportsArch(vendor, arch) {
  386. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  387. return
  388. }
  389. store := s.integrationsStore()
  390. if _, exists := store.Get(body.Slug); exists {
  391. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  392. return
  393. }
  394. // El env que se va a escribir tiene que poder arrancar: con la URL en https
  395. // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
  396. // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
  397. // sin tocar nada, que un alta que muere al segundo siguiente.
  398. serverURL := s.agentBaseURL(r)
  399. if err := requirePusherPin(serverURL); err != nil {
  400. writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
  401. return
  402. }
  403. // Resolver y descargar el último release verificado. En modo local se
  404. // extrae el binario aquí (corre en este host); en modo ssh solo se
  405. // verifica: el router descarga el asset él mismo.
  406. fetch := s.integrationFetcher()
  407. res, err := fetch.ResolveLatest(vendor, arch)
  408. if err != nil {
  409. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  410. return
  411. }
  412. binPath := ""
  413. if vendor.Mode == "local" {
  414. if s.integrations == nil {
  415. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  416. return
  417. }
  418. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  419. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  420. if err != nil {
  421. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  422. return
  423. }
  424. } else {
  425. if s.pool == nil {
  426. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  427. return
  428. }
  429. if err := fetch.Verify(res); err != nil {
  430. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  431. return
  432. }
  433. }
  434. now := time.Now().UnixMilli()
  435. row := rintegration.Row{
  436. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  437. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  438. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  439. CreatedAt: now, UpdatedAt: now,
  440. }
  441. if err := store.Upsert(row); err != nil {
  442. writeError(w, http.StatusInternalServerError, "db_error")
  443. return
  444. }
  445. // #1708: en modo ssh la misma contraseña del formulario es la credencial
  446. // SSH del alta y de las acciones posteriores: se guarda en el fichero
  447. // compañero (0600) antes de conectar, nunca en la base de datos.
  448. if vendor.Mode == "ssh" && s.integrations != nil {
  449. if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
  450. _ = store.Delete(body.Slug)
  451. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  452. return
  453. }
  454. }
  455. // Router external cuyo id es el slug (push autenticado por token de
  456. // agente, agent.token.<slug>).
  457. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  458. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  459. })
  460. if err != nil || router.ID != body.Slug {
  461. _ = store.Delete(body.Slug)
  462. writeError(w, http.StatusInternalServerError, "router_error")
  463. return
  464. }
  465. s.syncRouters()
  466. rollback := func() {
  467. if vendor.Mode == "local" && s.integrations != nil {
  468. _ = s.integrations.Stop(body.Slug)
  469. _ = s.integrations.Cleanup(body.Slug)
  470. }
  471. if vendor.Mode == "ssh" && s.integrations != nil {
  472. _ = s.integrations.RemoveSSHPassword(body.Slug)
  473. }
  474. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  475. s.syncRouters()
  476. _ = store.Delete(body.Slug)
  477. }
  478. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  479. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  480. if vendor.Mode == "local" {
  481. return s.integrations.Start(body.Slug, env, binPath)
  482. }
  483. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  484. })
  485. if err != nil {
  486. rollback()
  487. writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
  488. return
  489. }
  490. _ = store.SetState(body.Slug, "running", "")
  491. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  492. s.broadcastIntegrations()
  493. item, _ := s.getIntegrationRow(body.Slug)
  494. writeJSON(w, http.StatusCreated, map[string]any{
  495. "integration": s.integrationItemOf(item),
  496. "token": token,
  497. })
  498. }
  499. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  500. for _, a := range v.Arches {
  501. if a == arch {
  502. return true
  503. }
  504. }
  505. return false
  506. }
  507. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  508. // propio router, así que el host del dispositivo es la propia unidad
  509. // (127.0.0.1) en lugar del host SSH de la tabla.
  510. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  511. prefix := strings.ToUpper(v.ID) + "_"
  512. host := row.Host
  513. if v.Mode == "ssh" {
  514. host = "127.0.0.1"
  515. }
  516. env := map[string]string{
  517. prefix + "HOST": host,
  518. prefix + "USER": row.Username,
  519. prefix + "PASS": password,
  520. prefix + "INSECURE": "1",
  521. "NETPULSE_SERVER": serverURL,
  522. "NETPULSE_TOKEN": token,
  523. "NETPULSE_SLUG": row.Slug,
  524. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  525. }
  526. for k, v := range pusherPinEnv(serverURL) {
  527. env[k] = v
  528. }
  529. return env
  530. }
  531. // healPusherPin merges the current server pin into a pusher environment,
  532. // healing files written before the pin requirement and refreshing the pin
  533. // after a certificate reissue. It is a no-op when the server URL needs no
  534. // pin (plain HTTP).
  535. func healPusherPin(env map[string]string, serverURL string) map[string]string {
  536. for k, v := range pusherPinEnv(serverURL) {
  537. env[k] = v
  538. }
  539. return env
  540. }
  541. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  542. _, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  543. return err
  544. }
  545. // sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
  546. // contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
  547. // solo implementan Run no, y en ese caso el pool queda como esté.
  548. type sshPasswordSetter interface {
  549. SetPassword(host, user, password string)
  550. }
  551. // applyIntegrationSSHAuth aplica al pool la credencial SSH de la
  552. // integración (#1708): si existe el fichero compañero <slug>.sshpass la
  553. // conexión va por contraseña con el usuario de la fila (gana sobre la llave
  554. // del servidor); si no, la credencial se limpia y el dial usa la llave como
  555. // siempre. Un fichero ilegible cae a llave con aviso en el log.
  556. func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
  557. if s.pool == nil || s.integrations == nil {
  558. return
  559. }
  560. setter, ok := s.pool.(sshPasswordSetter)
  561. if !ok {
  562. return
  563. }
  564. pass, err := s.integrations.ReadSSHPassword(row.Slug)
  565. if err != nil {
  566. log.Printf("[netpulse] aviso: integración %s: no se pudo leer el fichero de contraseña SSH (%v); conecto con llave", row.Slug, err)
  567. pass = ""
  568. }
  569. setter.SetPassword(row.Host, row.Username, pass)
  570. }
  571. // runIntegrationSSH ejecuta un comando en el router de la integración
  572. // aplicando antes la credencial SSH del fichero compañero (#1708).
  573. func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
  574. s.applyIntegrationSSHAuth(row)
  575. return s.pool.Run(row.Host, cmd, timeout)
  576. }
  577. // sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
  578. // autenticación es su propio código (ssh_auth_failed) frente al fallo
  579. // genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
  580. // la contraseña.
  581. func sshErrorCode(err error) string {
  582. var ae *adapters.SSHAuthError
  583. if errors.As(err, &ae) {
  584. return "ssh_auth_failed"
  585. }
  586. return "ssh_failed"
  587. }
  588. // sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
  589. // autenticación SSH y fallback para cualquier otro error.
  590. func sshErrorOr(err error, fallback string) string {
  591. if sshErrorCode(err) == "ssh_auth_failed" {
  592. return "ssh_auth_failed"
  593. }
  594. return fallback
  595. }
  596. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  597. slug := r.PathValue("slug")
  598. row, ok := s.getIntegrationRow(slug)
  599. if !ok {
  600. writeError(w, http.StatusNotFound, "not_found")
  601. return
  602. }
  603. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  604. if !ok {
  605. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  606. return
  607. }
  608. store := s.integrationsStore()
  609. if vendor.Mode == "local" {
  610. if s.integrations == nil {
  611. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  612. return
  613. }
  614. if !s.integrations.Running(slug) {
  615. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  616. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  617. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  618. return
  619. }
  620. }
  621. } else {
  622. if s.pool == nil {
  623. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  624. return
  625. }
  626. if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  627. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  628. return
  629. }
  630. }
  631. _ = store.SetState(slug, "running", "")
  632. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  633. s.broadcastIntegrations()
  634. item, _ := s.getIntegrationRow(slug)
  635. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  636. }
  637. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  638. slug := r.PathValue("slug")
  639. row, ok := s.getIntegrationRow(slug)
  640. if !ok {
  641. writeError(w, http.StatusNotFound, "not_found")
  642. return
  643. }
  644. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  645. if !ok {
  646. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  647. return
  648. }
  649. if vendor.Mode == "local" {
  650. if s.integrations != nil {
  651. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  652. }
  653. } else if s.pool != nil {
  654. _, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
  655. }
  656. _ = s.integrationsStore().SetState(slug, "stopped", "")
  657. s.broadcastIntegrations()
  658. item, _ := s.getIntegrationRow(slug)
  659. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  660. }
  661. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  662. slug := r.PathValue("slug")
  663. row, ok := s.getIntegrationRow(slug)
  664. if !ok {
  665. writeError(w, http.StatusNotFound, "not_found")
  666. return
  667. }
  668. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  669. if !ok {
  670. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  671. return
  672. }
  673. running := false
  674. if vendor.Mode == "local" {
  675. running = s.integrations != nil && s.integrations.Running(slug)
  676. } else if s.pool != nil {
  677. _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
  678. running = err == nil
  679. }
  680. // #1696: un check verificado reconcilia el estado guardado: el unverified
  681. // que deja un reinicio del servidor (o una fila desfasada) vuelve a
  682. // running cuando el proceso está demostradamente vivo.
  683. if running && row.State != "running" {
  684. _ = s.integrationsStore().SetState(slug, "running", "")
  685. s.broadcastIntegrations()
  686. if fresh, ok := s.getIntegrationRow(slug); ok {
  687. row = fresh
  688. }
  689. }
  690. writeJSON(w, http.StatusOK, map[string]any{
  691. "integration": s.integrationItemOf(row),
  692. "running": running,
  693. })
  694. }
  695. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  696. slug := r.PathValue("slug")
  697. row, ok := s.getIntegrationRow(slug)
  698. if !ok {
  699. writeError(w, http.StatusNotFound, "not_found")
  700. return
  701. }
  702. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  703. if !ok {
  704. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  705. return
  706. }
  707. fetch := s.integrationFetcher()
  708. res, err := fetch.ResolveLatest(vendor, row.Arch)
  709. if err != nil {
  710. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  711. return
  712. }
  713. store := s.integrationsStore()
  714. if vendor.Mode == "local" {
  715. if s.integrations == nil {
  716. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  717. return
  718. }
  719. _ = s.integrations.Stop(slug)
  720. installDir := filepath.Join(s.integrations.Dir(), slug)
  721. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  722. _ = store.SetState(slug, "error", err.Error())
  723. s.broadcastIntegrations()
  724. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  725. return
  726. }
  727. // Heal environments created before the pin requirement: the
  728. // refreshed binary refuses to start without it. Best effort, on
  729. // error the old file is reused and the start below reports it.
  730. if env, err := s.integrations.Env(slug); err == nil {
  731. _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
  732. }
  733. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  734. _ = store.SetState(slug, "error", err.Error())
  735. s.broadcastIntegrations()
  736. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  737. return
  738. }
  739. } else {
  740. if s.pool == nil {
  741. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  742. return
  743. }
  744. if err := fetch.Verify(res); err != nil {
  745. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  746. return
  747. }
  748. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  749. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  750. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  751. return
  752. }
  753. }
  754. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  755. _ = store.SetState(slug, "running", "")
  756. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  757. s.broadcastIntegrations()
  758. item, _ := s.getIntegrationRow(slug)
  759. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  760. }
  761. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  762. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  763. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  764. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  765. func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
  766. slug := r.PathValue("slug")
  767. row, ok := s.getIntegrationRow(slug)
  768. if !ok {
  769. writeError(w, http.StatusNotFound, "not_found")
  770. return
  771. }
  772. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  773. if !ok {
  774. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  775. return
  776. }
  777. var body struct {
  778. Host *string `json:"host"`
  779. Username *string `json:"username"`
  780. Password *string `json:"password"`
  781. IntervalS *int `json:"intervalS"`
  782. }
  783. if st := readJSONBody(w, r, &body); st != 0 {
  784. writeBodyError(w, st, "invalid_body", "")
  785. return
  786. }
  787. changed := false
  788. if body.Host != nil {
  789. h := strings.TrimSpace(*body.Host)
  790. if h == "" {
  791. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  792. return
  793. }
  794. row.Host = h
  795. changed = true
  796. }
  797. if body.Username != nil {
  798. u := strings.TrimSpace(*body.Username)
  799. if u == "" {
  800. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  801. return
  802. }
  803. row.Username = u
  804. changed = true
  805. }
  806. if body.IntervalS != nil {
  807. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  808. writeError(w, http.StatusBadRequest, "invalid_interval")
  809. return
  810. }
  811. row.IntervalS = *body.IntervalS
  812. changed = true
  813. }
  814. password := ""
  815. if body.Password != nil {
  816. password = *body.Password
  817. changed = true
  818. }
  819. if !changed {
  820. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  821. return
  822. }
  823. prefix := strings.ToUpper(vendor.ID) + "_"
  824. host := row.Host
  825. if vendor.Mode == "ssh" {
  826. host = "127.0.0.1"
  827. }
  828. store := s.integrationsStore()
  829. if vendor.Mode == "local" {
  830. if s.integrations == nil {
  831. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  832. return
  833. }
  834. env, err := s.integrations.Env(slug)
  835. if err != nil {
  836. _ = store.SetState(slug, "error", err.Error())
  837. s.broadcastIntegrations()
  838. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  839. return
  840. }
  841. env[prefix+"HOST"] = host
  842. env[prefix+"USER"] = row.Username
  843. if password != "" {
  844. env[prefix+"PASS"] = password
  845. }
  846. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  847. healPusherPin(env, s.agentBaseURL(r))
  848. if err := s.integrations.WriteEnv(slug, env); err != nil {
  849. _ = store.SetState(slug, "error", err.Error())
  850. s.broadcastIntegrations()
  851. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  852. return
  853. }
  854. _ = s.integrations.Stop(slug)
  855. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  856. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  857. _ = store.SetState(slug, "error", err.Error())
  858. s.broadcastIntegrations()
  859. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  860. return
  861. }
  862. } else {
  863. if s.pool == nil {
  864. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  865. return
  866. }
  867. // #1708: la contraseña nueva del formulario es también la credencial
  868. // SSH: guardarla en el fichero compañero ANTES de conectar, porque si
  869. // el usuario ya cambió la contraseña en el router, la conexión de
  870. // este mismo guardado necesita la nueva.
  871. if password != "" && s.integrations != nil {
  872. if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
  873. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  874. return
  875. }
  876. }
  877. raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
  878. if err != nil {
  879. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  880. return
  881. }
  882. env := rintegration.ParseEnv(raw)
  883. env[prefix+"HOST"] = host
  884. env[prefix+"USER"] = row.Username
  885. if password != "" {
  886. env[prefix+"PASS"] = password
  887. }
  888. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  889. healPusherPin(env, s.agentBaseURL(r))
  890. if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  891. _ = store.SetState(slug, "error", err.Error())
  892. s.broadcastIntegrations()
  893. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  894. return
  895. }
  896. }
  897. if err := store.Upsert(row); err != nil {
  898. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  899. return
  900. }
  901. _ = store.SetState(slug, "running", "")
  902. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  903. s.broadcastIntegrations()
  904. item, _ := s.getIntegrationRow(slug)
  905. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  906. }
  907. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  908. slug := r.PathValue("slug")
  909. row, ok := s.getIntegrationRow(slug)
  910. if !ok {
  911. writeError(w, http.StatusNotFound, "not_found")
  912. return
  913. }
  914. vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
  915. if vendor.Mode == "local" {
  916. if s.integrations != nil {
  917. _ = s.integrations.Stop(slug)
  918. _ = s.integrations.Cleanup(slug)
  919. }
  920. } else if s.pool != nil {
  921. _, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
  922. }
  923. // #1708: la contraseña SSH del fichero compañero muere con la
  924. // integración y el pool pierde la credencial (la conexión cacheada se
  925. // tira y el siguiente dial vuelve a la llave).
  926. if s.integrations != nil {
  927. _ = s.integrations.RemoveSSHPassword(slug)
  928. }
  929. if setter, ok := s.pool.(sshPasswordSetter); ok {
  930. setter.SetPassword(row.Host, "", "")
  931. }
  932. _ = s.integrationsStore().Delete(slug)
  933. _ = routerstore.RemoveRouter(s.db.DB, slug)
  934. s.syncRouters()
  935. if s.db != nil {
  936. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  937. }
  938. s.broadcastIntegrations()
  939. w.WriteHeader(http.StatusNoContent)
  940. }
  941. // ---------------------------------------------------------------------------
  942. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  943. // ---------------------------------------------------------------------------
  944. // envFileBody renders the sorted KEY=value body of an env file, with values
  945. // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
  946. func envFileBody(env map[string]string) string {
  947. keys := make([]string, 0, len(env))
  948. for k := range env {
  949. keys = append(keys, k)
  950. }
  951. sort.Strings(keys)
  952. var b strings.Builder
  953. for _, k := range keys {
  954. b.WriteString(k)
  955. b.WriteString("=")
  956. b.WriteString(rintegration.EscapeEnvValue(env[k]))
  957. b.WriteString("\n")
  958. }
  959. return b.String()
  960. }
  961. // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
  962. // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
  963. // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
  964. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  965. if v.InitSystem() == "merlin" {
  966. return sshMerlinInstallScript(v, env, assetURL, sha256)
  967. }
  968. return sshProcdInstallScript(v, env, assetURL, sha256)
  969. }
  970. // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
  971. // /usr/sbin, init procd en /etc/init.d y env en /etc.
  972. func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  973. bin := "/usr/sbin/" + v.Binary
  974. init := "/etc/init.d/" + v.Binary
  975. envFile := "/etc/" + v.Binary + ".env"
  976. envBlock := envFileBody(env)
  977. return `#!/bin/sh
  978. set -e
  979. BIN="` + bin + `"
  980. INIT="` + init + `"
  981. ENV_FILE="` + envFile + `"
  982. SERVER="` + env["NETPULSE_SERVER"] + `"
  983. ASSET_URL="` + assetURL + `"
  984. SHA256="` + sha256 + `"
  985. # Preflight: el router debe alcanzar el server.
  986. if command -v curl >/dev/null 2>&1; then
  987. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  988. else
  989. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  990. fi
  991. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  992. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  993. # Descargar el asset desde la URL ya verificada en el server.
  994. if command -v curl >/dev/null 2>&1; then
  995. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  996. else
  997. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  998. fi
  999. # Verificar sha256 antes de instalar.
  1000. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1001. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1002. # Extraer y mover de forma atómica (.new -> rename).
  1003. mkdir -p /tmp/` + v.Binary + `.extract
  1004. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1005. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1006. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1007. cp "$SRC" "$BIN.new"
  1008. chmod 0755 "$BIN.new"
  1009. mv -f "$BIN.new" "$BIN"
  1010. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1011. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  1012. # fichero existente (la contraseña y el token solo viven ahí).
  1013. if [ ! -f "$ENV_FILE" ]; then
  1014. cat > "$ENV_FILE" <<'ENVEOF'
  1015. ` + envBlock + `ENVEOF
  1016. chmod 600 "$ENV_FILE"
  1017. fi
  1018. # Init procd.
  1019. cat > "$INIT" <<'INITEOF'
  1020. #!/bin/sh /etc/rc.common
  1021. START=99
  1022. STOP=10
  1023. USE_PROCD=1
  1024. BIN="/usr/sbin/` + v.Binary + `"
  1025. ENV_FILE="/etc/` + v.Binary + `.env"
  1026. start_service() {
  1027. [ -x "$BIN" ] || return 1
  1028. [ -r "$ENV_FILE" ] || { echo "netpulse: missing or unreadable env file $ENV_FILE" >&2; return 1; }
  1029. # Cargar el fichero de entorno y pasarlo entero al proceso en UNA sola
  1030. # llamada env (#1709): cada llamada adicional pisaria a la anterior y al
  1031. # proceso solo le llegaria la ultima variable (OpenWrt 21.02, #1701).
  1032. # Los valores van escapados (salto de linea = \n): printf %b los
  1033. # desescapa igual que ParseEnv en el server y que el control script de
  1034. # Merlin (#1705), sin pasar por . "$ENV_FILE" ni /etc/profile.
  1035. set --
  1036. while IFS= read -r line || [ -n "$line" ]; do
  1037. case "$line" in ""|\#*) continue ;; esac
  1038. k=${line%%=*}
  1039. val=${line#*=}
  1040. val=$(printf '%b' "$val")
  1041. set -- "$@" "$k=$val"
  1042. done < "$ENV_FILE"
  1043. procd_open_instance ` + v.Binary + `
  1044. procd_set_param env "$@"
  1045. procd_set_param command "$BIN"
  1046. procd_set_param respawn 3600 5 5
  1047. procd_set_param stdout 1
  1048. procd_set_param stderr 1
  1049. # Vigila el fichero: un cambio sigue reiniciando el servicio y el
  1050. # arranque vuelve a leer el env, asi que el proceso recoge los valores
  1051. # nuevos.
  1052. procd_set_param file "$ENV_FILE"
  1053. procd_close_instance
  1054. }
  1055. INITEOF
  1056. chmod 0755 "$INIT"
  1057. "$INIT" enable
  1058. "$INIT" restart
  1059. `
  1060. }
  1061. // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
  1062. // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
  1063. // control con pidfile y log) y un bloque gestionado en
  1064. // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
  1065. // idempotente: el env solo se escribe si falta y el bloque solo se añade una
  1066. // vez; el resto del hook no se toca.
  1067. func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  1068. dir := "/jffs/netpulse"
  1069. bin := dir + "/" + v.Binary
  1070. ctrl := bin + ".sh"
  1071. envFile := bin + ".env"
  1072. pidFile := bin + ".pid"
  1073. logFile := bin + ".log"
  1074. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1075. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1076. return `#!/bin/sh
  1077. set -e
  1078. BIN="` + bin + `"
  1079. CTRL="` + ctrl + `"
  1080. ENV_FILE="` + envFile + `"
  1081. PID_FILE="` + pidFile + `"
  1082. LOG_FILE="` + logFile + `"
  1083. HOOK="/jffs/scripts/services-start"
  1084. SERVER="` + env["NETPULSE_SERVER"] + `"
  1085. ASSET_URL="` + assetURL + `"
  1086. SHA256="` + sha256 + `"
  1087. # Preflight: el router debe alcanzar el server.
  1088. if command -v curl >/dev/null 2>&1; then
  1089. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1090. else
  1091. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1092. fi
  1093. # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
  1094. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1095. # Descargar el asset desde la URL ya verificada en el server.
  1096. if command -v curl >/dev/null 2>&1; then
  1097. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1098. else
  1099. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1100. fi
  1101. # Verificar sha256 antes de instalar.
  1102. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1103. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1104. # Extraer y mover de forma atómica (.new -> rename).
  1105. mkdir -p /tmp/` + v.Binary + `.extract
  1106. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1107. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1108. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1109. mkdir -p "$DIR"
  1110. cp "$SRC" "$BIN.new"
  1111. chmod 0755 "$BIN.new"
  1112. mv -f "$BIN.new" "$BIN"
  1113. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1114. # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
  1115. # el fichero (la contraseña y el token solo viven ahí).
  1116. if [ ! -f "$ENV_FILE" ]; then
  1117. cat > "$ENV_FILE" <<'ENVEOF'
  1118. ` + envFileBody(env) + `ENVEOF
  1119. chmod 600 "$ENV_FILE"
  1120. fi
  1121. # Script de control con pidfile (start|stop|restart|check). El env guarda
  1122. # los valores escapados (salto de línea = \n): printf %b los desescapa igual
  1123. # que ParseEnv en el server antes de exportarlos al pusher.
  1124. cat > "$CTRL" <<'CTRLEOF'
  1125. #!/bin/sh
  1126. # NetPulse pusher control script (Asuswrt-Merlin).
  1127. BIN="` + bin + `"
  1128. PID_FILE="` + pidFile + `"
  1129. ENV_FILE="` + envFile + `"
  1130. LOG_FILE="` + logFile + `"
  1131. running() {
  1132. [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
  1133. }
  1134. case "$1" in
  1135. start)
  1136. [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
  1137. if running; then
  1138. exit 0
  1139. fi
  1140. rm -f "$PID_FILE"
  1141. [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
  1142. while IFS= read -r line || [ -n "$line" ]; do
  1143. case "$line" in ""|\#*) continue ;; esac
  1144. k=${line%%=*}
  1145. val=${line#*=}
  1146. val=$(printf '%b' "$val")
  1147. export "$k=$val"
  1148. done < "$ENV_FILE"
  1149. nohup "$BIN" >> "$LOG_FILE" 2>&1 &
  1150. echo $! > "$PID_FILE"
  1151. ;;
  1152. stop)
  1153. if [ -f "$PID_FILE" ]; then
  1154. RUN_PID=$(cat "$PID_FILE")
  1155. kill "$RUN_PID" 2>/dev/null || true
  1156. n=0
  1157. while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
  1158. sleep 1
  1159. n=$((n+1))
  1160. done
  1161. if kill -0 "$RUN_PID" 2>/dev/null; then
  1162. kill -9 "$RUN_PID" 2>/dev/null || true
  1163. fi
  1164. rm -f "$PID_FILE"
  1165. fi
  1166. ;;
  1167. restart)
  1168. "$0" stop
  1169. "$0" start
  1170. ;;
  1171. check)
  1172. if running; then
  1173. exit 0
  1174. fi
  1175. exit 1
  1176. ;;
  1177. *)
  1178. echo "usage: $0 {start|stop|restart|check}"
  1179. exit 2
  1180. ;;
  1181. esac
  1182. CTRLEOF
  1183. chmod 0755 "$CTRL"
  1184. # Arranque al boot: bloque gestionado en services-start, delimitado por
  1185. # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
  1186. mkdir -p /jffs/scripts
  1187. if [ ! -f "$HOOK" ]; then
  1188. printf '#!/bin/sh\n' > "$HOOK"
  1189. fi
  1190. chmod 0755 "$HOOK"
  1191. if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
  1192. cat >> "$HOOK" <<'BLOKEOF'
  1193. ` + blockStart + `
  1194. ` + ctrl + ` start
  1195. ` + blockEnd + `
  1196. BLOKEOF
  1197. fi
  1198. "$CTRL" start
  1199. `
  1200. }
  1201. // sshEnvReadScript prints the environment file of an integration running
  1202. // inside the router, so the server can merge changes without ever storing the
  1203. // token or the password. Merlin vendors keep the env under /jffs/netpulse.
  1204. func sshEnvReadScript(v rintegration.Vendor) string {
  1205. if v.InitSystem() == "merlin" {
  1206. return "cat /jffs/netpulse/" + v.Binary + ".env"
  1207. }
  1208. return "cat /etc/" + v.Binary + ".env"
  1209. }
  1210. // sshEnvWriteScript replaces the environment file inside the router and
  1211. // restarts the service. Values come already escaped by EscapeEnvValue and the
  1212. // heredoc is quoted, so the shell does not expand anything.
  1213. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  1214. envBlock := envFileBody(env)
  1215. if v.InitSystem() == "merlin" {
  1216. envFile := "/jffs/netpulse/" + v.Binary + ".env"
  1217. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1218. return `#!/bin/sh
  1219. set -e
  1220. ENV_FILE="` + envFile + `"
  1221. CTRL="` + ctrl + `"
  1222. cat > "$ENV_FILE.new" <<'ENVEOF'
  1223. ` + envBlock + `ENVEOF
  1224. chmod 600 "$ENV_FILE.new"
  1225. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1226. if [ -x "$CTRL" ]; then
  1227. "$CTRL" restart >/dev/null 2>&1 || true
  1228. fi
  1229. `
  1230. }
  1231. init := "/etc/init.d/" + v.Binary
  1232. envFile := "/etc/" + v.Binary + ".env"
  1233. return `#!/bin/sh
  1234. set -e
  1235. INIT="` + init + `"
  1236. ENV_FILE="` + envFile + `"
  1237. cat > "$ENV_FILE.new" <<'ENVEOF'
  1238. ` + envBlock + `ENVEOF
  1239. chmod 600 "$ENV_FILE.new"
  1240. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1241. if [ -x "$INIT" ]; then
  1242. "$INIT" stop >/dev/null 2>&1 || true
  1243. "$INIT" start >/dev/null 2>&1 || true
  1244. fi
  1245. `
  1246. }
  1247. func sshServiceScript(v rintegration.Vendor, action string) string {
  1248. if v.InitSystem() == "merlin" {
  1249. // Merlin no tiene procd: las acciones van al script de control
  1250. // con pidfile. check sigue siendo pgrep para no cambiar el camino
  1251. // de salud del handler.
  1252. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1253. switch action {
  1254. case "start":
  1255. return "test -x " + ctrl + " && " + ctrl + " start || true"
  1256. case "stop":
  1257. return "test -x " + ctrl + " && " + ctrl + " stop || true"
  1258. case "restart":
  1259. return "test -x " + ctrl + " && " + ctrl + " restart || true"
  1260. case "check":
  1261. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1262. }
  1263. return "true"
  1264. }
  1265. init := "/etc/init.d/" + v.Binary
  1266. switch action {
  1267. case "start":
  1268. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  1269. case "stop":
  1270. return "test -x " + init + " && " + init + " stop || true"
  1271. case "restart":
  1272. return "test -x " + init + " && " + init + " restart || true"
  1273. case "check":
  1274. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1275. }
  1276. return "true"
  1277. }
  1278. func sshUninstallScript(v rintegration.Vendor) string {
  1279. if v.InitSystem() == "merlin" {
  1280. return sshMerlinUninstallScript(v)
  1281. }
  1282. init := "/etc/init.d/" + v.Binary
  1283. bin := "/usr/sbin/" + v.Binary
  1284. envFile := "/etc/" + v.Binary + ".env"
  1285. return fmt.Sprintf(
  1286. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  1287. init, init, init, init, init, bin, envFile,
  1288. )
  1289. }
  1290. // sshMerlinUninstallScript para el pusher con su script de control, quita el
  1291. // bloque gestionado de services-start (el resto del hook queda intacto) y
  1292. // borra /jffs/netpulse entero.
  1293. func sshMerlinUninstallScript(v rintegration.Vendor) string {
  1294. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1295. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1296. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1297. return `CTRL="` + ctrl + `"
  1298. HOOK="/jffs/scripts/services-start"
  1299. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1300. if [ -f "$HOOK" ]; then
  1301. sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
  1302. fi
  1303. rm -rf /jffs/netpulse
  1304. `
  1305. }