reanchor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. // reanchor.go — recomendaciones de re-anclaje WiFi (issue #403).
  2. //
  3. // El motor prueba primero usteer (daemon preferido) y, si no está disponible,
  4. // recurre a DAWN. Para usteer usa `local_info` + `remote_info` para el
  5. // inventario de APs, `connected_clients` para saber dónde está cada cliente y
  6. // `get_clients` como hearing map. Para DAWN usa `get_network` + `get_hearing_map`.
  7. package adapters
  8. import (
  9. "context"
  10. "encoding/json"
  11. "fmt"
  12. "sort"
  13. "strings"
  14. )
  15. // Umbrales por defecto del re-anclaje: -65 dBm mínimo para el destino y 10 dBm
  16. // de mejora respecto al AP actual.
  17. const (
  18. reanchorMinRecommendedSignal = -65
  19. reanchorMinDeltaDbm = 10
  20. )
  21. // GetReanchorRecommendations devuelve recomendaciones de re-anclaje WiFi.
  22. // Prefiere usteer; si ningún router responde con usteer, prueba DAWN.
  23. func (l *Live) GetReanchorRecommendations(ctx context.Context, cfg ReanchorConfig) ([]ReanchorRecommendation, RoamingDaemon, error) {
  24. l.mu.Lock()
  25. routers := append([]RouterConfig(nil), l.routers...)
  26. l.mu.Unlock()
  27. if cfg.MinRecommendedSignal == 0 {
  28. cfg.MinRecommendedSignal = reanchorMinRecommendedSignal
  29. }
  30. if cfg.MinDeltaDbm == 0 {
  31. cfg.MinDeltaDbm = reanchorMinDeltaDbm
  32. }
  33. if recs, ok := usteerReanchor(ctx, routers, cfg, l.pool); ok {
  34. return recs, RoamingDaemonUsteer, nil
  35. }
  36. if recs, ok := dawnReanchor(ctx, routers, cfg, l.pool); ok {
  37. return recs, RoamingDaemonDawn, nil
  38. }
  39. return []ReanchorRecommendation{}, RoamingDaemonNone, nil
  40. }
  41. // ---------------------------------------------------------------------------
  42. // usteer
  43. // ---------------------------------------------------------------------------
  44. // usteerHearingRaw es una entrada de `ubus call usteer get_clients`:
  45. // { "connected": bool, "signal": int }.
  46. type usteerHearingRaw struct {
  47. Connected bool `json:"connected"`
  48. Signal int `json:"signal"`
  49. }
  50. // usteerAPInfo almacena la metainformación de un AP (local o remoto) para
  51. // convertir el nombre de nodo devuelto por usteer en datos legibles.
  52. type usteerAPInfo struct {
  53. BSSID string
  54. SSID string
  55. Freq int
  56. Hostname string
  57. Iface string
  58. Local bool
  59. Host string // solo para APs locales; SSH host donde ejecutar del_client
  60. }
  61. // usteerReanchor devuelve (recomendaciones, true) si al menos un router responde
  62. // con usteer local_info. Si no hay usteer devuelve (nil, false).
  63. func usteerReanchor(ctx context.Context, routers []RouterConfig, cfg ReanchorConfig, runner sshRunner) ([]ReanchorRecommendation, bool) {
  64. apByNode := make(map[string]usteerAPInfo) // nombre de nodo usteer -> AP
  65. currentByMAC := make(map[string]struct {
  66. node string
  67. signal int
  68. host string
  69. })
  70. hearing := make(map[string]map[string]int) // MAC -> nodo -> mejor señal
  71. found := false
  72. for _, rt := range routers {
  73. if rt.AgentOnly || rt.Host == "" {
  74. continue
  75. }
  76. name := rt.Name
  77. if name == "" {
  78. name = rt.ID
  79. }
  80. // APs locales: nombre de nodo = iface.
  81. localOut, _ := runner.Run(rt.Host, "ubus call usteer local_info", 0)
  82. var local map[string]usteerAPRaw
  83. if err := json.Unmarshal([]byte(localOut), &local); err != nil {
  84. continue
  85. }
  86. if len(local) > 0 {
  87. found = true
  88. }
  89. for iface, raw := range local {
  90. if raw.SSID == "" || raw.BSSID == "" {
  91. continue
  92. }
  93. apByNode[iface] = usteerAPInfo{
  94. BSSID: strings.ToUpper(raw.BSSID),
  95. SSID: raw.SSID,
  96. Freq: raw.Freq,
  97. Hostname: name,
  98. Iface: iface,
  99. Local: true,
  100. Host: rt.Host,
  101. }
  102. }
  103. // APs remotos: nombre de nodo = "IP#iface".
  104. remoteOut, _ := runner.Run(rt.Host, "ubus call usteer remote_info", 0)
  105. var remote map[string]usteerAPRaw
  106. if err := json.Unmarshal([]byte(remoteOut), &remote); err == nil {
  107. for node, raw := range remote {
  108. if raw.SSID == "" || raw.BSSID == "" {
  109. continue
  110. }
  111. if _, exists := apByNode[node]; exists {
  112. continue
  113. }
  114. apByNode[node] = usteerAPInfo{
  115. BSSID: strings.ToUpper(raw.BSSID),
  116. SSID: raw.SSID,
  117. Freq: raw.Freq,
  118. Hostname: usteerRemoteHostname(node, routers, raw.BSSID),
  119. Iface: usteerRemoteIface(node),
  120. Local: false,
  121. }
  122. }
  123. }
  124. // Clientes conectados en este router (solo nodos locales).
  125. clientsOut, _ := runner.Run(rt.Host, "ubus call usteer connected_clients", 0)
  126. var clients map[string]map[string]usteerClientRaw
  127. if err := json.Unmarshal([]byte(clientsOut), &clients); err == nil {
  128. for iface, macs := range clients {
  129. for mac, c := range macs {
  130. if c.Signal >= 0 {
  131. continue
  132. }
  133. mac = strings.ToUpper(mac)
  134. currentByMAC[mac] = struct {
  135. node string
  136. signal int
  137. host string
  138. }{node: iface, signal: c.Signal, host: rt.Host}
  139. }
  140. }
  141. }
  142. // Hearing map global de usteer.
  143. hearOut, _ := runner.Run(rt.Host, "ubus call usteer get_clients", 0)
  144. var hear map[string]map[string]usteerHearingRaw
  145. if err := json.Unmarshal([]byte(hearOut), &hear); err == nil {
  146. for mac, nodes := range hear {
  147. mac = strings.ToUpper(mac)
  148. if hearing[mac] == nil {
  149. hearing[mac] = make(map[string]int)
  150. }
  151. for node, h := range nodes {
  152. if h.Signal >= 0 {
  153. continue
  154. }
  155. if prev, ok := hearing[mac][node]; !ok || h.Signal > prev {
  156. hearing[mac][node] = h.Signal
  157. }
  158. }
  159. }
  160. }
  161. }
  162. if !found {
  163. return nil, false
  164. }
  165. var recs []ReanchorRecommendation
  166. for mac, current := range currentByMAC {
  167. hearMap, ok := hearing[mac]
  168. if !ok {
  169. continue
  170. }
  171. currentAP, ok := apByNode[current.node]
  172. if !ok {
  173. continue
  174. }
  175. var bestNode string
  176. var bestSignal int
  177. for node, signal := range hearMap {
  178. if node == current.node {
  179. continue
  180. }
  181. if bestNode == "" || signal > bestSignal {
  182. bestNode = node
  183. bestSignal = signal
  184. }
  185. }
  186. if bestNode == "" {
  187. continue
  188. }
  189. if bestSignal < cfg.MinRecommendedSignal {
  190. continue
  191. }
  192. if bestSignal-current.signal < cfg.MinDeltaDbm {
  193. continue
  194. }
  195. recommendedAP := apByNode[bestNode]
  196. recs = append(recs, ReanchorRecommendation{
  197. MAC: mac,
  198. CurrentBSSID: currentAP.BSSID,
  199. CurrentHostname: currentAP.Hostname,
  200. CurrentIface: currentAP.Iface,
  201. CurrentHost: current.host,
  202. CurrentSignal: current.signal,
  203. RecommendedBSSID: recommendedAP.BSSID,
  204. RecommendedHostname: recommendedAP.Hostname,
  205. RecommendedIface: recommendedAP.Iface,
  206. RecommendedSignal: bestSignal,
  207. DeltaDbm: bestSignal - current.signal,
  208. })
  209. }
  210. sort.Slice(recs, func(i, j int) bool {
  211. if recs[i].DeltaDbm != recs[j].DeltaDbm {
  212. return recs[i].DeltaDbm > recs[j].DeltaDbm
  213. }
  214. return recs[i].MAC < recs[j].MAC
  215. })
  216. return recs, true
  217. }
  218. // usteerRemoteHostname devuelve un nombre amigable para un nodo remoto. Si el
  219. // prefijo IP coincide con un router conocido, usa su nombre; si no, muestra
  220. // la propia IP.
  221. func usteerRemoteHostname(node string, routers []RouterConfig, bssid string) string {
  222. const sep = "#"
  223. idx := strings.Index(node, sep)
  224. if idx < 0 {
  225. return bssid
  226. }
  227. ip := node[:idx]
  228. for _, r := range routers {
  229. if r.Host == ip {
  230. name := r.Name
  231. if name == "" {
  232. name = r.ID
  233. }
  234. return name
  235. }
  236. }
  237. return ip
  238. }
  239. // usteerRemoteIface extrae la parte de iface del nombre de nodo remoto
  240. // ("IP#iface" -> "iface").
  241. func usteerRemoteIface(node string) string {
  242. const sep = "#"
  243. idx := strings.Index(node, sep)
  244. if idx < 0 {
  245. return node
  246. }
  247. return node[idx+len(sep):]
  248. }
  249. // ---------------------------------------------------------------------------
  250. // DAWN (fallback)
  251. // ---------------------------------------------------------------------------
  252. // DawnNetworkFromHost ejecuta `ubus call dawn get_network` en un host concreto
  253. // y devuelve los APs parseados. Devuelve nil si falla el SSH o el parseo.
  254. func DawnNetworkFromHost(ctx context.Context, host string, runner sshRunner) []DawnAP {
  255. if host == "" {
  256. return nil
  257. }
  258. out, err := runner.Run(host, "ubus call dawn get_network", 0)
  259. if err != nil {
  260. return nil
  261. }
  262. var data map[string]map[string]json.RawMessage
  263. if json.Unmarshal([]byte(out), &data) != nil {
  264. return nil
  265. }
  266. return dawnAPsFromNetwork(data)
  267. }
  268. // DawnHearingMapFromHost ejecuta `ubus call dawn get_hearing_map` en un host
  269. // concreto. Devuelve map[MAC] -> map[BSSID] -> signal. Los MAC y BSSID se
  270. // normalizan a mayúsculas.
  271. func DawnHearingMapFromHost(ctx context.Context, host string, runner sshRunner) map[string]map[string]int {
  272. if host == "" {
  273. return nil
  274. }
  275. out, err := runner.Run(host, "ubus call dawn get_hearing_map", 0)
  276. if err != nil {
  277. return nil
  278. }
  279. return parseDawnHearingMap(out)
  280. }
  281. // parseDawnHearingMap parsea la salida JSON de `ubus call dawn get_hearing_map`.
  282. // Estructura: { SSID: { MAC: { BSSID: { signal, freq, ... } } } }
  283. func parseDawnHearingMap(out string) map[string]map[string]int {
  284. var raw map[string]map[string]map[string]map[string]json.RawMessage
  285. if json.Unmarshal([]byte(out), &raw) != nil {
  286. return nil
  287. }
  288. res := make(map[string]map[string]int)
  289. for _, clients := range raw {
  290. for mac, bssids := range clients {
  291. mac = strings.ToUpper(mac)
  292. if res[mac] == nil {
  293. res[mac] = make(map[string]int)
  294. }
  295. for bssid, fields := range bssids {
  296. bssid = strings.ToUpper(bssid)
  297. signalRaw, ok := fields["signal"]
  298. if !ok {
  299. continue
  300. }
  301. var s int
  302. if json.Unmarshal(signalRaw, &s) != nil {
  303. continue
  304. }
  305. // signal=0 suele significar "no medido"; lo ignoramos.
  306. if s >= 0 {
  307. continue
  308. }
  309. // Quedarse con la mejor señal (mayor valor, -50 > -80).
  310. if prev, ok := res[mac][bssid]; !ok || s > prev {
  311. res[mac][bssid] = s
  312. }
  313. }
  314. }
  315. }
  316. return res
  317. }
  318. // dawnAPsFromNetwork extrae los APs del JSON de `ubus call dawn get_network`.
  319. // Estructura: { SSID: { BSSID: { ... } } }
  320. func dawnAPsFromNetwork(data map[string]map[string]json.RawMessage) []DawnAP {
  321. var aps []DawnAP
  322. for ssid, bssids := range data {
  323. for bssidRaw, raw := range bssids {
  324. bssid := strings.ToUpper(bssidRaw)
  325. var ap dawnAPData
  326. if json.Unmarshal(raw, &ap) != nil {
  327. continue
  328. }
  329. band := "2.4 GHz"
  330. if ap.Freq >= 5000 {
  331. band = "5 GHz"
  332. }
  333. var clients []DawnClient
  334. for mac, c := range ap.Clients {
  335. if c.Signal >= 0 {
  336. continue
  337. }
  338. clients = append(clients, DawnClient{
  339. MAC: strings.ToUpper(mac),
  340. Signal: c.Signal,
  341. HT: c.HT,
  342. VHT: c.VHT,
  343. })
  344. }
  345. sort.Slice(clients, func(i, j int) bool { return clients[i].MAC < clients[j].MAC })
  346. aps = append(aps, DawnAP{
  347. SSID: ssid,
  348. BSSID: bssid,
  349. Hostname: ap.Hostname,
  350. Band: band,
  351. Channel: ap.Channel,
  352. UtilizationPct: ap.UtilizationPct,
  353. ClientCount: ap.ClientCount,
  354. Clients: clients,
  355. Local: ap.Local,
  356. Iface: ap.Iface,
  357. })
  358. }
  359. }
  360. return aps
  361. }
  362. // dawnAPData es la forma interna de un AP en `get_network`.
  363. type dawnAPData struct {
  364. Hostname string `json:"hostname"`
  365. Freq int `json:"freq"`
  366. Channel int `json:"channel"`
  367. UtilizationPct float64 `json:"utilization"`
  368. ClientCount int `json:"num_sta"`
  369. Clients map[string]dawnClientData `json:"clients"`
  370. Local bool `json:"local"`
  371. Iface string `json:"iface"`
  372. }
  373. type dawnClientData struct {
  374. Signal int `json:"signal"`
  375. HT bool `json:"ht"`
  376. VHT bool `json:"vht"`
  377. }
  378. // dawnReanchor devuelve (recomendaciones, true) si al menos un router responde
  379. // con DAWN. Si no hay DAWN devuelve (nil, false).
  380. func dawnReanchor(ctx context.Context, routers []RouterConfig, cfg ReanchorConfig, runner sshRunner) ([]ReanchorRecommendation, bool) {
  381. apByBSSID := make(map[string]DawnAP)
  382. currentByMAC := make(map[string]struct {
  383. bssid string
  384. signal int
  385. host string
  386. })
  387. hearing := make(map[string]map[string]int)
  388. found := false
  389. for _, rt := range routers {
  390. if rt.AgentOnly || rt.Host == "" {
  391. continue
  392. }
  393. aps := DawnNetworkFromHost(ctx, rt.Host, runner)
  394. if len(aps) > 0 {
  395. found = true
  396. }
  397. for _, ap := range aps {
  398. ap.BSSID = strings.ToUpper(ap.BSSID)
  399. if _, exists := apByBSSID[ap.BSSID]; !exists {
  400. apByBSSID[ap.BSSID] = ap
  401. }
  402. if !ap.Local {
  403. continue
  404. }
  405. for _, c := range ap.Clients {
  406. c.MAC = strings.ToUpper(c.MAC)
  407. currentByMAC[c.MAC] = struct {
  408. bssid string
  409. signal int
  410. host string
  411. }{bssid: ap.BSSID, signal: c.Signal, host: rt.Host}
  412. }
  413. }
  414. hm := DawnHearingMapFromHost(ctx, rt.Host, runner)
  415. for mac, bssids := range hm {
  416. if hearing[mac] == nil {
  417. hearing[mac] = make(map[string]int)
  418. }
  419. for bssid, signal := range bssids {
  420. if prev, ok := hearing[mac][bssid]; !ok || signal > prev {
  421. hearing[mac][bssid] = signal
  422. }
  423. }
  424. }
  425. }
  426. if !found {
  427. return nil, false
  428. }
  429. var recs []ReanchorRecommendation
  430. for mac, current := range currentByMAC {
  431. hearingMap, ok := hearing[mac]
  432. if !ok {
  433. continue
  434. }
  435. currentAP := apByBSSID[current.bssid]
  436. var bestBSSID string
  437. var bestSignal int
  438. for bssid, signal := range hearingMap {
  439. if bssid == current.bssid {
  440. continue
  441. }
  442. if bestBSSID == "" || signal > bestSignal {
  443. bestBSSID = bssid
  444. bestSignal = signal
  445. }
  446. }
  447. if bestBSSID == "" {
  448. continue
  449. }
  450. if bestSignal < cfg.MinRecommendedSignal {
  451. continue
  452. }
  453. if bestSignal-current.signal < cfg.MinDeltaDbm {
  454. continue
  455. }
  456. recommendedAP := apByBSSID[bestBSSID]
  457. recs = append(recs, ReanchorRecommendation{
  458. MAC: mac,
  459. CurrentBSSID: current.bssid,
  460. CurrentHostname: currentAP.Hostname,
  461. CurrentIface: currentAP.Iface,
  462. CurrentHost: current.host,
  463. CurrentSignal: current.signal,
  464. RecommendedBSSID: bestBSSID,
  465. RecommendedHostname: recommendedAP.Hostname,
  466. RecommendedIface: recommendedAP.Iface,
  467. RecommendedSignal: bestSignal,
  468. DeltaDbm: bestSignal - current.signal,
  469. })
  470. }
  471. sort.Slice(recs, func(i, j int) bool {
  472. if recs[i].DeltaDbm != recs[j].DeltaDbm {
  473. return recs[i].DeltaDbm > recs[j].DeltaDbm
  474. }
  475. return recs[i].MAC < recs[j].MAC
  476. })
  477. return recs, true
  478. }
  479. // ReanchorKickScript genera el comando hostapd del_client para expulsar a un
  480. // cliente de un AP. Se ejecuta en el host donde está el AP actual (DAWN).
  481. func ReanchorKickScript(mac string, iface string) string {
  482. mac = strings.ToUpper(mac)
  483. return fmt.Sprintf("ubus call hostapd.%s del_client '{\"addr\":\"%s\",\"reason\":5,\"deauth\":true,\"ban_time\":120000}'",
  484. iface, mac)
  485. }