Explorar el Código

fix(ubus): send the JSON-RPC transport to the web port, not SSH (#1893) (#2187)

Nacho hace 1 semana
padre
commit
af77b6b165

+ 59 - 5
server-go/internal/adapters/openwrt.go

@@ -28,6 +28,11 @@ import (
 
 const (
 	ubusHTTPTimeout = 4 * time.Second
+	// ubusHTTPDownTTL (#1893): tras un fallo de transporte HTTP no se vuelve
+	// a intentar hasta que pase este tiempo. Sin esta ventana, cada UbusCall
+	// reintentaba el POST (login incluido) antes de caer a SSH, de modo que
+	// un ciclo de poll multiplicaba las conexiones fallidas a la unidad.
+	ubusHTTPDownTTL = 10 * time.Minute
 	iwinfoTimeout   = 8 * time.Second
 	// radiosTTL (#368/#373, paridad con el agente): el resumen de radios
 	// (canal/htmode/txpower) apenas cambia; cachearlo evita correr iwinfo en
@@ -50,16 +55,25 @@ type OpenWrtClient struct {
 	User     string // para ubus HTTP (default root)
 	Password string
 
+	// httpHost es el destino del transporte ubus HTTP ("host:80"), que NO es
+	// el destino SSH (#1893): `Host` es `ip:puertoSSH` y un POST HTTP contra
+	// el puerto 22 acaba en dropbear como "Exit before auth" en cada
+	// llamada. Se deriva del host plano, nunca del puerto SSH configurado.
+	httpHost string
+
 	pool poolRunner
 
 	// mu protege el estado mutable del cliente (sid, lastStat, lastNetDev,
-	// lldpDownUntil): los handlers HTTP pueden sondear (p.ej. GetSurvey) en
-	// paralelo con el poller.
+	// lldpDownUntil, ubusHTTPDownUntil): los handlers HTTP pueden sondear
+	// (p.ej. GetSurvey) en paralelo con el poller.
 	mu sync.Mutex
 
 	sid        string     // sesión ubus HTTP cacheada
 	lastStat   *cpuSample // /proc/stat previo
 	lastNetDev *netSample // /proc/net/dev previo
+	// ubusHTTPDownUntil (#1893): el transporte HTTP falló y no se reintenta
+	// antes de este instante. Acceso serializado por mu.
+	ubusHTTPDownUntil time.Time
 	// lastNetIf: /proc/net/dev previo POR INTERFAZ (contadores por boca,
 	// issue #305). Acceso serializado por mu.
 	lastNetIf *netIfSample
@@ -117,8 +131,38 @@ func NewOpenWrtClient(cfg RouterConfig, pool poolRunner, user, password string)
 	if user == "" {
 		user = "root"
 	}
-	// Host aquí es el destino `host:port` (#605) para el pool SSH.
-	return &OpenWrtClient{Host: cfg.SSHAddr(), User: user, Password: password, pool: pool}
+	// Host aquí es el destino `host:port` (#605) para el pool SSH. El
+	// transporte ubus HTTP va al puerto web del mismo host (#1893).
+	return &OpenWrtClient{Host: cfg.SSHAddr(), httpHost: net.JoinHostPort(cfg.Host, "80"), User: user, Password: password, pool: pool}
+}
+
+// ubusURL es el endpoint ubus sobre HTTP: host plano en el puerto web, nunca
+// el destino SSH (#1893).
+func (c *OpenWrtClient) ubusURL() string {
+	host := c.httpHost
+	if host == "" {
+		if h, _, err := net.SplitHostPort(c.Host); err == nil {
+			host = net.JoinHostPort(h, "80")
+		} else {
+			host = net.JoinHostPort(c.Host, "80")
+		}
+	}
+	return "http://" + host + "/ubus"
+}
+
+// ubusHTTPReady informa si toca probar el transporte HTTP o si sigue en la
+// ventana de indisponibilidad abierta por el último fallo (#1893).
+func (c *OpenWrtClient) ubusHTTPReady() bool {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	return c.ubusHTTPDownUntil.IsZero() || time.Now().After(c.ubusHTTPDownUntil)
+}
+
+// markUbusHTTPDown abre la ventana de indisponibilidad del transporte HTTP.
+func (c *OpenWrtClient) markUbusHTTPDown() {
+	c.mu.Lock()
+	c.ubusHTTPDownUntil = time.Now().Add(ubusHTTPDownTTL)
+	c.mu.Unlock()
 }
 
 // ---------------------------------------------------------------------------
@@ -134,24 +178,30 @@ func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (jso
 	if params == nil {
 		params = map[string]any{}
 	}
+	// #1893: si el transporte HTTP ya falló, no se reintenta en cada llamada.
+	if !c.ubusHTTPReady() {
+		return nil, &ubusRPCError{"ubus HTTP no disponible"}
+	}
 	body, _ := json.Marshal(map[string]any{
 		"jsonrpc": "2.0", "id": 1, "method": "call",
 		"params": []any{sid, object, method, params},
 	})
 	ctx, cancel := context.WithTimeout(context.Background(), ubusHTTPTimeout)
 	defer cancel()
-	req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.Host+"/ubus", bytes.NewReader(body))
+	req, err := http.NewRequestWithContext(ctx, "POST", c.ubusURL(), bytes.NewReader(body))
 	if err != nil {
 		return nil, err
 	}
 	req.Header.Set("Content-Type", "application/json")
 	res, err := http.DefaultClient.Do(req)
 	if err != nil {
+		c.markUbusHTTPDown()
 		return nil, err
 	}
 	defer res.Body.Close()
 	data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
 	if err != nil {
+		c.markUbusHTTPDown()
 		return nil, err
 	}
 	if res.StatusCode != 200 {
@@ -162,6 +212,10 @@ func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (jso
 		Result json.RawMessage `json:"result"`
 	}
 	if err := json.Unmarshal(data, &rpc); err != nil {
+		// Un 200 que no es JSON-RPC es el puerto web de la unidad (LuCI u
+		// otra página), no ubus: reintentarlo en cada llamada solo suma
+		// peticiones inútiles.
+		c.markUbusHTTPDown()
 		return nil, &ubusRPCError{"ubus: respuesta no JSON"}
 	}
 	if len(rpc.Error) > 0 && string(rpc.Error) != "null" {

+ 123 - 0
server-go/internal/adapters/openwrt_ubus_test.go

@@ -0,0 +1,123 @@
+package adapters
+
+import (
+	"net"
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"strings"
+	"sync/atomic"
+	"testing"
+	"time"
+)
+
+// #1893: el transporte ubus HTTP apuntaba al destino SSH (`ip:22`), así que
+// cada UbusCall mandaba un POST HTTP al puerto de dropbear antes de caer a
+// SSH. En una unidad sondeada solo por SSH eso deja tres conexiones
+// "Exit before auth" por ciclo en el log del router.
+func TestUbusHTTPUsesWebPortNotSSH(t *testing.T) {
+	cfg := RouterConfig{ID: "gw", Host: "192.168.1.1", SSHPort: 2222}
+	c := NewOpenWrtClient(cfg, nil, "", "")
+
+	if c.Host != "192.168.1.1:2222" {
+		t.Fatalf("destino SSH: %q, want 192.168.1.1:2222", c.Host)
+	}
+	got := c.ubusURL()
+	want := "http://192.168.1.1:80/ubus"
+	if got != want {
+		t.Fatalf("ubus URL: %q, want %q (el puerto SSH no es un endpoint HTTP)", got, want)
+	}
+	if strings.Contains(got, "2222") {
+		t.Fatalf("la URL de ubus lleva el puerto SSH: %q", got)
+	}
+
+	// Puerto SSH por defecto: tampoco debe colarse el 22.
+	c = NewOpenWrtClient(RouterConfig{Host: "192.168.1.1"}, nil, "", "")
+	if got := c.ubusURL(); got != "http://192.168.1.1:80/ubus" {
+		t.Fatalf("ubus URL por defecto: %q", got)
+	}
+	// IPv6 literal: el host va entre corchetes.
+	c = NewOpenWrtClient(RouterConfig{Host: "fd00::1", SSHPort: 22}, nil, "", "")
+	if got := c.ubusURL(); got != "http://[fd00::1]:80/ubus" {
+		t.Fatalf("ubus URL IPv6: %q", got)
+	}
+}
+
+// #1893: tras un fallo de transporte HTTP no se vuelve a probar en cada
+// llamada; el cliente cae a SSH sin sumar peticiones al puerto web.
+func TestUbusHTTPStopsProbingAfterTransportFailure(t *testing.T) {
+	c := &OpenWrtClient{Host: "127.0.0.1:1", httpHost: "127.0.0.1:1"}
+
+	if _, err := c.ubusHTTPRpc(strings.Repeat("0", 32), "session", "login", nil); err == nil {
+		t.Fatal("un endpoint cerrado debe fallar")
+	}
+	if c.ubusHTTPReady() {
+		t.Fatal("tras un fallo de transporte el HTTP debe quedar en ventana de indisponibilidad")
+	}
+
+	var hits atomic.Int32
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		hits.Add(1)
+		_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":[0,{}]}`))
+	}))
+	defer srv.Close()
+	u, err := url.Parse(srv.URL)
+	if err != nil {
+		t.Fatalf("parse url: %v", err)
+	}
+	c.httpHost = u.Host
+
+	if _, err := c.ubusHTTPRpc(strings.Repeat("0", 32), "session", "login", nil); err == nil {
+		t.Fatal("con el HTTP marcado caído la llamada debe devolver error")
+	}
+	if n := hits.Load(); n != 0 {
+		t.Fatalf("el cliente golpeó el puerto web %d veces estando caído, want 0", n)
+	}
+
+	// Gate negativo del test: levantando la ventana el mismo endpoint sí se
+	// golpea, así que el cero anterior es la caché y no un handler mudo.
+	c.mu.Lock()
+	c.ubusHTTPDownUntil = time.Time{}
+	c.mu.Unlock()
+	if _, err := c.ubusHTTPRpc(strings.Repeat("0", 32), "session", "login", nil); err != nil {
+		t.Fatalf("con la ventana levantada la llamada debe funcionar: %v", err)
+	}
+	if n := hits.Load(); n != 1 {
+		t.Fatalf("peticiones al endpoint sano: %d, want 1", n)
+	}
+}
+
+// El camino feliz del transporte sigue intacto: un ubus JSON-RPC válido
+// devuelve el payload y no abre ninguna ventana de indisponibilidad.
+func TestUbusHTTPValidEndpointStillWorks(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/ubus" {
+			t.Errorf("path: %q, want /ubus", r.URL.Path)
+		}
+		_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":[0,{"ok":true}]}`))
+	}))
+	defer srv.Close()
+	u, _ := url.Parse(srv.URL)
+
+	c := &OpenWrtClient{Host: "192.168.1.1:22", httpHost: u.Host}
+	out, err := c.ubusHTTPRpc(strings.Repeat("0", 32), "system", "board", nil)
+	if err != nil {
+		t.Fatalf("ubus HTTP válido: %v", err)
+	}
+	if string(out) != `{"ok":true}` {
+		t.Fatalf("payload: %s", out)
+	}
+	if !c.ubusHTTPReady() {
+		t.Fatal("un endpoint sano no debe abrir la ventana de indisponibilidad")
+	}
+}
+
+// El host sin puerto configurado se resuelve al puerto web incluso si el
+// cliente se construye a mano (los tests y el modo agente no pasan por el
+// constructor).
+func TestUbusURLFallsBackToWebPort(t *testing.T) {
+	c := &OpenWrtClient{Host: "192.168.1.1"}
+	if got := c.ubusURL(); got != "http://"+net.JoinHostPort("192.168.1.1", "80")+"/ubus" {
+		t.Fatalf("ubus URL sin httpHost: %q", got)
+	}
+}