ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ota_backend_esp_idf.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
3
7#include "esphome/core/log.h"
8
9#include <esp_ota_ops.h>
10#include <sdkconfig.h>
11#include <spi_flash_mmap.h>
12#ifdef USE_OTA_DOWNGRADE_PROTECTION
13#include <esp_app_desc.h>
14#endif
15
16namespace esphome::ota {
17
18ESPHOME_LOG_TAG(TAG, "ota");
19
20std::unique_ptr<IDFOTABackend> make_ota_backend() { return make_unique<IDFOTABackend>(); }
21
23 if (!this->lock_.try_acquire())
25#ifdef USE_OTA_PARTITIONS
26 this->ota_type_ = ota_type;
27 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_PARTITION_TABLE) {
28 // Reject any size other than ESP_PARTITION_TABLE_MAX_LEN
29 if (image_size != ESP_PARTITION_TABLE_MAX_LEN) {
30 ESP_LOGE(TAG, "Wrong partition table size: expected %u bytes, got %zu", ESP_PARTITION_TABLE_MAX_LEN, image_size);
32 }
33 memset(this->buf_, 0xFF, sizeof this->buf_);
34 this->buf_written_ = 0;
35 this->image_size_ = image_size;
36 this->md5_.init();
37 return OTA_RESPONSE_OK;
38 }
39 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_BOOTLOADER) {
40 OTAResponseTypes result = this->prepare_bootloader_update_(image_size);
41 if (result != OTA_RESPONSE_OK) {
42 return result;
43 }
44 }
45 if (!this->is_app_or_bootloader_update_()) {
47 }
48#else
49 if (ota_type != ota::OTA_TYPE_UPDATE_APP) {
51 }
52#endif
53#ifdef USE_OTA_ROLLBACK
54 // If we're starting an OTA, the current boot is good enough - mark it valid
55 // to prevent rollback and allow the OTA to proceed even if the safe mode
56 // timer hasn't expired yet.
57 esp_ota_mark_app_valid_cancel_rollback();
58#endif
59
60 this->partition_ = esp_ota_get_next_update_partition(nullptr);
61 if (this->partition_ == nullptr) {
63 }
64
65 // Both lazy-erase paths below replace esp_ota_begin()'s blocking full erase.
66 // Size check replaces the one that erase performed (0 = unknown size,
67 // e.g. web_server uploads).
68 if (image_size != 0 && image_size > this->partition_->size) {
70 }
71 this->written_ = 0;
72 esp_err_t err;
73#ifdef USE_OTA_BLOCK_ERASE_AHEAD
74 this->erased_end_ = 0;
75 // Unlike esp_ota_begin(), esp_ota_resume() does not reject a running app in
76 // ESP_OTA_IMG_PENDING_VERIFY; that state is unreachable here because the app
77 // was marked valid at boot (esp32/hal.cpp) or just above under USE_OTA_ROLLBACK.
78 // erase_size 0 (!= OTA_WITH_SEQUENTIAL_WRITES) means no erase; erase_ahead_() handles it
79 err = esp_ota_resume(this->partition_, 0, 0, &this->update_handle_);
80#if (defined(CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE) || defined(CONFIG_BOOTLOADER_APP_ROLLBACK)) && \
81 ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
82 // esp_ota_begin() does this on IDF 5.5+; esp_ota_resume() does not. Prevents
83 // booting a half-written slot after a crash mid-OTA. Not available on the
84 // 5.3.3/5.4.2 backports, whose esp_ota_begin() did not invalidate either.
85 if (err == ESP_OK) {
86 esp_ota_invalidate_inactive_ota_data_slot();
87 }
88#endif
89#else
90 err = esp_ota_begin(this->partition_, OTA_WITH_SEQUENTIAL_WRITES, &this->update_handle_);
91#endif
92
93 if (err != ESP_OK) {
94 ESP_LOGE(TAG, "OTA begin failed (err=0x%X)", err);
95 esp_ota_abort(this->update_handle_);
96 this->update_handle_ = 0;
97 if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
99 } else if (err == ESP_ERR_OTA_PARTITION_CONFLICT) {
100 // This error appears with 1 factory and 1 ota partition
102 }
104 }
105#ifdef USE_OTA_PARTITIONS
106 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_BOOTLOADER) {
108 if (result != OTA_RESPONSE_OK) {
109 return result;
110 }
111 }
112#endif
113 this->md5_.init();
114 return OTA_RESPONSE_OK;
115}
116
117void IDFOTABackend::set_update_md5(const char *expected_md5) {
118 memcpy(this->expected_bin_md5_, expected_md5, 32);
119 this->md5_set_ = true;
120}
121
123#ifdef USE_OTA_PARTITIONS
124 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_PARTITION_TABLE) {
125 if (len > PARTITION_TABLE_BUFFER_SIZE - this->buf_written_) {
126 ESP_LOGE(TAG, "Wrong partition table size");
128 }
129 memcpy(this->buf_ + this->buf_written_, data, len);
130 this->buf_written_ += len;
131 this->md5_.add(data, len);
132 return OTA_RESPONSE_OK;
133 }
134 if (!this->is_app_or_bootloader_update_()) {
136 }
137#endif
138 // Overflow can only happen on unknown-size uploads (web_server); known
139 // sizes were rejected in begin().
140 if (this->written_ + len > this->partition_->size) {
142 }
143#ifdef USE_OTA_BLOCK_ERASE_AHEAD
144 OTAResponseTypes erase_result = this->erase_ahead_(len);
145 if (erase_result != OTA_RESPONSE_OK) {
146 return erase_result;
147 }
148#endif
149 esp_err_t err = esp_ota_write(this->update_handle_, data, len);
150 this->md5_.add(data, len);
151 if (err != ESP_OK) {
152 ESP_LOGE(TAG, "esp_ota_write failed (err=0x%X)", err);
153 if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
155 } else if (err == ESP_ERR_INVALID_SIZE) {
156 // Sequential-writes fallback: IDF's lazy erase reports overflow here
158 } else if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
160 }
162 }
163 this->written_ += len;
164 return OTA_RESPONSE_OK;
165}
166
167#ifdef USE_OTA_BLOCK_ERASE_AHEAD
168OTAResponseTypes IDFOTABackend::erase_ahead_(size_t len) {
169 const size_t end = this->written_ + len;
170 if (this->erased_end_ >= end) {
171 return OTA_RESPONSE_OK;
172 }
173 // Round up to a block boundary, clamped to the partition end; IDF splits the
174 // range into 64 KiB block erases where aligned, sector erases elsewhere.
175 const size_t erase_to = next_erase_end(end, this->partition_->size);
176 // A block erase is one uninterruptible flash op (typically ~150 ms, seconds
177 // on aged flash) and the transfer loop may not have fed the WDT for ~1s.
178 watchdog::WatchdogManager watchdog(15000);
179 esp_err_t err = esp_partition_erase_range(this->partition_, this->erased_end_, erase_to - this->erased_end_);
180 if (err != ESP_OK) {
181 ESP_LOGE(TAG, "esp_partition_erase_range failed (err=0x%X)", err);
183 }
184 this->erased_end_ = erase_to;
185 return OTA_RESPONSE_OK;
186}
187#endif
188
190 if (this->md5_set_) {
191 this->md5_.calculate();
192 if (!this->md5_.equals_hex(this->expected_bin_md5_)) {
193 this->abort();
195 }
196 }
197#ifdef USE_OTA_PARTITIONS
198 // A partition-table update carries an MD5 (checked by IDF), not a Secure Boot
199 // signature, and only re-points boot at an already-installed app -- so it is
200 // intentionally not run through the signature verifier below.
201 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_PARTITION_TABLE) {
202 return this->hold_lock_if_ok_(this->update_partition_table_());
203 }
204 if (!this->is_app_or_bootloader_update_()) {
206 }
207#endif
208 esp_err_t err = esp_ota_end(this->update_handle_);
209 this->update_handle_ = 0;
210 if (err != ESP_OK) {
211 ESP_LOGE(TAG, "esp_ota_end failed (err=0x%X)", err);
212 }
213#ifdef USE_OTA_PARTITIONS
214 if (this->ota_type_ == ota::OTA_TYPE_UPDATE_BOOTLOADER) {
215 return this->hold_lock_if_ok_(this->finalize_bootloader_update_(err));
216 }
217#endif
218 if (err == ESP_OK) {
219#ifdef USE_OTA_SIGNED_VERIFICATION_MULTI_KEY
220 // IDF's built-in on-update check is disabled for this scheme (it only
221 // matches the incoming image's first signature block against the running
222 // app's first). Verify here against every key the running app trusts, so
223 // rotation and backup keys are accepted. Leaving the boot partition
224 // unchanged means a rejected image never boots.
225 if (!this->verify_signed_image_(this->partition_)) {
227 }
228#endif
229#ifdef USE_OTA_DOWNGRADE_PROTECTION
230 // The image is written and (when signing is enabled) signature-verified by
231 // esp_ota_end(), so its embedded project version can be trusted. Reject the
232 // update if it is older than the running version by leaving the boot
233 // partition unchanged -- the staged image simply never boots.
234 esp_app_desc_t incoming;
235 esp_err_t desc_err = esp_ota_get_partition_description(this->partition_, &incoming);
236 if (desc_err != ESP_OK) {
237 // Couldn't read the staged image's version, so the comparison is skipped.
238 // Warn so the bypassed check is observable rather than silent.
239 ESP_LOGW(TAG, "Downgrade protection: could not read image version (err=0x%X); allowing update", desc_err);
240 } else if (version_is_older(incoming.version, ESPHOME_PROJECT_VERSION)) {
241 ESP_LOGE(TAG, "Rejecting downgrade: image version '%s' is older than running version '%s'", incoming.version,
242 ESPHOME_PROJECT_VERSION);
244 }
245#endif
246 err = esp_ota_set_boot_partition(this->partition_);
247 if (err == ESP_OK) {
248 return this->hold_lock_if_ok_(OTA_RESPONSE_OK);
249 }
250 }
251 if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
252#ifdef USE_OTA_SIGNED_VERIFICATION
253 ESP_LOGE(TAG, "OTA validation failed (err=0x%X) - possible signature verification failure", err);
255#else
257#endif
258 }
259 if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
261 }
263}
264
266 if (!this->lock_.is_held()) // refused in begin()
267 return;
268#ifdef USE_OTA_PARTITIONS
269 if (this->partition_table_part_ != nullptr) {
270 esp_partition_deregister_external(this->partition_table_part_);
271 this->partition_table_part_ = nullptr;
272 }
273 if (this->bootloader_part_ != nullptr) {
274 esp_partition_deregister_external(this->bootloader_part_);
275 this->bootloader_part_ = nullptr;
276 }
277#endif
278 // esp_ota_abort with handle 0 returns ESP_ERR_INVALID_ARG harmlessly, so this is safe whether
279 // or not an update is in flight.
280 esp_ota_abort(this->update_handle_);
281 this->update_handle_ = 0;
282 this->written_ = 0;
283#ifdef USE_OTA_BLOCK_ERASE_AHEAD
284 this->erased_end_ = 0;
285#endif
286}
287
288} // namespace esphome::ota
289#endif // USE_ESP32
bool equals_hex(const char *expected)
Compare the hash against a provided hex-encoded hash of get_size() * 2 characters,...
Definition hash_base.h:36
void calculate() override
Compute the digest, based on the provided data.
Definition md5.cpp:16
void add(const uint8_t *data, size_t len) override
Add bytes of data for the digest.
Definition md5.cpp:14
void init() override
Initialize a new MD5 digest computation.
Definition md5.cpp:9
void set_update_md5(const char *md5)
OTAResponseTypes finalize_bootloader_update_(esp_err_t ota_end_err)
OTAResponseTypes begin(size_t image_size, ota::OTAType ota_type=ota::OTA_TYPE_UPDATE_APP)
OTAResponseTypes prepare_bootloader_update_(size_t image_size)
OTAResponseTypes write(uint8_t *data, size_t len)
OTAResponseTypes hold_lock_if_ok_(OTAResponseTypes result)
bool try_acquire()
Returns false if held elsewhere.
@ OTA_TYPE_UPDATE_BOOTLOADER
Definition ota_backend.h:96
@ OTA_TYPE_UPDATE_PARTITION_TABLE
Definition ota_backend.h:95
ESPHOME_LOG_TAG(TAG, "ota")
bool version_is_older(const char *candidate, const char *reference)
Compare two dotted-numeric version strings (such as "1.2.3").
constexpr size_t next_erase_end(size_t write_end, size_t partition_size)
Target erased watermark for lazy block erase-ahead.
Definition ota_backend.h:80
@ OTA_RESPONSE_ERROR_MD5_MISMATCH
Definition ota_backend.h:44
@ OTA_RESPONSE_ERROR_VERSION_DOWNGRADE
Definition ota_backend.h:52
@ OTA_RESPONSE_ERROR_ESP32_NOT_ENOUGH_SPACE
Definition ota_backend.h:42
@ OTA_RESPONSE_ERROR_WRITING_FLASH
Definition ota_backend.h:36
@ OTA_RESPONSE_ERROR_UNSUPPORTED_OTA_TYPE
Definition ota_backend.h:47
@ OTA_RESPONSE_ERROR_UPDATE_END
Definition ota_backend.h:37
@ OTA_RESPONSE_ERROR_SIGNATURE_INVALID
Definition ota_backend.h:46
@ OTA_RESPONSE_ERROR_UPDATE_BUSY
Definition ota_backend.h:54
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:55
@ OTA_RESPONSE_ERROR_NO_UPDATE_PARTITION
Definition ota_backend.h:43
@ OTA_RESPONSE_ERROR_MAGIC
Definition ota_backend.h:33
@ OTA_RESPONSE_ERROR_PARTITION_TABLE_VERIFY
Definition ota_backend.h:48
std::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
const void size_t len
Definition hal.h:68