[host] Add null checks for getenv and fopen in preferences (#14531)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jonathan Swoboda
2026-03-05 20:47:47 -05:00
committed by GitHub
parent 58ab630965
commit 44870323da
+12 -3
View File
@@ -4,6 +4,7 @@
#include <fstream>
#include "preferences.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
namespace esphome {
namespace host {
@@ -14,7 +15,12 @@ static const char *const TAG = "host.preferences";
void HostPreferences::setup_() {
if (this->setup_complete_)
return;
this->filename_.append(getenv("HOME"));
const char *home = getenv("HOME");
if (home == nullptr) {
ESP_LOGE(TAG, "HOME environment variable is not set");
abort();
}
this->filename_.append(home);
this->filename_.append("/.esphome");
this->filename_.append("/prefs");
fs::create_directories(this->filename_);
@@ -44,9 +50,12 @@ void HostPreferences::setup_() {
bool HostPreferences::sync() {
this->setup_();
FILE *fp = fopen(this->filename_.c_str(), "wb");
std::map<uint32_t, std::vector<uint8_t>>::iterator it;
if (fp == nullptr) {
ESP_LOGE(TAG, "Failed to open preferences file for writing: %s", this->filename_.c_str());
return false;
}
for (it = this->data.begin(); it != this->data.end(); ++it) {
for (auto it = this->data.begin(); it != this->data.end(); ++it) {
fwrite(&it->first, sizeof(uint32_t), 1, fp);
uint8_t len = it->second.size();
fwrite(&len, sizeof(len), 1, fp);