4
0

integrations.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
  274. writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
  275. }
  276. type integrationCreateBody struct {
  277. Slug string `json:"slug"`
  278. Vendor string `json:"vendor"`
  279. Host string `json:"host"`
  280. Username string `json:"username"`
  281. Password string `json:"password"`
  282. IntervalS int `json:"intervalS"`
  283. Arch string `json:"arch"`
  284. }
  285. func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
  286. if s.db == nil {
  287. writeError(w, http.StatusInternalServerError, "db_error")
  288. return
  289. }
  290. var body integrationCreateBody
  291. if st := readJSONBody(w, r, &body); st != 0 {
  292. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
  293. return
  294. }
  295. if !agentSlugRe.MatchString(body.Slug) {
  296. writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
  297. return
  298. }
  299. vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
  300. if !ok {
  301. writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
  302. return
  303. }
  304. if body.Host == "" || body.Username == "" || body.Password == "" {
  305. writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
  306. return
  307. }
  308. if body.IntervalS < 10 || body.IntervalS > 86400 {
  309. writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
  310. return
  311. }
  312. arch := body.Arch
  313. if arch == "" {
  314. arch = vendor.Arches[0]
  315. } else if !vendorSupportsArch(vendor, arch) {
  316. writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
  317. return
  318. }
  319. store := s.integrationsStore()
  320. if _, exists := store.Get(body.Slug); exists {
  321. writeError(w, http.StatusConflict, "already_exists", "integration already exists")
  322. return
  323. }
  324. // El env que se va a escribir tiene que poder arrancar: con la URL en https
  325. // el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
  326. // exige que este server alcance su propia URL pública. Mejor un 502 aquí,
  327. // sin tocar nada, que un alta que muere al segundo siguiente.
  328. serverURL := s.agentBaseURL(r)
  329. if err := requirePusherPin(serverURL); err != nil {
  330. writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
  331. return
  332. }
  333. // Resolver y descargar el último release verificado. En modo local se
  334. // extrae el binario aquí (corre en este host); en modo ssh solo se
  335. // verifica: el router descarga el asset él mismo.
  336. fetch := s.integrationFetcher()
  337. res, err := fetch.ResolveLatest(vendor, arch)
  338. if err != nil {
  339. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  340. return
  341. }
  342. binPath := ""
  343. if vendor.Mode == "local" {
  344. if s.integrations == nil {
  345. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  346. return
  347. }
  348. installDir := filepath.Join(s.integrations.Dir(), body.Slug)
  349. binPath, err = fetch.Download(res, vendor.Binary, installDir)
  350. if err != nil {
  351. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  352. return
  353. }
  354. } else {
  355. if s.pool == nil {
  356. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  357. return
  358. }
  359. if err := fetch.Verify(res); err != nil {
  360. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  361. return
  362. }
  363. }
  364. now := time.Now().UnixMilli()
  365. row := rintegration.Row{
  366. Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
  367. Username: body.Username, Version: res.Version, Asset: res.AssetName,
  368. Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
  369. CreatedAt: now, UpdatedAt: now,
  370. }
  371. if err := store.Upsert(row); err != nil {
  372. writeError(w, http.StatusInternalServerError, "db_error")
  373. return
  374. }
  375. // #1708: en modo ssh la misma contraseña del formulario es la credencial
  376. // SSH del alta y de las acciones posteriores: se guarda en el fichero
  377. // compañero (0600) antes de conectar, nunca en la base de datos.
  378. if vendor.Mode == "ssh" && s.integrations != nil {
  379. if err := s.integrations.WriteSSHPassword(body.Slug, body.Password); err != nil {
  380. _ = store.Delete(body.Slug)
  381. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  382. return
  383. }
  384. }
  385. // Router external cuyo id es el slug (push autenticado por token de
  386. // agente, agent.token.<slug>).
  387. router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  388. Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
  389. })
  390. if err != nil || router.ID != body.Slug {
  391. _ = store.Delete(body.Slug)
  392. writeError(w, http.StatusInternalServerError, "router_error")
  393. return
  394. }
  395. s.syncRouters()
  396. rollback := func() {
  397. if vendor.Mode == "local" && s.integrations != nil {
  398. _ = s.integrations.Stop(body.Slug)
  399. _ = s.integrations.Cleanup(body.Slug)
  400. }
  401. if vendor.Mode == "ssh" && s.integrations != nil {
  402. _ = s.integrations.RemoveSSHPassword(body.Slug)
  403. }
  404. _ = routerstore.RemoveRouter(s.db.DB, body.Slug)
  405. s.syncRouters()
  406. _ = store.Delete(body.Slug)
  407. }
  408. token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
  409. env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
  410. if vendor.Mode == "local" {
  411. return s.integrations.Start(body.Slug, env, binPath)
  412. }
  413. return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
  414. })
  415. if err != nil {
  416. rollback()
  417. writeError(w, http.StatusBadGateway, sshErrorOr(err, "start_failed"), err.Error())
  418. return
  419. }
  420. _ = store.SetState(body.Slug, "running", "")
  421. _ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
  422. s.broadcastIntegrations()
  423. item, _ := s.getIntegrationRow(body.Slug)
  424. writeJSON(w, http.StatusCreated, map[string]any{
  425. "integration": s.integrationItemOf(item),
  426. "token": token,
  427. })
  428. }
  429. func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
  430. for _, a := range v.Arches {
  431. if a == arch {
  432. return true
  433. }
  434. }
  435. return false
  436. }
  437. // pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
  438. // propio router, así que el host del dispositivo es la propia unidad
  439. // (127.0.0.1) en lugar del host SSH de la tabla.
  440. func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
  441. prefix := strings.ToUpper(v.ID) + "_"
  442. host := row.Host
  443. if v.Mode == "ssh" {
  444. host = "127.0.0.1"
  445. }
  446. env := map[string]string{
  447. prefix + "HOST": host,
  448. prefix + "USER": row.Username,
  449. prefix + "PASS": password,
  450. prefix + "INSECURE": "1",
  451. "NETPULSE_SERVER": serverURL,
  452. "NETPULSE_TOKEN": token,
  453. "NETPULSE_SLUG": row.Slug,
  454. "NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
  455. }
  456. for k, v := range pusherPinEnv(serverURL) {
  457. env[k] = v
  458. }
  459. return env
  460. }
  461. // healPusherPin merges the current server pin into a pusher environment,
  462. // healing files written before the pin requirement and refreshing the pin
  463. // after a certificate reissue. It is a no-op when the server URL needs no
  464. // pin (plain HTTP).
  465. func healPusherPin(env map[string]string, serverURL string) map[string]string {
  466. for k, v := range pusherPinEnv(serverURL) {
  467. env[k] = v
  468. }
  469. return env
  470. }
  471. func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
  472. _, err := s.runIntegrationSSH(row, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
  473. return err
  474. }
  475. // sshPasswordSetter es la capacidad opcional del pool SSH de conectar por
  476. // contraseña (#1708). adapters.SSHPool la implementa; los fakes de tests que
  477. // solo implementan Run no, y en ese caso el pool queda como esté.
  478. type sshPasswordSetter interface {
  479. SetPassword(host, user, password string)
  480. }
  481. // applyIntegrationSSHAuth aplica al pool la credencial SSH de la
  482. // integración (#1708): si existe el fichero compañero <slug>.sshpass la
  483. // conexión va por contraseña con el usuario de la fila (gana sobre la llave
  484. // del servidor); si no, la credencial se limpia y el dial usa la llave como
  485. // siempre. Un fichero ilegible cae a llave con aviso en el log.
  486. func (s *server) applyIntegrationSSHAuth(row rintegration.Row) {
  487. if s.pool == nil || s.integrations == nil {
  488. return
  489. }
  490. setter, ok := s.pool.(sshPasswordSetter)
  491. if !ok {
  492. return
  493. }
  494. pass, err := s.integrations.ReadSSHPassword(row.Slug)
  495. if err != nil {
  496. log.Printf("[netpulse] aviso: integración %s: no se pudo leer el fichero de contraseña SSH (%v); conecto con llave", row.Slug, err)
  497. pass = ""
  498. }
  499. setter.SetPassword(row.Host, row.Username, pass)
  500. }
  501. // runIntegrationSSH ejecuta un comando en el router de la integración
  502. // aplicando antes la credencial SSH del fichero compañero (#1708).
  503. func (s *server) runIntegrationSSH(row rintegration.Row, cmd string, timeout time.Duration) (string, error) {
  504. s.applyIntegrationSSHAuth(row)
  505. return s.pool.Run(row.Host, cmd, timeout)
  506. }
  507. // sshErrorCode clasifica un error SSH para la API (#1708): el rechazo de
  508. // autenticación es su propio código (ssh_auth_failed) frente al fallo
  509. // genérico de conexión (ssh_failed), de modo que la UI puede pedir revisar
  510. // la contraseña.
  511. func sshErrorCode(err error) string {
  512. var ae *adapters.SSHAuthError
  513. if errors.As(err, &ae) {
  514. return "ssh_auth_failed"
  515. }
  516. return "ssh_failed"
  517. }
  518. // sshErrorOr devuelve ssh_auth_failed cuando err es un rechazo de
  519. // autenticación SSH y fallback para cualquier otro error.
  520. func sshErrorOr(err error, fallback string) string {
  521. if sshErrorCode(err) == "ssh_auth_failed" {
  522. return "ssh_auth_failed"
  523. }
  524. return fallback
  525. }
  526. func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
  527. slug := r.PathValue("slug")
  528. row, ok := s.getIntegrationRow(slug)
  529. if !ok {
  530. writeError(w, http.StatusNotFound, "not_found")
  531. return
  532. }
  533. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  534. if !ok {
  535. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  536. return
  537. }
  538. store := s.integrationsStore()
  539. if vendor.Mode == "local" {
  540. if s.integrations == nil {
  541. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  542. return
  543. }
  544. if !s.integrations.Running(slug) {
  545. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  546. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  547. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  548. return
  549. }
  550. }
  551. } else {
  552. if s.pool == nil {
  553. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  554. return
  555. }
  556. if _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
  557. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  558. return
  559. }
  560. }
  561. _ = store.SetState(slug, "running", "")
  562. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  563. s.broadcastIntegrations()
  564. item, _ := s.getIntegrationRow(slug)
  565. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  566. }
  567. func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
  568. slug := r.PathValue("slug")
  569. row, ok := s.getIntegrationRow(slug)
  570. if !ok {
  571. writeError(w, http.StatusNotFound, "not_found")
  572. return
  573. }
  574. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  575. if !ok {
  576. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  577. return
  578. }
  579. if vendor.Mode == "local" {
  580. if s.integrations != nil {
  581. _ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
  582. }
  583. } else if s.pool != nil {
  584. _, _ = s.runIntegrationSSH(row, sshServiceScript(vendor, "stop"), 60*time.Second)
  585. }
  586. _ = s.integrationsStore().SetState(slug, "stopped", "")
  587. s.broadcastIntegrations()
  588. item, _ := s.getIntegrationRow(slug)
  589. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  590. }
  591. func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
  592. slug := r.PathValue("slug")
  593. row, ok := s.getIntegrationRow(slug)
  594. if !ok {
  595. writeError(w, http.StatusNotFound, "not_found")
  596. return
  597. }
  598. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  599. if !ok {
  600. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  601. return
  602. }
  603. running := false
  604. if vendor.Mode == "local" {
  605. running = s.integrations != nil && s.integrations.Running(slug)
  606. } else if s.pool != nil {
  607. _, err := s.runIntegrationSSH(row, sshServiceScript(vendor, "check"), 30*time.Second)
  608. running = err == nil
  609. }
  610. // #1696: un check verificado reconcilia el estado guardado: el unverified
  611. // que deja un reinicio del servidor (o una fila desfasada) vuelve a
  612. // running cuando el proceso está demostradamente vivo.
  613. if running && row.State != "running" {
  614. _ = s.integrationsStore().SetState(slug, "running", "")
  615. s.broadcastIntegrations()
  616. if fresh, ok := s.getIntegrationRow(slug); ok {
  617. row = fresh
  618. }
  619. }
  620. writeJSON(w, http.StatusOK, map[string]any{
  621. "integration": s.integrationItemOf(row),
  622. "running": running,
  623. })
  624. }
  625. func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
  626. slug := r.PathValue("slug")
  627. row, ok := s.getIntegrationRow(slug)
  628. if !ok {
  629. writeError(w, http.StatusNotFound, "not_found")
  630. return
  631. }
  632. vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
  633. if !ok {
  634. writeError(w, http.StatusInternalServerError, "invalid_vendor")
  635. return
  636. }
  637. fetch := s.integrationFetcher()
  638. res, err := fetch.ResolveLatest(vendor, row.Arch)
  639. if err != nil {
  640. writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
  641. return
  642. }
  643. store := s.integrationsStore()
  644. if vendor.Mode == "local" {
  645. if s.integrations == nil {
  646. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  647. return
  648. }
  649. _ = s.integrations.Stop(slug)
  650. installDir := filepath.Join(s.integrations.Dir(), slug)
  651. if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
  652. _ = store.SetState(slug, "error", err.Error())
  653. s.broadcastIntegrations()
  654. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  655. return
  656. }
  657. // Heal environments created before the pin requirement: the
  658. // refreshed binary refuses to start without it. Best effort, on
  659. // error the old file is reused and the start below reports it.
  660. if env, err := s.integrations.Env(slug); err == nil {
  661. _ = s.integrations.WriteEnv(slug, healPusherPin(env, s.agentBaseURL(r)))
  662. }
  663. if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
  664. _ = store.SetState(slug, "error", err.Error())
  665. s.broadcastIntegrations()
  666. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  667. return
  668. }
  669. } else {
  670. if s.pool == nil {
  671. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  672. return
  673. }
  674. if err := fetch.Verify(res); err != nil {
  675. writeError(w, http.StatusBadGateway, "download_failed", err.Error())
  676. return
  677. }
  678. env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
  679. if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
  680. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  681. return
  682. }
  683. }
  684. _ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
  685. _ = store.SetState(slug, "running", "")
  686. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  687. s.broadcastIntegrations()
  688. item, _ := s.getIntegrationRow(slug)
  689. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  690. }
  691. // handleIntegrationEdit actualiza los ajustes mutables de una integración sin
  692. // recrearla: host, usuario, contraseña e intervalo. El fichero de entorno se
  693. // lee, se cambian solo las claves afectadas y se reescribe, de modo que el
  694. // token y la contraseña omitida se conservan (nunca viven en la base de datos).
  695. func (s *server) handleIntegrationEdit(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. var body struct {
  708. Host *string `json:"host"`
  709. Username *string `json:"username"`
  710. Password *string `json:"password"`
  711. IntervalS *int `json:"intervalS"`
  712. }
  713. if st := readJSONBody(w, r, &body); st != 0 {
  714. writeBodyError(w, st, "invalid_body", "")
  715. return
  716. }
  717. changed := false
  718. if body.Host != nil {
  719. h := strings.TrimSpace(*body.Host)
  720. if h == "" {
  721. writeError(w, http.StatusBadRequest, "invalid_input", "host cannot be empty")
  722. return
  723. }
  724. row.Host = h
  725. changed = true
  726. }
  727. if body.Username != nil {
  728. u := strings.TrimSpace(*body.Username)
  729. if u == "" {
  730. writeError(w, http.StatusBadRequest, "invalid_input", "username cannot be empty")
  731. return
  732. }
  733. row.Username = u
  734. changed = true
  735. }
  736. if body.IntervalS != nil {
  737. if *body.IntervalS < 10 || *body.IntervalS > 86400 {
  738. writeError(w, http.StatusBadRequest, "invalid_interval")
  739. return
  740. }
  741. row.IntervalS = *body.IntervalS
  742. changed = true
  743. }
  744. password := ""
  745. if body.Password != nil {
  746. password = *body.Password
  747. changed = true
  748. }
  749. if !changed {
  750. writeError(w, http.StatusBadRequest, "invalid_input", "nothing to update")
  751. return
  752. }
  753. prefix := strings.ToUpper(vendor.ID) + "_"
  754. host := row.Host
  755. if vendor.Mode == "ssh" {
  756. host = "127.0.0.1"
  757. }
  758. store := s.integrationsStore()
  759. if vendor.Mode == "local" {
  760. if s.integrations == nil {
  761. writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
  762. return
  763. }
  764. env, err := s.integrations.Env(slug)
  765. if err != nil {
  766. _ = store.SetState(slug, "error", err.Error())
  767. s.broadcastIntegrations()
  768. writeError(w, http.StatusConflict, "env_unavailable", err.Error())
  769. return
  770. }
  771. env[prefix+"HOST"] = host
  772. env[prefix+"USER"] = row.Username
  773. if password != "" {
  774. env[prefix+"PASS"] = password
  775. }
  776. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  777. healPusherPin(env, s.agentBaseURL(r))
  778. if err := s.integrations.WriteEnv(slug, env); err != nil {
  779. _ = store.SetState(slug, "error", err.Error())
  780. s.broadcastIntegrations()
  781. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  782. return
  783. }
  784. _ = s.integrations.Stop(slug)
  785. binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
  786. if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
  787. _ = store.SetState(slug, "error", err.Error())
  788. s.broadcastIntegrations()
  789. writeError(w, http.StatusBadGateway, "start_failed", err.Error())
  790. return
  791. }
  792. } else {
  793. if s.pool == nil {
  794. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  795. return
  796. }
  797. // #1708: la contraseña nueva del formulario es también la credencial
  798. // SSH: guardarla en el fichero compañero ANTES de conectar, porque si
  799. // el usuario ya cambió la contraseña en el router, la conexión de
  800. // este mismo guardado necesita la nueva.
  801. if password != "" && s.integrations != nil {
  802. if err := s.integrations.WriteSSHPassword(slug, password); err != nil {
  803. writeError(w, http.StatusInternalServerError, "ssh_password_write", err.Error())
  804. return
  805. }
  806. }
  807. raw, err := s.runIntegrationSSH(row, sshEnvReadScript(vendor), 30*time.Second)
  808. if err != nil {
  809. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  810. return
  811. }
  812. env := rintegration.ParseEnv(raw)
  813. env[prefix+"HOST"] = host
  814. env[prefix+"USER"] = row.Username
  815. if password != "" {
  816. env[prefix+"PASS"] = password
  817. }
  818. env["NETPULSE_INTERVAL"] = strconv.Itoa(row.IntervalS) + "s"
  819. healPusherPin(env, s.agentBaseURL(r))
  820. if _, err := s.runIntegrationSSH(row, sshEnvWriteScript(vendor, env), 60*time.Second); err != nil {
  821. _ = store.SetState(slug, "error", err.Error())
  822. s.broadcastIntegrations()
  823. writeError(w, http.StatusBadGateway, sshErrorOr(err, "ssh_failed"), err.Error())
  824. return
  825. }
  826. }
  827. if err := store.Upsert(row); err != nil {
  828. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  829. return
  830. }
  831. _ = store.SetState(slug, "running", "")
  832. _ = store.SetLastStart(slug, time.Now().UnixMilli())
  833. s.broadcastIntegrations()
  834. item, _ := s.getIntegrationRow(slug)
  835. writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
  836. }
  837. func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
  838. slug := r.PathValue("slug")
  839. row, ok := s.getIntegrationRow(slug)
  840. if !ok {
  841. writeError(w, http.StatusNotFound, "not_found")
  842. return
  843. }
  844. vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
  845. if vendor.Mode == "local" {
  846. if s.integrations != nil {
  847. _ = s.integrations.Stop(slug)
  848. _ = s.integrations.Cleanup(slug)
  849. }
  850. } else if s.pool != nil {
  851. _, _ = s.runIntegrationSSH(row, sshUninstallScript(vendor), 60*time.Second)
  852. }
  853. // #1708: la contraseña SSH del fichero compañero muere con la
  854. // integración y el pool pierde la credencial (la conexión cacheada se
  855. // tira y el siguiente dial vuelve a la llave).
  856. if s.integrations != nil {
  857. _ = s.integrations.RemoveSSHPassword(slug)
  858. }
  859. if setter, ok := s.pool.(sshPasswordSetter); ok {
  860. setter.SetPassword(row.Host, "", "")
  861. }
  862. _ = s.integrationsStore().Delete(slug)
  863. _ = routerstore.RemoveRouter(s.db.DB, slug)
  864. s.syncRouters()
  865. if s.db != nil {
  866. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  867. }
  868. s.broadcastIntegrations()
  869. w.WriteHeader(http.StatusNoContent)
  870. }
  871. // ---------------------------------------------------------------------------
  872. // Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
  873. // ---------------------------------------------------------------------------
  874. // envFileBody renders the sorted KEY=value body of an env file, with values
  875. // escaped by EscapeEnvValue for a lossless round-trip through ParseEnv.
  876. func envFileBody(env map[string]string) string {
  877. keys := make([]string, 0, len(env))
  878. for k := range env {
  879. keys = append(keys, k)
  880. }
  881. sort.Strings(keys)
  882. var b strings.Builder
  883. for _, k := range keys {
  884. b.WriteString(k)
  885. b.WriteString("=")
  886. b.WriteString(rintegration.EscapeEnvValue(env[k]))
  887. b.WriteString("\n")
  888. }
  889. return b.String()
  890. }
  891. // sshInstallScript genera el instalador on-router de un vendor en modo ssh.
  892. // Ramifica por el sistema de init del vendor (#1681): procd (layout OpenWrt,
  893. // salida intacta) o merlin (/jffs + bloque gestionado en services-start).
  894. func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  895. if v.InitSystem() == "merlin" {
  896. return sshMerlinInstallScript(v, env, assetURL, sha256)
  897. }
  898. return sshProcdInstallScript(v, env, assetURL, sha256)
  899. }
  900. // sshProcdInstallScript instala el pusher en un vendor OpenWrt: binario en
  901. // /usr/sbin, init procd en /etc/init.d y env en /etc.
  902. func sshProcdInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  903. bin := "/usr/sbin/" + v.Binary
  904. init := "/etc/init.d/" + v.Binary
  905. envFile := "/etc/" + v.Binary + ".env"
  906. envBlock := envFileBody(env)
  907. return `#!/bin/sh
  908. set -e
  909. BIN="` + bin + `"
  910. INIT="` + init + `"
  911. ENV_FILE="` + envFile + `"
  912. SERVER="` + env["NETPULSE_SERVER"] + `"
  913. ASSET_URL="` + assetURL + `"
  914. SHA256="` + sha256 + `"
  915. # Preflight: el router debe alcanzar el server.
  916. if command -v curl >/dev/null 2>&1; then
  917. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  918. else
  919. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  920. fi
  921. # Parar el servicio previo (el proceso vivo mantiene el binario abierto).
  922. [ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
  923. # Descargar el asset desde la URL ya verificada en el server.
  924. if command -v curl >/dev/null 2>&1; then
  925. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  926. else
  927. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  928. fi
  929. # Verificar sha256 antes de instalar.
  930. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  931. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  932. # Extraer y mover de forma atómica (.new -> rename).
  933. mkdir -p /tmp/` + v.Binary + `.extract
  934. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  935. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  936. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  937. cp "$SRC" "$BIN.new"
  938. chmod 0755 "$BIN.new"
  939. mv -f "$BIN.new" "$BIN"
  940. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  941. # Env (chmod 600): solo se escribe en el alta; los updates preservan el
  942. # fichero existente (la contraseña y el token solo viven ahí).
  943. if [ ! -f "$ENV_FILE" ]; then
  944. cat > "$ENV_FILE" <<'ENVEOF'
  945. ` + envBlock + `ENVEOF
  946. chmod 600 "$ENV_FILE"
  947. fi
  948. # Init procd.
  949. cat > "$INIT" <<'INITEOF'
  950. #!/bin/sh /etc/rc.common
  951. START=99
  952. STOP=10
  953. USE_PROCD=1
  954. BIN="/usr/sbin/` + v.Binary + `"
  955. ENV_FILE="/etc/` + v.Binary + `.env"
  956. start_service() {
  957. [ -x "$BIN" ] || return 1
  958. [ -r "$ENV_FILE" ] || { echo "netpulse: missing or unreadable env file $ENV_FILE" >&2; return 1; }
  959. # Cargar el fichero de entorno y pasarlo entero al proceso en UNA sola
  960. # llamada env (#1709): cada llamada adicional pisaria a la anterior y al
  961. # proceso solo le llegaria la ultima variable (OpenWrt 21.02, #1701).
  962. # Los valores van escapados (salto de linea = \n): printf %b los
  963. # desescapa igual que ParseEnv en el server y que el control script de
  964. # Merlin (#1705), sin pasar por . "$ENV_FILE" ni /etc/profile.
  965. set --
  966. while IFS= read -r line || [ -n "$line" ]; do
  967. case "$line" in ""|\#*) continue ;; esac
  968. k=${line%%=*}
  969. val=${line#*=}
  970. val=$(printf '%b' "$val")
  971. set -- "$@" "$k=$val"
  972. done < "$ENV_FILE"
  973. procd_open_instance ` + v.Binary + `
  974. procd_set_param env "$@"
  975. procd_set_param command "$BIN"
  976. procd_set_param respawn 3600 5 5
  977. procd_set_param stdout 1
  978. procd_set_param stderr 1
  979. # Vigila el fichero: un cambio sigue reiniciando el servicio y el
  980. # arranque vuelve a leer el env, asi que el proceso recoge los valores
  981. # nuevos.
  982. procd_set_param file "$ENV_FILE"
  983. procd_close_instance
  984. }
  985. INITEOF
  986. chmod 0755 "$INIT"
  987. "$INIT" enable
  988. "$INIT" restart
  989. `
  990. }
  991. // sshMerlinInstallScript instala el pusher en un vendor Asuswrt-Merlin
  992. // (#1681): sin procd, todo bajo /jffs/netpulse (binario, env, script de
  993. // control con pidfile y log) y un bloque gestionado en
  994. // /jffs/scripts/services-start para el arranque al boot. Re-ejecutarlo es
  995. // idempotente: el env solo se escribe si falta y el bloque solo se añade una
  996. // vez; el resto del hook no se toca.
  997. func sshMerlinInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
  998. dir := "/jffs/netpulse"
  999. bin := dir + "/" + v.Binary
  1000. ctrl := bin + ".sh"
  1001. envFile := bin + ".env"
  1002. pidFile := bin + ".pid"
  1003. logFile := bin + ".log"
  1004. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1005. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1006. return `#!/bin/sh
  1007. set -e
  1008. BIN="` + bin + `"
  1009. CTRL="` + ctrl + `"
  1010. ENV_FILE="` + envFile + `"
  1011. PID_FILE="` + pidFile + `"
  1012. LOG_FILE="` + logFile + `"
  1013. HOOK="/jffs/scripts/services-start"
  1014. SERVER="` + env["NETPULSE_SERVER"] + `"
  1015. ASSET_URL="` + assetURL + `"
  1016. SHA256="` + sha256 + `"
  1017. # Preflight: el router debe alcanzar el server.
  1018. if command -v curl >/dev/null 2>&1; then
  1019. curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1020. else
  1021. wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
  1022. fi
  1023. # Parar el pusher previo (el proceso vivo mantiene el binario abierto).
  1024. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1025. # Descargar el asset desde la URL ya verificada en el server.
  1026. if command -v curl >/dev/null 2>&1; then
  1027. curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1028. else
  1029. wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
  1030. fi
  1031. # Verificar sha256 antes de instalar.
  1032. GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
  1033. [ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
  1034. # Extraer y mover de forma atómica (.new -> rename).
  1035. mkdir -p /tmp/` + v.Binary + `.extract
  1036. tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
  1037. SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
  1038. [ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
  1039. mkdir -p "$DIR"
  1040. cp "$SRC" "$BIN.new"
  1041. chmod 0755 "$BIN.new"
  1042. mv -f "$BIN.new" "$BIN"
  1043. rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
  1044. # Env (chmod 600): solo se escribe si aún no existe; los updates preservan
  1045. # el fichero (la contraseña y el token solo viven ahí).
  1046. if [ ! -f "$ENV_FILE" ]; then
  1047. cat > "$ENV_FILE" <<'ENVEOF'
  1048. ` + envFileBody(env) + `ENVEOF
  1049. chmod 600 "$ENV_FILE"
  1050. fi
  1051. # Script de control con pidfile (start|stop|restart|check). El env guarda
  1052. # los valores escapados (salto de línea = \n): printf %b los desescapa igual
  1053. # que ParseEnv en el server antes de exportarlos al pusher.
  1054. cat > "$CTRL" <<'CTRLEOF'
  1055. #!/bin/sh
  1056. # NetPulse pusher control script (Asuswrt-Merlin).
  1057. BIN="` + bin + `"
  1058. PID_FILE="` + pidFile + `"
  1059. ENV_FILE="` + envFile + `"
  1060. LOG_FILE="` + logFile + `"
  1061. running() {
  1062. [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
  1063. }
  1064. case "$1" in
  1065. start)
  1066. [ -x "$BIN" ] || { echo "netpulse: missing $BIN"; exit 1; }
  1067. if running; then
  1068. exit 0
  1069. fi
  1070. rm -f "$PID_FILE"
  1071. [ -f "$ENV_FILE" ] || { echo "netpulse: missing $ENV_FILE"; exit 1; }
  1072. while IFS= read -r line || [ -n "$line" ]; do
  1073. case "$line" in ""|\#*) continue ;; esac
  1074. k=${line%%=*}
  1075. val=${line#*=}
  1076. val=$(printf '%b' "$val")
  1077. export "$k=$val"
  1078. done < "$ENV_FILE"
  1079. nohup "$BIN" >> "$LOG_FILE" 2>&1 &
  1080. echo $! > "$PID_FILE"
  1081. ;;
  1082. stop)
  1083. if [ -f "$PID_FILE" ]; then
  1084. RUN_PID=$(cat "$PID_FILE")
  1085. kill "$RUN_PID" 2>/dev/null || true
  1086. n=0
  1087. while kill -0 "$RUN_PID" 2>/dev/null && [ "$n" -lt 10 ]; do
  1088. sleep 1
  1089. n=$((n+1))
  1090. done
  1091. if kill -0 "$RUN_PID" 2>/dev/null; then
  1092. kill -9 "$RUN_PID" 2>/dev/null || true
  1093. fi
  1094. rm -f "$PID_FILE"
  1095. fi
  1096. ;;
  1097. restart)
  1098. "$0" stop
  1099. "$0" start
  1100. ;;
  1101. check)
  1102. if running; then
  1103. exit 0
  1104. fi
  1105. exit 1
  1106. ;;
  1107. *)
  1108. echo "usage: $0 {start|stop|restart|check}"
  1109. exit 2
  1110. ;;
  1111. esac
  1112. CTRLEOF
  1113. chmod 0755 "$CTRL"
  1114. # Arranque al boot: bloque gestionado en services-start, delimitado por
  1115. # marcadores únicos para poder quitarlo sin tocar el resto del fichero.
  1116. mkdir -p /jffs/scripts
  1117. if [ ! -f "$HOOK" ]; then
  1118. printf '#!/bin/sh\n' > "$HOOK"
  1119. fi
  1120. chmod 0755 "$HOOK"
  1121. if ! grep -qF '` + blockStart + `' "$HOOK" 2>/dev/null; then
  1122. cat >> "$HOOK" <<'BLOKEOF'
  1123. ` + blockStart + `
  1124. ` + ctrl + ` start
  1125. ` + blockEnd + `
  1126. BLOKEOF
  1127. fi
  1128. "$CTRL" start
  1129. `
  1130. }
  1131. // sshEnvReadScript prints the environment file of an integration running
  1132. // inside the router, so the server can merge changes without ever storing the
  1133. // token or the password. Merlin vendors keep the env under /jffs/netpulse.
  1134. func sshEnvReadScript(v rintegration.Vendor) string {
  1135. if v.InitSystem() == "merlin" {
  1136. return "cat /jffs/netpulse/" + v.Binary + ".env"
  1137. }
  1138. return "cat /etc/" + v.Binary + ".env"
  1139. }
  1140. // sshEnvWriteScript replaces the environment file inside the router and
  1141. // restarts the service. Values come already escaped by EscapeEnvValue and the
  1142. // heredoc is quoted, so the shell does not expand anything.
  1143. func sshEnvWriteScript(v rintegration.Vendor, env map[string]string) string {
  1144. envBlock := envFileBody(env)
  1145. if v.InitSystem() == "merlin" {
  1146. envFile := "/jffs/netpulse/" + v.Binary + ".env"
  1147. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1148. return `#!/bin/sh
  1149. set -e
  1150. ENV_FILE="` + envFile + `"
  1151. CTRL="` + ctrl + `"
  1152. cat > "$ENV_FILE.new" <<'ENVEOF'
  1153. ` + envBlock + `ENVEOF
  1154. chmod 600 "$ENV_FILE.new"
  1155. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1156. if [ -x "$CTRL" ]; then
  1157. "$CTRL" restart >/dev/null 2>&1 || true
  1158. fi
  1159. `
  1160. }
  1161. init := "/etc/init.d/" + v.Binary
  1162. envFile := "/etc/" + v.Binary + ".env"
  1163. return `#!/bin/sh
  1164. set -e
  1165. INIT="` + init + `"
  1166. ENV_FILE="` + envFile + `"
  1167. cat > "$ENV_FILE.new" <<'ENVEOF'
  1168. ` + envBlock + `ENVEOF
  1169. chmod 600 "$ENV_FILE.new"
  1170. mv -f "$ENV_FILE.new" "$ENV_FILE"
  1171. if [ -x "$INIT" ]; then
  1172. "$INIT" stop >/dev/null 2>&1 || true
  1173. "$INIT" start >/dev/null 2>&1 || true
  1174. fi
  1175. `
  1176. }
  1177. func sshServiceScript(v rintegration.Vendor, action string) string {
  1178. if v.InitSystem() == "merlin" {
  1179. // Merlin no tiene procd: las acciones van al script de control
  1180. // con pidfile. check sigue siendo pgrep para no cambiar el camino
  1181. // de salud del handler.
  1182. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1183. switch action {
  1184. case "start":
  1185. return "test -x " + ctrl + " && " + ctrl + " start || true"
  1186. case "stop":
  1187. return "test -x " + ctrl + " && " + ctrl + " stop || true"
  1188. case "restart":
  1189. return "test -x " + ctrl + " && " + ctrl + " restart || true"
  1190. case "check":
  1191. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1192. }
  1193. return "true"
  1194. }
  1195. init := "/etc/init.d/" + v.Binary
  1196. switch action {
  1197. case "start":
  1198. return "test -x " + init + " && " + init + " enable && " + init + " start || true"
  1199. case "stop":
  1200. return "test -x " + init + " && " + init + " stop || true"
  1201. case "restart":
  1202. return "test -x " + init + " && " + init + " restart || true"
  1203. case "check":
  1204. return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
  1205. }
  1206. return "true"
  1207. }
  1208. func sshUninstallScript(v rintegration.Vendor) string {
  1209. if v.InitSystem() == "merlin" {
  1210. return sshMerlinUninstallScript(v)
  1211. }
  1212. init := "/etc/init.d/" + v.Binary
  1213. bin := "/usr/sbin/" + v.Binary
  1214. envFile := "/etc/" + v.Binary + ".env"
  1215. return fmt.Sprintf(
  1216. "test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
  1217. init, init, init, init, init, bin, envFile,
  1218. )
  1219. }
  1220. // sshMerlinUninstallScript para el pusher con su script de control, quita el
  1221. // bloque gestionado de services-start (el resto del hook queda intacto) y
  1222. // borra /jffs/netpulse entero.
  1223. func sshMerlinUninstallScript(v rintegration.Vendor) string {
  1224. ctrl := "/jffs/netpulse/" + v.Binary + ".sh"
  1225. blockStart := "# >>> netpulse " + v.Binary + " >>>"
  1226. blockEnd := "# <<< netpulse " + v.Binary + " <<<"
  1227. return `CTRL="` + ctrl + `"
  1228. HOOK="/jffs/scripts/services-start"
  1229. [ -x "$CTRL" ] && "$CTRL" stop >/dev/null 2>&1 || true
  1230. if [ -f "$HOOK" ]; then
  1231. sed -i '/` + blockStart + `/,/` + blockEnd + `/d' "$HOOK" 2>/dev/null || true
  1232. fi
  1233. rm -rf /jffs/netpulse
  1234. `
  1235. }