package routers
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
"unicode"
)
var errAccess = errors.New("access_required")
var errProtocol = errors.New("unsupported_response")
var errLink = errors.New("local_link_changed")
type api struct {
client *http.Client
base string
check func() bool
}
func newAPI(c Candidate) *api {
jar, _ := cookiejar.New(nil)
return &api{base: "http://" + c.Address + "/cgi-bin/", check: func() bool {
return c.MAC == "" || neighbor(c.Interface, c.Address) == c.MAC
}, client: &http.Client{
Timeout: 35 * time.Second, Jar: jar,
CheckRedirect: func(*http.Request, []*http.Request) error { return errProtocol },
Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true, MaxResponseHeaderBytes: 16384,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
local, ok := onLink(c.Interface, c.Address)
if !ok || local != c.LocalIP || address != net.JoinHostPort(c.Address, "80") {
return nil, errLink
}
var selected []route
if !commandJSON(ctx, []string{"-j", "-4", "route", "get", c.Address}, &selected) || len(selected) != 1 || selected[0].Dev != c.Interface || selected[0].Gateway != "" {
return nil, errLink
}
return (&net.Dialer{Timeout: time.Second, LocalAddr: &net.TCPAddr{IP: net.ParseIP(c.LocalIP)}}).DialContext(ctx, network, address)
}},
}}
}
func (a *api) request(ctx context.Context, path string, form url.Values) ([]byte, error) {
budget := 2 * time.Second
if path == "dexaflow_status" {
// The firmware gathers modem statistics synchronously (observed 3.8 s).
// Keep discovery/login fast while allowing this bounded read to finish.
budget = 8 * time.Second
}
if form != nil && path == "dexaflow_manual" {
budget = 30 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, budget)
defer cancel()
if !a.check() {
return nil, errLink
}
method := http.MethodGet
var body io.Reader
if form != nil {
method = http.MethodPost
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, a.base+path, body)
if err != nil {
return nil, errProtocol
}
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
response, err := a.client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode == 401 || response.StatusCode == 403 {
return nil, errAccess
}
if response.StatusCode != 200 {
return nil, errProtocol
}
data, err := io.ReadAll(io.LimitReader(response.Body, 262145))
if err != nil {
return nil, err
}
if len(data) > 262144 {
return nil, errProtocol
}
return data, nil
}
func (a *api) family(ctx context.Context) bool {
data, err := a.request(ctx, "luci/dexaflow", nil)
return err == nil && familyPage(string(data))
}
func familyPage(page string) bool {
page = strings.ToLower(page)
if !strings.Contains(page, "
dexaflow") {
return false
}
if strings.Contains(page, "/dexaflow/app.js") {
return true
}
// An unauthenticated gateway serves a separate login page without app.js.
// Identify that page before asking the operator for credentials; discovery
// itself must never try a password. This is a family marker, not attestation.
return strings.Contains(page, "dexaflow dashboard") &&
strings.Contains(page, "'/cgi-bin/dexaflow_auth'") &&
strings.Contains(page, "action:'login'") &&
strings.Contains(page, `name="user"`) &&
strings.Contains(page, `name="password"`)
}
func (a *api) json(ctx context.Context, path string, form url.Values) (map[string]any, error) {
data, err := a.request(ctx, path, form)
if err != nil {
return nil, err
}
var value map[string]any
if json.Unmarshal(data, &value) != nil || value == nil {
return nil, errProtocol
}
if value["ok"] == false {
return nil, errAccess
}
return value, nil
}
func (a *api) login(ctx context.Context, c credential) error {
result, err := a.json(ctx, "dexaflow_auth", url.Values{"action": {"login"}, "user": {c.Username}, "password": {c.Password}})
if err != nil {
return err
}
if result["ok"] != true {
return errAccess
}
return nil
}
// Explicit allowlists keep raw router responses, identifiers and credentials
// out of heartbeat payloads and incident history. Missing is never zero.
func text(v any) string {
s, ok := v.(string)
if !ok || len(s) > 128 {
return ""
}
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func number(v any, low, high float64) *float64 {
f, ok := v.(float64)
if !ok || math.IsNaN(f) || math.IsInf(f, 0) || f < low || f > high {
return nil
}
return &f
}
func bandwidth(v any) *float64 {
// This firmware reports bandwidth as decimal text, unlike RSRP and PCI.
if s, ok := v.(string); ok {
if len(s) == 0 || len(s) > 16 {
return nil
}
parsed, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil
}
v = parsed
}
return number(v, 0, 1000)
}
func boolean(v any) *bool {
b, ok := v.(bool)
if !ok {
return nil
}
return &b
}
func ip(v any) string {
p := net.ParseIP(text(v))
if p == nil {
return ""
}
return p.String()
}
func mode(v any) string {
s := text(v)
switch s {
case "direct", "aggregation", "proxy", "whitelist", "vpn", "auto", "off", "glue", "vpnone":
return s
}
return ""
}
func normalize(status, manual, internet, me map[string]any) (Device, error) {
modems, ok := status["modems"].([]any)
if !ok || len(modems) > 3 {
return Device{}, errProtocol
}
d := Device{Family: "DexaFlow", Identity: "local_mac", State: "ready", Internet: "unknown", Modems: []Modem{},
Firmware: text(me["firmware"]), Uptime: number(status["uptime"], 0, 1e12),
SelectedMode: mode(internet["selected"]), ActiveMode: mode(internet["active"]),
ManualMode: mode(manual["mode"]), ActiveSlots: manualSlots(manual), PersistedMode: mode(manual["persist"]), RebootResets: boolean(manual["reboot_resets"]), ActiveWAN: text(manual["wan"]),
VPSUp: boolean(status["vps_up"]), RTT: number(status["ping"], 0, 60000),
DownKbps: number(status["dl_kbps"], 0, 1e9), UpKbps: number(status["ul_kbps"], 0, 1e9)}
// The vendor separates the selected policy, observed path and verification.
// An IP string or responsive LAN alone does not establish Internet access.
verified := internet["stale"] == false && ((d.ActiveMode == "aggregation" && internet["aggregate_verified"] == true) || (d.ActiveMode == "vpn" && internet["vpn_verified"] == true))
if d.ActiveMode == "direct" && internet["stale"] == false {
if sims, ok := internet["sims"].([]any); ok {
for _, v := range sims {
if s, ok := v.(map[string]any); ok {
for slot := 1; slot <= 3; slot++ {
if d.ActiveWAN == fmt.Sprintf("wan%d", slot) && s["slot"] == fmt.Sprintf("M%d", slot) && s["state"] == "ok" && (s["cloudflare"] == true || s["google"] == true || s["kernel"] == true) {
verified = true
}
}
}
}
}
}
if verified {
d.Internet = "verified"
}
if status["public_ip_stale"] == false && text(status["public_ip_via"]) == d.ActiveMode && verified {
d.PublicIP = ip(status["public_ip"])
}
seen := map[int]bool{}
for _, raw := range modems {
m, ok := raw.(map[string]any)
if !ok {
return Device{}, errProtocol
}
slot := number(m["slot"], 1, 3)
if slot == nil || *slot != math.Trunc(*slot) || seen[int(*slot)] {
return Device{}, errProtocol
}
seen[int(*slot)] = true
d.Modems = append(d.Modems, Modem{Slot: int(*slot), Operator: text(m["operator"]), Connectivity: text(m["connectivity"]), Radio: text(m["radio"]), IP: ip(m["ip"]), Technology: text(m["tech"]), Band: text(m["band"]), Bandwidth: bandwidth(m["bandwidth"]),
RSRP: number(m["rsrp"], -160, -20), RSRQ: number(m["rsrq"], -50, 20), SINR: number(m["sinr"], -40, 60), RSSI: number(m["rssi"], -160, 0), CellID: text(m["cell_id"]), PCI: number(m["pci"], 0, 1007), DownKbps: number(m["dl"], 0, 1e9), UpKbps: number(m["ul"], 0, 1e9)})
}
applyInventory(&d, status)
return d, nil
}
func (a *api) read(ctx context.Context) (Device, error) {
s, err := a.json(ctx, "dexaflow_status", nil)
if err != nil {
return Device{}, err
}
m, err := a.json(ctx, "dexaflow_manual", nil)
if err != nil {
return Device{}, err
}
i, err := a.json(ctx, "dexaflow_internet", nil)
if err != nil {
return Device{}, err
}
me, err := a.json(ctx, "dexaflow_auth?action=me", nil)
if err != nil {
return Device{}, err
}
return normalize(s, m, i, me)
}