Files
mimiclaw/main/nvs_safety/nvs_safety.c

102 lines
3.1 KiB
C

#include "nvs_safety.h"
#include "mimi_config.h"
#include <string.h>
#include "esp_log.h"
#include "nvs.h"
static const char *TAG = "nvs_safety";
/* Critical namespaces to check */
static const char *critical_namespaces[] = {
MIMI_NVS_WIFI,
MIMI_NVS_LLM,
MIMI_NVS_TG,
MIMI_NVS_FEISHU,
MIMI_NVS_PROXY,
MIMI_NVS_SEARCH,
"system_config",
};
static const int critical_ns_count = sizeof(critical_namespaces) / sizeof(critical_namespaces[0]);
/*
* Iterate through all keys in a namespace and validate each entry.
* Erase entries that appear corrupted (invalid length, invalid name, etc.).
* Returns number of corrupted entries found and removed.
*/
static int check_and_repair_namespace(const char *ns)
{
nvs_handle_t nvs;
esp_err_t err = nvs_open(ns, NVS_READWRITE, &nvs);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Cannot open namespace '%s': %s", ns, esp_err_to_name(err));
return 0;
}
nvs_iterator_t it = NULL;
esp_err_t find_err = nvs_entry_find_in_handle(nvs, NVS_TYPE_ANY, &it);
int corrupted = 0;
while (find_err == ESP_OK && it != NULL) {
nvs_entry_info_t info;
nvs_entry_info(it, &info);
find_err = nvs_entry_next(&it);
/* Try to read the entry to verify integrity */
char buf[512];
size_t len = sizeof(buf);
esp_err_t read_err = nvs_get_str(nvs, info.key, buf, &len);
if (read_err == ESP_ERR_NVS_INVALID_LENGTH ||
read_err == ESP_ERR_NVS_INVALID_NAME ||
read_err == ESP_ERR_NVS_NOT_FOUND) {
ESP_LOGW(TAG, "Corrupted entry in %s: key='%s' (err=%s), erasing",
ns, info.key, esp_err_to_name(read_err));
nvs_erase_key(nvs, info.key);
corrupted++;
} else if (read_err == ESP_OK) {
/* Valid entry - check for obviously corrupted values */
if (len > 0 && buf[0] != '\0') {
/* Check that string is properly null-terminated within expected bounds */
if (len > sizeof(buf) - 1) {
ESP_LOGW(TAG, "Oversized value in %s: key='%s' (len=%d), erasing",
ns, info.key, (int)len);
nvs_erase_key(nvs, info.key);
corrupted++;
}
}
}
/* ESP_ERR_NVS_TYPE_MISMATCH is not an error for string-only namespaces */
}
if (corrupted > 0) {
nvs_commit(nvs);
ESP_LOGW(TAG, "Repaired %d corrupted entries in namespace '%s'", corrupted, ns);
}
if (it != NULL) {
nvs_release_iterator(it);
}
nvs_close(nvs);
return corrupted;
}
esp_err_t nvs_safety_check(void)
{
ESP_LOGI(TAG, "Checking NVS integrity...");
int total_corrupted = 0;
for (int i = 0; i < critical_ns_count; i++) {
total_corrupted += check_and_repair_namespace(critical_namespaces[i]);
}
if (total_corrupted > 0) {
ESP_LOGW(TAG, "NVS safety check complete: %d corrupted entries repaired", total_corrupted);
return ESP_ERR_INVALID_STATE;
}
ESP_LOGI(TAG, "NVS integrity check passed");
return ESP_OK;
}