Files
nanopsx/firmware/components/http_portal/src/http_portal.c
T

684 lines
26 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// File: src/http_portal.c
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_http_server.h"
#include "esp_netif.h"
#include "http_portal.h"
#include "storage.h"
static portal_http_callbacks_t s_cb;
static void __attribute__((unused)) log_one_hdr(httpd_req_t *req, const char* key) {
size_t len = httpd_req_get_hdr_value_len(req, key);
if (len == 0) return;
if (len < 1024) {
char *val = calloc(1, len + 1);
if (val && httpd_req_get_hdr_value_str(req, key, val, len + 1) == ESP_OK) {
ESP_LOGI("portal_http", " H %s (%u): %s", key, (unsigned)len, val);
} else {
ESP_LOGI("portal_http", " H %s (%u): <alloc/get failed>", key, (unsigned)len);
}
free(val);
} else {
ESP_LOGI("portal_http", " H %s LEN=%u (too long to print)", key, (unsigned)len);
}
}
static const char *TAG = "portal_http";
static httpd_handle_t s_http = NULL;
static EventGroupHandle_t s_wifi_events = NULL;
static EventBits_t s_BIT_GOTIP = 0;
static EventBits_t s_BIT_FAIL = 0;
static char s_ap_ssid[33] = {0};
static bool s_force_captive = true; // true = Portal immer zeigen
// === Neue, feste Limits ===
#define MAX_SSID_BYTES 32 // IEEE 802.11
#define MIN_PASS_CHARS 8 // WPA2/3 Passphrase
#define MAX_PASS_CHARS 63 // WPA2/3 Passphrase (nicht PSK)
#define PSK_HEX_LEN 64 // 64-stellige Hex-PSK
#define MAX_TOKEN_CHARS 256 // groß genug (88 Beispiel + Reserve)
#define MAX_DEV_CHARS 63
#define MAX_BUCKET_CHARS 128
#define MAX_ORG_CHARS 128
#define MAX_FORM_BYTES 16384 // max. Bodygröße akzeptieren
// --- Logging helpers ---
static const char* method_str(httpd_method_t m) {
switch (m) {
case HTTP_GET: return "GET";
case HTTP_POST: return "POST";
case HTTP_PUT: return "PUT";
case HTTP_DELETE: return "DELETE";
case HTTP_HEAD: return "HEAD";
default: return "?";
}
}
static void log_req_basic(httpd_req_t *req, const char* where) {
ESP_LOGI("portal_http", "[%s] %s %s", where, method_str(req->method), req->uri);
// Einige typische Header auslesen (nur wenn vorhanden)
const char* keys[] = { "Host", "User-Agent", "Accept", "Accept-Language", "Connection" };
for (size_t i = 0; i < sizeof(keys)/sizeof(keys[0]); ++i) {
size_t len = httpd_req_get_hdr_value_len(req, keys[i]);
if (len > 0 && len < 512) {
char *val = calloc(1, len + 1);
if (val) {
if (httpd_req_get_hdr_value_str(req, keys[i], val, len + 1) == ESP_OK) {
ESP_LOGI("portal_http", " H %s: %s", keys[i], val);
}
free(val);
}
}
}
}
static void log_resp_basic(const char* where, const char* status, const char* type, int content_len) {
ESP_LOGI("portal_http", "[%s] RESP %s, type=%s, len=%d", where, status ? status : "?", type ? type : "?", content_len);
}
// ---------- Helfer ----------
static char* html_escape(const char* s) {
if (!s) return strdup("");
size_t len = 0;
for (const char* p = s; *p; ++p) {
switch(*p){ case '&': len+=5; break; case '<': case '>': len+=4; break; case '"': case '\'': len+=6; break; default: len+=1; }
}
char* out = (char*)malloc(len+1); if(!out) return NULL;
char* o = out;
for (const char* p = s; *p; ++p) {
switch(*p){
case '&': memcpy(o,"&amp;",5); o+=5; break;
case '<': memcpy(o,"&lt;",4); o+=4; break;
case '>': memcpy(o,"&gt;",4); o+=4; break;
case '"': memcpy(o,"&quot;",6);o+=6; break;
case '\'':memcpy(o,"&#39;",5); o+=5; break;
default: *o++ = *p;
}
}
*o = '\0';
return out;
}
// Sehr simpler JSON-Escape (für SSIDs in /scan)
static void json_escape(const char* in, char* out, size_t outlen) {
size_t j = 0;
for (size_t i = 0; in && in[i] && j + 2 < outlen; ++i) {
unsigned char c = (unsigned char)in[i];
if (c == '"' || c == '\\') {
if (j + 2 < outlen) { out[j++]='\\'; out[j++]=c; }
} else if (c <= 0x1F) {
if (j + 6 < outlen) {
j += (size_t)snprintf(out + j, outlen - j, "\\u%04x", c);
} else break;
} else {
out[j++] = (char)c;
}
}
out[j] = '\0';
}
// === Neue kleine Helfer ===
static inline bool is_hex(char c){
return (c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F');
}
static bool is_hex_string(const char* s, size_t n){
for(size_t i=0;i<n;i++) if(!is_hex(s[i])) return false;
return true;
}
static char* dup_with_limit(const char* s, size_t max){
size_t n = strnlen(s, max + 1);
if (n > max) return NULL;
char* r = (char*)malloc(n + 1);
if (!r) return NULL;
memcpy(r, s, n); r[n] = '\0';
return r;
}
// ---------- HTML (mit Platzhalter) ----------
static const char form_html_tpl[] =
"<!doctype html><html><head><meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
"<title>Wi-Fi Setup</title>"
"<style>body{font-family:system-ui,Arial;margin:2rem;line-height:1.4}"
"label{display:block;margin-top:1rem}input,select{padding:.5rem;width:100%%;max-width:28rem}"
"button{margin-top:1rem;padding:.6rem 1rem;border:0;border-radius:.6rem;background:#0b6cff;color:#fff;}"
".card{max-width:32rem;padding:1rem 1.25rem;border:1px solid #e5e5e5;border-radius:1rem;box-shadow:0 2px 10px rgba(0,0,0,.04)}"
".row{display:flex;gap:.5rem;align-items:center;max-width:28rem}"
".muted{color:#666;font-size:.9em}</style>"
"</head><body><div class='card'>"
"<h1>Wi-Fi Configuration</h1>"
"<p>Connected to <b>%s</b>. Choose your Wi-Fi network or enter it manually:</p>"
"<div class='row'><select id='nets'></select><button id='refresh' type='button'>Refresh</button></div>"
"<form method='POST' action='/save'>"
"<label>SSID*<input id='ssid' name='ssid' required maxlength='32'></label>"
"<label>Password*<input name='pass' type='password' required minlength='8' maxlength='63' pattern='.{8,63}|[0-9A-Fa-f]{64}'></label>"
"<label>Device Name*<input id='dev' name='dev' required value='%s' maxlength='63' placeholder=''></label>"
"<label>Organization (optional)<input id='org' name='org' placeholder='' value='%s' maxlength='128'></label>"
"<label>Bucket (optional)<input id='bucket' name='bucket' placeholder='' value='%s' maxlength='128'></label>"
"<label>Token<input id='token' name='token' placeholder='' maxlength='256'></label>"
"<button type='submit'>Save & Connect</button>"
"</form>"
"<p class='muted'>After saving, the device will connect to your Wi-Fi network. "
"The access point will automatically shut down shortly afterward.</p>"
"</div>"
"<script>"
"async function load(){try{"
" let r=await fetch('/scan'); if(!r.ok) throw 0; let a=await r.json();"
" let s=document.getElementById('nets'); s.innerHTML='';"
" a.sort((x,y)=>y.rssi-x.rssi);"
" a.forEach(n=>{let o=document.createElement('option');"
" o.value=n.ssid; o.textContent=n.ssid+' ('+n.rssi+' dBm)'; s.appendChild(o);});"
" if(a.length && !document.getElementById('ssid').value){"
" document.getElementById('ssid').value=a[0].ssid;}"
"}catch(e){console.log(e);}}"
"document.getElementById('refresh').onclick=load;"
"document.getElementById('nets').onchange=function(){document.getElementById('ssid').value=this.value;};"
"load();"
"</script>"
"</body></html>";
static const char saved_html[] =
"<!doctype html><html><head><meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
"<title>Saved</title></head><body>"
"<h1>✔️ Saved</h1>"
"<p>The credentials have been saved. The device is now connecting to your Wi-Fi…</p>"
"<script>setTimeout(()=>location.href='/status',1500)</script>"
"</body></html>";
static const char status_tpl[] =
"<!doctype html><html><head><meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
"<title>Status</title>"
"<style>body{font-family:system-ui,Arial;margin:2rem} .ok{color:#0a0} .err{color:#b00} .muted{color:#666}</style>"
"</head><body>"
"<h1>Connection Status</h1>"
"<p id='msg' class='muted'>⏳ Connecting...</p>"
"<p><a href='/'>Back</a></p>"
"<script>"
"async function poll(){"
" try{"
" const r = await fetch('/status.json',{cache:'no-store'});"
" if(!r.ok) throw 0; const j = await r.json();"
" const m = document.getElementById('msg');"
" if(j.state==='got_ip'){ m.textContent='✅ Connected'+(j.ip?(' (IP '+j.ip+')'):''); m.className='ok'; return; }"
" if(j.state==='fail'){ m.textContent='❌ Connection failed. Please check your data.'; m.className='err'; return; }"
" m.textContent='⏳ Connecting...'; m.className='muted';"
" }catch(e){ /* ignore */ }"
" setTimeout(poll, 1000);"
"}"
"poll();"
"</script>"
"</body></html>";
// ---------- sehr simpler URL-Decoder ----------
static int hexval(char c){ if(c>='0'&&c<='9')return c-'0'; if(c>='a'&&c<='f')return 10+c-'a'; if(c>='A'&&c<='F')return 10+c-'A'; return -1; }
static void urldecode(char* s){
char* o = s;
for (char* i = s; *i; ++i) {
if (*i == '+') { *o++ = ' '; }
else if (*i == '%' && i[1] && i[2]) {
int h1 = hexval(i[1]), h2 = hexval(i[2]);
if (h1 >= 0 && h2 >= 0) { *o++ = (char)((h1<<4)|h2); i += 2; }
else { *o++ = *i; } // ungültiges %, unverändert übernehmen
} else { *o++ = *i; }
}
*o = '\0';
}
// ---------- HTTP-Handler ----------
static esp_err_t root_get(httpd_req_t *req) {
// 1) Effektive Influx-Werte laden (fällt auf Defaults zurück)
log_req_basic(req, "root_get");
char *org = NULL, *bucket = NULL, *token = NULL;
if (!storage_get_effective_influx(&org, &bucket, &token)) {
org = strdup("");
bucket = strdup("");
token = strdup("");
if (!org || !bucket || !token) {
if (org) free(org);
if (bucket) free(bucket);
if (token) free(token);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
}
}
// 2) Effektiven Devicenamen laden (fällt intern auf DEFAULT_DEVNAME zurück)
char *dev_raw = NULL;
if (!storage_get_effective_device_name(&dev_raw)) {
dev_raw = strdup("");
if (!dev_raw) {
free(org); free(bucket); free(token);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
}
}
// 3) HTML-escaping
char *dev_esc = html_escape(dev_raw);
char *org_esc = html_escape(org ? org : "");
char *bucket_esc = html_escape(bucket ? bucket : "");
char *ap_esc = html_escape(s_ap_ssid); // NEU: AP-SSID escapen
if (!dev_esc || !org_esc || !bucket_esc || !ap_esc) {
if (dev_esc) free(dev_esc);
if (org_esc) free(org_esc);
if (bucket_esc) free(bucket_esc);
if (ap_esc) free(ap_esc);
free(org);
free(bucket);
free(token);
free(dev_raw);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
}
// 4) Seite rendern
int need = snprintf(NULL, 0, form_html_tpl, ap_esc, dev_esc, org_esc, bucket_esc);
if (need < 0) {
free(org); free(bucket); free(token); free(dev_raw);
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "format error");
}
char *page = (char*)malloc((size_t)need + 1);
if (!page) {
free(org); free(bucket); free(token); free(dev_raw);
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
}
snprintf(page, (size_t)need + 1, form_html_tpl, ap_esc, dev_esc, org_esc, bucket_esc);
httpd_resp_set_type(req, "text/html; charset=utf-8");
httpd_resp_set_hdr(req, "Connection", "close");
log_resp_basic("root_get", "200 OK", "text/html; charset=utf-8", need);
esp_err_t r = httpd_resp_send(req, page, HTTPD_RESP_USE_STRLEN);
// 5) Cleanup
free(page);
free(org); free(bucket); free(token);
free(dev_raw);
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
return r;
}
// Captive-Portal Endpunkte (Apple, Android, Windows)
static void get_ap_ip_str(char ipstr[16]) {
ipstr[0] = '\0';
esp_netif_t *ap = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
if (!ap) return;
esp_netif_ip_info_t ip;
if (esp_netif_get_ip_info(ap, &ip) == ESP_OK) {
snprintf(ipstr, 16, IPSTR, IP2STR(&ip.ip));
}
}
static esp_err_t captive_ok(httpd_req_t *req) {
log_req_basic(req, "captive_ok");
// Wenn wir nicht mehr "erzwingen" und STA schon online ist -> 204 (schließt Captive auf dem Handy)
if (!s_force_captive) {
EventBits_t bits = xEventGroupGetBits(s_wifi_events);
if (bits & s_BIT_GOTIP) {
httpd_resp_set_status(req, "204 No Content");
httpd_resp_set_type(req, "text/plain");
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
log_resp_basic("captive_ok", "204 No Content", "text/plain", 0);
return httpd_resp_send(req, NULL, 0);
}
}
// >>> WICHTIG: Für Android/Apple/Windows lieber ein 302-Redirect auf das Portal
char ipstr[16]; get_ap_ip_str(ipstr);
char loc[64];
if (ipstr[0]) snprintf(loc, sizeof(loc), "http://%s/", ipstr);
else snprintf(loc, sizeof(loc), "/");
httpd_resp_set_status(req, "302 Found");
httpd_resp_set_hdr(req, "Location", loc); // absolute URL ist am sichersten für manche ROMs
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
// KEIN Body → Content-Length: 0
log_resp_basic("captive_ok", "302 Found", "redirect", 0);
return httpd_resp_send(req, NULL, 0);
}
static esp_err_t status_get(httpd_req_t *req) {
log_req_basic(req, "status_get");
// Kein Formatieren nötig – Template enthält keine %s
httpd_resp_set_type(req, "text/html; charset=utf-8");
httpd_resp_set_hdr(req, "Connection", "close");
int len = (int)strlen(status_tpl);
log_resp_basic("status_get", "200 OK", "text/html; charset=utf-8", len);
return httpd_resp_send(req, status_tpl, HTTPD_RESP_USE_STRLEN);
}
static esp_err_t favicon_get(httpd_req_t *req) {
httpd_resp_set_status(req, "204 No Content");
httpd_resp_set_type(req, "image/x-icon");
httpd_resp_set_hdr(req, "Connection", "close");
return httpd_resp_send(req, NULL, 0);
}
static esp_err_t save_post(httpd_req_t *req) {
log_req_basic(req, "save_post");
ESP_LOGI("portal_http", "[save_post] content_len (req->content_len) = %d", (int)req->content_len);
// Body vollständig lesen (ggf. in mehreren recv-Aufrufen)
size_t content_len = (size_t)req->content_len;
// Hartes Limit (gegen OOM/DoS)
if (content_len == 0 || content_len > MAX_FORM_BYTES) {
httpd_resp_set_status(req, "413 Request Entity Too Large");
httpd_resp_set_type(req, "text/plain; charset=utf-8");
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_send(req, "payload too large", HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
char *buf = (char*)calloc(1, content_len + 1);
if (!buf) return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
size_t received = 0;
while (received < content_len) {
int r = httpd_req_recv(req, buf + received, content_len - received);
if (r == HTTPD_SOCK_ERR_TIMEOUT) continue; // nochmal versuchen
if (r <= 0) { free(buf); return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "recv fail"); }
received += (size_t)r;
}
buf[received] = '\0';
// ssid=...&pass=...&dev=...&token=...&bucket=...&org=...
char *ssid = NULL, *pass = NULL, *dev = NULL, *token = NULL, *bucket = NULL, *org = NULL;
// Wir parsen in-place
char *p = buf;
while (p && *p) {
char *key = p;
char *eq = strchr(key, '=');
if (!eq) break;
*eq = 0;
char *val = eq + 1;
char *amp = strchr(val, '&');
if (amp) { *amp = 0; p = amp + 1; } else p = NULL;
urldecode(val);
if (!strcmp(key, "ssid")) { ssid = dup_with_limit(val, MAX_SSID_BYTES); }
else if (!strcmp(key, "pass")) { pass = strdup(val); } // validieren wir später
else if (!strcmp(key, "dev")) { dev = dup_with_limit(val, MAX_DEV_CHARS); }
else if (!strcmp(key, "token")){ token = dup_with_limit(val, MAX_TOKEN_CHARS); }
else if (!strcmp(key, "bucket")){bucket = dup_with_limit(val, MAX_BUCKET_CHARS); }
else if (!strcmp(key, "org")) { org = dup_with_limit(val, MAX_ORG_CHARS); }
}
free(buf);
// Pflichtfelder prüfen + Längen/Format validieren
if (!ssid || !pass || !dev || dev[0] == '\0') {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing ssid/pass/dev or invalid length");
goto cleanup_bad;
}
if (strlen(ssid) == 0 || strlen(ssid) > MAX_SSID_BYTES) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "SSID too long (max 32 bytes)");
goto cleanup_bad;
}
size_t pn = strlen(pass);
if (!((pn >= MIN_PASS_CHARS && pn <= MAX_PASS_CHARS) || (pn == PSK_HEX_LEN && is_hex_string(pass, pn)))) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Password must be 8-63 chars or 64 hex");
goto cleanup_bad;
}
if (token && strlen(token) > MAX_TOKEN_CHARS) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Token too long");
goto cleanup_bad;
}
// Seite sofort senden (UI reagiert schnell)
httpd_resp_set_type(req, "text/html; charset=utf-8");
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
log_resp_basic("save_post", "200 OK", "text/html; charset=utf-8", (int)strlen(saved_html));
httpd_resp_send(req, saved_html, HTTPD_RESP_USE_STRLEN);
// Geräteeigenschaften speichern (über Callback)
if (s_cb.save_device_info) {
s_cb.save_device_info(
dev,
(token && token[0]) ? token : NULL, // NULL = nicht geändert
(bucket && bucket[0]) ? bucket : NULL,
(org && org[0]) ? org : NULL
);
}
// STA-Creds speichern & reconnect (über Callback)
if (s_cb.save_sta_creds_and_reconnect) {
s_cb.save_sta_creds_and_reconnect(ssid, pass);
}
s_force_captive = false; // Captive beenden; OS darf 204 sehen
// Cleanup (Erfolgsweg)
free(ssid); free(pass); free(dev);
if (token) free(token);
if (bucket) free(bucket);
if (org) free(org);
return ESP_OK;
cleanup_bad:
if (ssid) free(ssid);
if (pass) free(pass);
if (dev) free(dev);
if (token) free(token);
if (bucket) free(bucket);
if (org) free(org);
return ESP_OK;
}
// Hilfsfunktion: sicherstellen, dass STA-Scan erlaubt ist (AP|STA)
static esp_err_t ensure_scan_capable_mode(void) {
wifi_mode_t m = WIFI_MODE_NULL;
esp_err_t er = esp_wifi_get_mode(&m);
if (er != ESP_OK) return er;
if (m == WIFI_MODE_STA || m == WIFI_MODE_APSTA) return ESP_OK;
// Wenn nur AP aktiv ist → auf APSTA erweitern, damit Scans möglich sind
if (m == WIFI_MODE_AP) {
return esp_wifi_set_mode(WIFI_MODE_APSTA);
}
// Falls NULL oder anderes: versuche sicherheitshalber APSTA
return esp_wifi_set_mode(WIFI_MODE_APSTA);
}
static esp_err_t scan_get(httpd_req_t *req) {
log_req_basic(req, "scan_get");
httpd_resp_set_type(req, "application/json; charset=utf-8");
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
// 0) Mode sicherstellen (damit Scan im AP-Portal funktioniert)
esp_err_t er = ensure_scan_capable_mode();
if (er != ESP_OK) {
const char *msg = "{\"error\":\"wifi mode not scan-capable\",\"code\":1}";
return httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
}
// 1) Scan-Konfig
wifi_scan_config_t cfg = {
.ssid = NULL, .bssid = NULL,
.channel = 0, .show_hidden = false,
.scan_type = WIFI_SCAN_TYPE_ACTIVE,
.scan_time = { .active = { .min = 100, .max = 300 } }
};
// 2) Scan starten – bei Busy kurz retryen
const int max_attempts = 5;
int attempt = 0;
while ((er = esp_wifi_scan_start(&cfg, true)) == ESP_ERR_WIFI_STATE && attempt < max_attempts) {
vTaskDelay(pdMS_TO_TICKS(150)); // 150 ms warten und erneut
attempt++;
}
if (er != ESP_OK) {
ESP_LOGW("portal_http", "[scan_get] scan_start failed: %d", (int)er);
const char *msg = "{\"error\":\"scan start failed\",\"code\":2}";
return httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
}
// 3) Ergebnisse
uint16_t num = 0;
esp_wifi_scan_get_ap_num(&num);
ESP_LOGI("portal_http", "[scan_get] found %u APs", (unsigned)num);
if (num == 0) {
return httpd_resp_send(req, "[]", 2);
}
wifi_ap_record_t *recs = (wifi_ap_record_t*)calloc(num, sizeof(wifi_ap_record_t));
if (!recs) return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
esp_wifi_scan_get_ap_records(&num, recs);
httpd_resp_sendstr_chunk(req, "[");
int emitted = 0;
for (uint16_t i = 0; i < num; ++i) {
if (recs[i].ssid[0] == '\0') continue; // hidden skip
char ssid_esc[96];
json_escape((char*)recs[i].ssid, ssid_esc, sizeof(ssid_esc));
char line[320]; // etwas größer
// authmode als int ausgeben, wie zuvor
snprintf(line, sizeof(line),
"%s{\"ssid\":\"%s\",\"rssi\":%d,\"auth\":%d}",
(emitted ? "," : ""),
ssid_esc, recs[i].rssi, recs[i].authmode);
httpd_resp_sendstr_chunk(req, line);
emitted++;
if (emitted >= 25) break; // Liste begrenzen
}
httpd_resp_sendstr_chunk(req, "]");
httpd_resp_sendstr_chunk(req, NULL);
free(recs);
return ESP_OK;
}
static esp_err_t not_found_handler(httpd_req_t *req, httpd_err_code_t err) {
log_req_basic(req, "404_redirect");
char ipstr[16]; get_ap_ip_str(ipstr);
char loc[64];
if (ipstr[0]) snprintf(loc, sizeof(loc), "http://%s/", ipstr);
else snprintf(loc, sizeof(loc), "/");
httpd_resp_set_status(req, "302 Found");
httpd_resp_set_hdr(req, "Location", loc);
httpd_resp_set_hdr(req, "Connection", "close");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
log_resp_basic("404_redirect", "302 Found", "redirect", 0);
return httpd_resp_send(req, NULL, 0);
}
static esp_err_t status_json_get(httpd_req_t *req) {
EventBits_t bits = xEventGroupGetBits(s_wifi_events);
const char *state = (bits & s_BIT_GOTIP) ? "got_ip"
: (bits & s_BIT_FAIL) ? "fail"
: "connecting";
// Optional: IP & SSID ausgeben (wenn verfügbar)
char ipstr[16] = "";
esp_netif_t *sta = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (sta) {
esp_netif_ip_info_t ip;
if (esp_netif_get_ip_info(sta, &ip) == ESP_OK) {
snprintf(ipstr, sizeof(ipstr), IPSTR, IP2STR(&ip.ip));
}
}
httpd_resp_set_type(req, "application/json; charset=utf-8");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
char buf[160];
int n = snprintf(buf, sizeof(buf),
"{\"state\":\"%s\",\"ip\":\"%s\"}", state, ipstr);
return httpd_resp_send(req, buf, n);
}
static httpd_handle_t start_http(void) {
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
cfg.server_port = 80;
cfg.uri_match_fn = httpd_uri_match_wildcard; // optional: falls du später /foo/* brauchst
cfg.recv_wait_timeout = 10; // Sekunden (default 5), hilft bei lahmen Clients
cfg.send_wait_timeout = 10;
cfg.lru_purge_enable = true;
cfg.max_uri_handlers = 12;
if (httpd_start(&s_http, &cfg) != ESP_OK) return NULL;
// Routen definieren (lokal)
httpd_uri_t status_json_uri = { .uri="/status.json", .method=HTTP_GET, .handler=status_json_get };
httpd_uri_t root_uri = { .uri="/", .method=HTTP_GET, .handler=root_get };
httpd_uri_t g204_uri = { .uri="/generate_204", .method=HTTP_GET, .handler=captive_ok };
httpd_uri_t hotsp_uri = { .uri="/hotspot-detect.html", .method=HTTP_GET, .handler=captive_ok };
httpd_uri_t msncsi_uri = { .uri="/ncsi.txt", .method=HTTP_GET, .handler=captive_ok };
httpd_uri_t status_uri = { .uri="/status", .method=HTTP_GET, .handler=status_get };
httpd_uri_t save_uri = { .uri="/save", .method=HTTP_POST, .handler=save_post };
httpd_uri_t fav_uri = { .uri="/favicon.ico", .method=HTTP_GET, .handler=favicon_get };
httpd_uri_t scan_uri = { .uri="/scan", .method=HTTP_GET, .handler=scan_get };
httpd_register_uri_handler(s_http, &status_json_uri);
httpd_register_uri_handler(s_http, &root_uri);
httpd_register_uri_handler(s_http, &g204_uri);
httpd_register_uri_handler(s_http, &hotsp_uri);
httpd_register_uri_handler(s_http, &msncsi_uri);
httpd_register_uri_handler(s_http, &status_uri);
httpd_register_uri_handler(s_http, &save_uri);
httpd_register_uri_handler(s_http, &fav_uri);
httpd_register_uri_handler(s_http, &scan_uri);
httpd_register_err_handler(s_http, HTTPD_404_NOT_FOUND, not_found_handler);
ESP_LOGI(TAG, "HTTP Server gestartet");
return s_http;
}
esp_err_t portal_http_start(EventGroupHandle_t wifi_events,
EventBits_t bit_gotip,
EventBits_t bit_fail,
const char* ap_ssid,
const portal_http_callbacks_t *cb)
{
if (s_http) return ESP_OK;
if (!cb) return ESP_ERR_INVALID_ARG;
s_cb = *cb;
if (s_http) return ESP_OK;
s_wifi_events = wifi_events;
s_BIT_GOTIP = bit_gotip;
s_BIT_FAIL = bit_fail;
if (ap_ssid) {
strncpy(s_ap_ssid, ap_ssid, sizeof(s_ap_ssid) - 1);
s_ap_ssid[sizeof(s_ap_ssid)-1] = '\0';
} else {
strcpy(s_ap_ssid, "nanoPSX");
}
s_force_captive = true; // immer beim Start erzwingen
return (start_http() ? ESP_OK : ESP_FAIL);
}
void portal_http_stop(void) {
if (s_http) {
httpd_stop(s_http);
s_http = NULL;
}
}