ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ota_esphome.cpp
Go to the documentation of this file.
1#include "ota_esphome.h"
2#ifdef USE_OTA_ENCRYPTION_PROVISIONED
4#endif
5#ifdef USE_OTA
6#ifdef USE_OTA_PASSWORD
8#endif
17#include "esphome/core/hal.h"
19#include "esphome/core/log.h"
20#include "esphome/core/util.h"
21#ifdef USE_LWIP_FAST_SELECT
23#endif
24
25#include <algorithm>
26#include <cerrno>
27#include <cstdio>
28#include <cstring>
29#include <sys/time.h>
30
31namespace esphome {
32
33ESPHOME_LOG_TAG(TAG, "esphome.ota");
34
35#ifdef USE_OTA_ENCRYPTION
37#ifdef USE_OTA_ENCRYPTION_PROVISIONED
38 // The api server holds the live key; safe mode never constructs it, and then
39 // noise_ctx_ holds the saved key setup() found, if any
40 if (api::global_api_server != nullptr)
42#endif
43 return this->noise_ctx_;
44}
45#endif
46static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
47static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 60000; // milliseconds for initial handshake
48// Milliseconds for data transfer. Covers the lwIP retransmit run seen in
49// practice for a lost chunk ack (1.5 + 3 + 6 + 12 + 24 + 48 s); the CLI waits
50// longer (espota2.DATA_PHASE_TIMEOUT) so the device is free before it retries
51static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 105000;
52// A handshake this old gives way to a waiting connection: a client retrying over a lossy link otherwise queues
53// behind its own stalled attempt until both time out
54static constexpr uint32_t OTA_HANDSHAKE_PREEMPT = 10000;
55static constexpr uint32_t OTA_PROGRESS_INTERVAL_MS = 1000;
56static constexpr size_t OTA_SIZE_FIELD_BYTES = 4; // sizes on the wire are 4 bytes MSB first
57
58// Single-instance pointer — multi-port configs are rejected in final_validate.
59// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
60static ESPHomeOTAComponent *global_esphome_ota_component = nullptr;
61
62// Called from any context (LwIP TCP/IP task, RP2040 user-IRQ).
64 if (global_esphome_ota_component != nullptr) {
65 global_esphome_ota_component->enable_loop_soon_any_context();
66 }
67}
68
70#ifdef USE_OTA_ENCRYPTION_PROVISIONED
71 // Safe mode never constructs the api server, so read the key it saved
72 noise::psk_t psk;
75 if (this->saved_psk_ != nullptr) {
76 this->noise_ctx_.set_psk(this->saved_psk_->data());
77 }
78 }
79#endif
80 this->server_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0).release(); // monitored for incoming connections
81 if (this->server_ == nullptr) {
82 this->server_failed_(LOG_STR("creation"));
83 return;
84 }
85 int enable = 1;
86 int err = this->server_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
87 if (err != 0) {
88 this->log_socket_error_(LOG_STR("reuseaddr"));
89 // we can still continue
90 }
91 err = this->server_->setblocking(false);
92 if (err != 0) {
93 this->server_failed_(LOG_STR("nonblocking"));
94 return;
95 }
96
97 struct sockaddr_storage server;
98
99 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
100 if (sl == 0) {
101 this->server_failed_(LOG_STR("set sockaddr"));
102 return;
103 }
104
105 err = this->server_->bind((struct sockaddr *) &server, sl);
106 if (err != 0) {
107 this->server_failed_(LOG_STR("bind"));
108 return;
109 }
110
111 err = this->server_->listen(1); // Only one client at a time
112 if (err != 0) {
113 this->server_failed_(LOG_STR("listen"));
114 return;
115 }
116
117 // loop() self-disables on its first idle tick; no explicit disable_loop() needed here.
118 global_esphome_ota_component = this;
119#ifdef USE_LWIP_FAST_SELECT
120 // Filter fast-select wakes to this listener only. If the sock lookup returns nullptr,
121 // no wakes fire and loop() falls back to the self-disable safety net.
123#endif
124
125#ifdef USE_OTA_PARTITIONS
127#endif
128}
129
131 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
132 ESP_LOGCONFIG(TAG,
133 "Over-The-Air updates:\n"
134 " Address: %s:%u\n"
135 " Version: %d"
136#ifdef USE_OTA_ENCRYPTION
137 "\n Encryption: %s"
138#endif
139 ,
140 network::get_use_address_to(addr_buf), this->port_, USE_OTA_VERSION
141#ifdef USE_OTA_ENCRYPTION_REQUIRED
142 ,
143 LOG_STR_LITERAL("required")
144#elif defined(USE_OTA_ENCRYPTION_PROVISIONED)
145 // A runtime provisioned key may not exist yet
146 ,
147 this->noise_context_().has_psk() ? LOG_STR_LITERAL("offered, plaintext accepted")
148 : LOG_STR_LITERAL("offered once the api key is provisioned")
149#elif defined(USE_OTA_ENCRYPTION)
150 ,
151 LOG_STR_LITERAL("offered, plaintext accepted")
152#endif
153 );
154#ifdef USE_OTA_PASSWORD
155 if (!this->password_.empty()) {
156 ESP_LOGCONFIG(TAG, " Password configured");
157 }
158#endif
159#ifdef USE_OTA_PARTITIONS
160 ESP_LOGCONFIG(TAG,
161 " Partition access allowed\n"
162 " Running app:\n"
163 " Partition address: 0x%" PRIX32 "\n"
164 " Used size: %zu bytes (0x%zX)",
166
167#ifdef USE_ESP32
168 ESP_LOGCONFIG(TAG,
169 " Partition table:\n"
170 " %-12s %-4s %-8s %-10s %-10s",
171 "Name", "Type", "Subtype", "Address", "Size");
172 esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY, nullptr);
173 while (it != nullptr) {
174 const esp_partition_t *partition = esp_partition_get(it);
175 ESP_LOGCONFIG(TAG, " %-12s 0x%-2X 0x%-6X 0x%-8" PRIX32 " 0x%-8" PRIX32, partition->label, partition->type,
176 partition->subtype, partition->address, partition->size);
177 it = esp_partition_next(it);
178 }
179 esp_partition_iterator_release(it);
180 esp_bootloader_desc_t bootloader_desc;
181 esp_err_t err = esp_ota_get_bootloader_description(nullptr, &bootloader_desc);
182 ESP_LOGCONFIG(TAG, " Bootloader: ESP-IDF %s",
183 (err == ESP_OK) ? bootloader_desc.idf_ver : LOG_STR_LITERAL("version unknown"));
184#endif // USE_ESP32
185#endif // USE_OTA_PARTITIONS
186}
187
189 // Self-disable idle loop where a wake path re-enables on listener readiness
190 // (fast-select, raw-TCP accept_fn_). Host BSD select doesn't, so stay enabled.
191 if (this->client_ == nullptr && !this->server_->ready()) {
192#ifndef USE_HOST
193 this->disable_loop();
194#endif
195 return;
196 }
197 this->handle_handshake_();
198}
199
200// Deflate for an RTL8710B image: 2026.10 firmware does not know this bit, and
201// there LibreTiny corrupts a deflate upload into OTA2 (esphome#22012)
202static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_DEFLATE_RTL8710B = 0x40;
203static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_COMPRESSION = 0x01;
204static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_SHA256_AUTH = 0x02;
205static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL = 0x04;
206static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_NOISE = 0x08;
207static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_DEFLATE = 0x10;
208#ifdef ESPHOME_OTA_UDP
209static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_UDP = 0x20;
210#endif
211// Noise needs the extended protocol: the prologue binds the 2-byte feature ack
212static constexpr uint8_t CLIENT_NOISE_FEATURES =
213 CLIENT_FEATURE_SUPPORTS_NOISE | CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL;
214static constexpr uint8_t SERVER_FEATURE_SUPPORTS_COMPRESSION = 0x01;
215static constexpr uint8_t SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS = 0x02;
216static constexpr uint8_t SERVER_FEATURE_SUPPORTS_NOISE = 0x04;
217// Raw deflate, window <= OTA_INFLATE_WINDOW_SIZE. Binding once offered: the
218// client must then send the image size frame and a deflate stream.
219static constexpr uint8_t SERVER_FEATURE_SUPPORTS_DEFLATE = 0x08;
220#ifdef ESPHOME_OTA_UDP
221static constexpr uint8_t SERVER_FEATURE_SUPPORTS_UDP = 0x10;
222static constexpr uint8_t UDP_REQUEST_V1 = 0x01; // espota2.UDP_REQUEST
223#endif
224
225#ifdef USE_OTA_ENCRYPTION
227 return (this->handshake_buf_[1] & SERVER_FEATURE_SUPPORTS_NOISE) != 0 &&
228 (this->ota_features_ & CLIENT_NOISE_FEATURES) == CLIENT_NOISE_FEATURES;
229}
230#endif
231
233#ifdef USE_OTA_ENCRYPTION_REQUIRED
234 // FEATURE_READ already refused every client without the extended protocol
235 return true;
236#else
237 return (this->ota_features_ & CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL) != 0;
238#endif
239}
240
247
248 if (this->client_ == nullptr) {
249 // We already checked server_->ready() in loop(), so we can accept directly
250 struct sockaddr_storage source_addr;
251 socklen_t addr_len = sizeof(source_addr);
252 int enable = 1;
253
254 this->client_ = this->server_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
255 if (this->client_ == nullptr)
256 return;
257 int err = this->client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(int));
258 if (err != 0) {
259 this->log_socket_error_(LOG_STR("nodelay"));
260 this->cleanup_connection_();
261 return;
262 }
263 err = this->client_->setblocking(false);
264 if (err != 0) {
265 this->log_socket_error_(LOG_STR("non-blocking"));
266 this->cleanup_connection_();
267 return;
268 }
269 this->log_start_(LOG_STR("handshake"));
271 this->handshake_buf_pos_ = 0; // Reset handshake buffer position
273 }
274
275 // Check for handshake timeout
277 if (now - this->client_connect_time_ > OTA_SOCKET_TIMEOUT_HANDSHAKE) {
278 ESP_LOGW(TAG, "Handshake timeout");
279 this->cleanup_connection_();
280 return;
281 }
282 // Only unauthenticated handshakes reach here; the data phase blocks inside handle_data_
283 if (now - this->client_connect_time_ > OTA_HANDSHAKE_PREEMPT && this->server_->ready()) {
284 ESP_LOGD(TAG, "Newer connection waiting");
285 this->cleanup_connection_();
286 return;
287 }
288
289 switch (this->ota_state_) {
291 // Try to read remaining magic bytes (5 total)
292 if (!this->try_read_(5, LOG_STR("read magic"))) {
293 return;
294 }
295
296 // Validate magic bytes
297 if (memcmp(this->handshake_buf_, MAGIC_BYTES, sizeof(MAGIC_BYTES)) != 0) {
298#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_WARN
300 ESP_LOGW(TAG, "Magic bytes mismatch! %s",
302#endif
304 return;
305 }
306
307 // Magic bytes valid, move to next state
310 this->handshake_buf_[1] = USE_OTA_VERSION;
311 [[fallthrough]];
312 }
313
314 case OTAState::MAGIC_ACK: {
315 // Send OK and version - 2 bytes
316 if (!this->try_write_(2, LOG_STR("ack magic"))) {
317 return;
318 }
319 // All bytes sent, create backend and move to next state
322 [[fallthrough]];
323 }
324
326 // Read features - 1 byte
327 if (!this->try_read_(1, LOG_STR("read feature"))) {
328 return;
329 }
330 this->ota_features_ = this->handshake_buf_[0];
331 ESP_LOGV(TAG, "Features: 0x%02X", this->ota_features_);
332
333#ifdef USE_OTA_ENCRYPTION_REQUIRED
334 // `ota: encryption:` requires the client to negotiate encryption
335 if ((this->ota_features_ & CLIENT_NOISE_FEATURES) != CLIENT_NOISE_FEATURES) {
336 ESP_LOGW(TAG, "Client does not support encryption");
338 return;
339 }
340#endif
341
343
344 const bool supports_compression =
345 (this->ota_features_ & CLIENT_FEATURE_SUPPORTS_COMPRESSION) != 0 && ota::OTABackend::supports_compression();
346
347 // Compose the feature-ack response. When the client negotiates the extended protocol we emit
348 // a 2-byte response (marker + server feature flags); otherwise we emit the single-byte
349 // legacy response.
350 if (this->extended_proto_()) {
351 static_assert(HANDSHAKE_BUF_SIZE >= 2, "handshake_buf_ must hold the 2-byte extended-protocol feature ack");
353 this->handshake_buf_[1] = (supports_compression ? SERVER_FEATURE_SUPPORTS_COMPRESSION : 0);
354#ifdef ESPHOME_OTA_UDP
355 this->handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_UDP;
356#endif
357#ifdef USE_OTA_PARTITIONS
358 this->handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS;
359#endif
360#ifdef USE_OTA_ENCRYPTION_PROVISIONED
361 // A runtime provisioned key may not exist yet
362 if (this->noise_context_().has_psk()) {
363 this->handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_NOISE;
364 }
365#elif defined(USE_OTA_ENCRYPTION)
366 // A yaml key always exists: validation rejects the all-zeros key
367 this->handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_NOISE;
368#endif
369#ifdef USE_OTA_ENCRYPTION
370 // Reserve the noise session before the optional inflate buffer, so the
371 // required allocation is not starved by the compression window
372 if (this->noise_offered_()) {
374 }
375#endif
376#ifdef USE_OTA_DEFLATE
377 // Offered only once the session memory is in hand; else uncompressed
378 if ((this->ota_features_ & (CLIENT_FEATURE_SUPPORTS_DEFLATE | CLIENT_FEATURE_SUPPORTS_DEFLATE_RTL8710B)) != 0) {
379 // Value initialized: a corrupt stream that back references the
380 // window before it is filled then copies zeros, never stale memory.
381 // Default placement, PSRAM first where present: the session lives for one
382 // upload and keeps 4.9 KB of internal heap free while it runs
384 if (this->inflate_ != nullptr) {
385 this->handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_DEFLATE;
386 } else {
387 ESP_LOGW(TAG, "No memory to inflate");
388 }
389 }
390#endif
391 } else {
392 this->handshake_buf_[0] =
394 }
395 [[fallthrough]];
396 }
397
399 static constexpr size_t STANDARD_PROTO_ACK_SIZE = 1;
400 static constexpr size_t EXTENDED_PROTO_ACK_SIZE = 2;
401 const size_t ack_size = this->extended_proto_() ? EXTENDED_PROTO_ACK_SIZE : STANDARD_PROTO_ACK_SIZE;
402 if (!this->try_write_(ack_size, LOG_STR("ack feature"))) {
403 return;
404 }
405#ifdef USE_OTA_ENCRYPTION
406 // Latch the offer actually sent: a key activating between the two
407 // states must not start a session the client never expects
408 if (this->noise_offered_()) {
409 // handshake_buf_ still holds the feature ack composed above; a
410 // would-block re-entry lands here without rebuilding it
411 if (!this->noise_start_session_(this->handshake_buf_[1])) {
412 return;
413 }
415 return;
416 }
417#endif
418#ifdef USE_OTA_PASSWORD
419 // If password is set, move to auth phase
420 if (!this->password_.empty()) {
422 } else
423#endif
424 {
425 // No password, move directly to data phase. Not a fallthrough: the next
426 // case is AUTH_SEND, which would demand a password that is not set.
428 this->handle_data_();
429 return;
430 }
431#ifdef USE_OTA_PASSWORD
432 [[fallthrough]];
433#endif
434 }
435
436#ifdef USE_OTA_PASSWORD
437 case OTAState::AUTH_SEND: {
438 // Non-blocking authentication send
439 if (!this->handle_auth_send_()) {
440 return;
441 }
443 [[fallthrough]];
444 }
445
446 case OTAState::AUTH_READ: {
447 // Non-blocking authentication read & verify
448 if (!this->handle_auth_read_()) {
449 return;
450 }
452 [[fallthrough]];
453 }
454#endif
455
456 case OTAState::DATA:
457 this->handle_data_();
458 return;
459
460#ifdef USE_OTA_ENCRYPTION
462 if (!this->handle_noise_handshake_()) {
463 return;
464 }
466 this->handle_data_();
467 return;
468#endif
469
470 default:
471 break;
472 }
473}
474
508 // Backend calls overwrite this with OK; reset to UNKNOWN before any
509 // goto error that follows a successful begin()/write()
511 DataTransfer xfer;
512 uint8_t buf[OTA_BUFFER_SIZE];
513 char *sbuf = reinterpret_cast<char *>(buf);
514 size_t image_size;
516#ifdef ESPHOME_OTA_UDP
517 UdpLink udp_link;
518 this->udp_ = nullptr; // client_connect_time_ is done with
519#endif
520
521 // Set socket timeouts and blocking mode (see strategy table above)
522 struct timeval tv;
523 tv.tv_sec = 2;
524 tv.tv_usec = 0;
525 this->client_->setsockopt(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
526 this->client_->setsockopt(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
527 if (this->client_->setblocking(true) != 0) {
528 this->log_socket_error_(LOG_STR("blocking"));
529 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
530 }
531
532 // Acknowledge auth OK - 1 byte
534
535#ifdef ESPHOME_OTA_UDP
536 // The server always offers UDP on the extended protocol
537 if (this->extended_proto_() && (this->ota_features_ & CLIENT_FEATURE_SUPPORTS_UDP) != 0) {
538 // Whether the client wants UDP (0: its link looks good), answered with our token
539 if (!this->data_readall_(buf, 1)) {
540 if (this->client_left_before_start_())
541 return;
542 this->log_read_error_(LOG_STR("UDP request"));
543 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
544 }
545 // 1 is this UDP format; other values are free for later ones, which we decline (a zero reply keeps TCP)
546 if (buf[0] == UDP_REQUEST_V1) {
547 this->udp_open_(udp_link);
548 if (udp_link.reply[0] == 0) {
549 ESP_LOGW(TAG, "UDP unavailable, using TCP");
550 }
551 }
552 if (!this->data_write_(udp_link.reply, sizeof(udp_link.reply)))
553 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
554 if (udp_link.reply[0] != 0) {
555 this->udp_ = &udp_link;
556 if (!this->udp_start_()) {
557 // Nothing started yet: just drop the session, which the client retries as a network failure
558 this->log_read_error_(LOG_STR("UDP start"));
559 this->cleanup_connection_();
560 return;
561 }
562 }
563 }
564
565#endif
566
567 if (this->extended_proto_()) {
568 // Read ota type, 1 byte
569 if (!this->data_readall_(buf, 1)) {
570 if (this->client_left_before_start_())
571 return;
572 this->log_read_error_(LOG_STR("OTA type"));
573 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
574 }
575 ota_type = static_cast<ota::OTAType>(buf[0]);
576 }
577 ESP_LOGV(TAG, "OTA type is 0x%02x", ota_type);
578
579 // Read size, 4 bytes MSB first
580 if (!this->read_size_(buf, xfer.ota_size, LOG_STR("size"))) {
581 // The first request byte is the type on the extended protocol; a close after it was a cut-off request
582 if (!this->extended_proto_() && this->client_left_before_start_())
583 return;
584 this->log_read_error_(LOG_STR("size"));
585 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
586 }
587 image_size = xfer.ota_size;
588#ifdef USE_OTA_DEFLATE
589 if (this->inflate_ != nullptr && !this->read_size_(buf, image_size, LOG_STR("image size"))) {
590 this->log_read_error_(LOG_STR("image size"));
591 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
592 }
593#endif
594
595#ifndef USE_OTA_PARTITIONS
596 if (ota_type != ota::OTA_TYPE_UPDATE_APP) {
598 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
599 }
600#endif
601
602 // Now that we've passed authentication and are actually
603 // starting the update, set the warning status and notify
604 // listeners. This ensures that port scanners do not
605 // accidentally trigger the update process.
606 this->log_start_(LOG_STR("update"));
607 this->status_set_warning();
608#ifdef USE_OTA_STATE_LISTENER
609 this->notify_state_(ota::OTA_STARTED, 0.0f, 0);
610#endif
611
612 // begin() returns quickly; flash sectors are erased incrementally during write().
613 error_code = this->backend_->begin(image_size, ota_type);
614 if (error_code != ota::OTA_RESPONSE_OK)
615 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
616
617 // Acknowledge prepare OK - 1 byte
619
620 // Read binary MD5, 32 bytes
621 if (!this->data_readall_(buf, 32)) {
622 this->log_read_error_(LOG_STR("MD5 checksum"));
624 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
625 }
626 sbuf[32] = '\0';
627 ESP_LOGV(TAG, "Update: Binary MD5 is %s", sbuf);
628 this->backend_->set_update_md5(sbuf);
629
630 // Acknowledge MD5 OK - 1 byte
632
633 xfer.last_data_ms = millis();
634#ifdef USE_OTA_DEFLATE
635 if (this->inflate_ != nullptr) {
636 error_code = this->inflate_data_(buf, image_size, xfer);
637 if (error_code != ota::OTA_RESPONSE_OK)
638 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
639 } else
640#endif
641 {
642 while (xfer.total < xfer.ota_size) {
643 ssize_t read = this->receive_data_(buf, xfer);
644 if (read < 0) {
646 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
647 }
648 error_code = this->write_flash_(buf, read);
649 if (error_code != ota::OTA_RESPONSE_OK)
650 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
651 this->ack_written_(xfer);
652 }
653 }
654
655 // Acknowledge receive OK - 1 byte
657
658 error_code = this->backend_->end();
659 if (error_code != ota::OTA_RESPONSE_OK) {
660 ESP_LOGW(TAG, "End update err %d", error_code);
661 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
662 }
663
664 // Acknowledge Update end OK - 1 byte
666
667#ifdef ESPHOME_OTA_UDP
668 // UDP never reports a close: wait only until the client has our responses, not for its final ack
669 if (this->udp_ != nullptr) {
670 this->udp_linger_();
671 } else
672#endif
673 // Read ACK
674 if (!this->data_readall_(buf, 1) || buf[0] != ota::OTA_RESPONSE_OK) {
675 this->log_read_error_(LOG_STR("ack"));
676 // do not go to error, this is not fatal
677 }
678
679 this->cleanup_connection_();
680 delay(10);
681 ESP_LOGI(TAG, "Update complete");
682 this->status_clear_warning();
683#ifdef USE_OTA_STATE_LISTENER
684 this->notify_state_(ota::OTA_COMPLETED, 100.0f, 0);
685#endif
686 delay(100); // NOLINT
687#ifdef USE_OTA_PARTITIONS
688 if (ota_type == ota::OTA_TYPE_UPDATE_PARTITION_TABLE) {
689 // Skip on_safe_shutdown: nvs_flash_deinit() has already invalidated open NVS handles, so
690 // preferences flush would emit ESP_ERR_NVS_INVALID_HANDLE for every entry. Reboot directly.
691 App.reboot();
692 }
693#endif
695
696error:
697 this->data_write_byte_(static_cast<uint8_t>(error_code));
698#ifdef ESPHOME_OTA_UDP
699 this->udp_linger_();
700#endif
701
702 // Abort backend before cleanup - cleanup_connection_() destroys the backend.
703 // Always call abort() unconditionally: backends register external partitions before
704 // esp_ota_begin (partition table / bootloader paths), and abort() is responsible for
705 // releasing those even if begin() failed before an OTA handle was opened. The IDF
706 // backend's esp_ota_abort(0) is documented as harmless.
707 if (this->backend_ != nullptr) {
708 this->backend_->abort();
709 }
710
711 this->cleanup_connection_();
712
713 this->status_momentary_error(5000);
714#ifdef USE_OTA_STATE_LISTENER
715 this->notify_state_(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
716#endif
717}
718
719bool ESPHomeOTAComponent::readall_(uint8_t *buf, size_t len) {
720 uint32_t start = millis();
721 uint32_t at = 0;
722 while (len - at > 0) {
723 uint32_t now = millis();
724 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
725 ESP_LOGW(TAG, "Timeout reading %zu bytes", len);
726 return false;
727 }
728
729 ssize_t read = this->transport_read_(buf + at, len - at);
730 if (read == -1) {
731 const int err = errno;
732 if (!this->would_block_(err)) {
733 ESP_LOGW(TAG, "Read err %zu bytes, errno %d", len, err);
734 return false;
735 }
736 } else if (read == 0) {
737 // A partial message is a cut-off request, not a clean close; the caller reports the clean one
738 this->remote_closed_ = at == 0;
739 if (at > 0) {
740 ESP_LOGW(TAG, "Remote closed after %u of %zu bytes", (unsigned) at, len);
741 }
742 return false;
743 } else {
744 at += read;
745 }
746 // read() already waited via SO_RCVTIMEO, just yield without 1ms stall
747 App.feed_wdt();
748 delay(0);
749 }
750
751 return true;
752}
753bool ESPHomeOTAComponent::writeall_(const uint8_t *buf, size_t len) {
754#ifdef ESPHOME_OTA_UDP
755 if (this->udp_ != nullptr)
756 return this->udp_send_(buf, len);
757#endif
758 uint32_t start = millis();
759 uint32_t at = 0;
760 while (len - at > 0) {
761 uint32_t now = millis();
762 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
763 ESP_LOGW(TAG, "Timeout writing %zu bytes", len);
764 return false;
765 }
766
767 ssize_t written = this->client_->write(buf + at, len - at);
768 if (written == -1) {
769 const int err = errno;
770 if (!this->would_block_(err)) {
771 ESP_LOGW(TAG, "Write err %zu bytes, errno %d", len, err);
772 return false;
773 }
774 // EWOULDBLOCK: on raw TCP writes never block, delay(1) prevents spinning
776 } else {
777 at += written;
778 // write() may block up to SO_SNDTIMEO on BSD/lwip sockets, feed WDT
779 App.feed_wdt();
780 }
781 }
782 return true;
783}
784
786
787void ESPHomeOTAComponent::log_socket_error_(const LogString *msg) {
788 ESP_LOGW(TAG, "Socket %s: errno %d", LOG_STR_ARG(msg), errno);
789}
790
792 // Key probes and scanners hang up right after the handshake; nothing started, so no error status or callback
793 if (!this->remote_closed_)
794 return false;
795 ESP_LOGD(TAG, "Client left after the handshake");
796 this->cleanup_connection_();
797 return true;
798}
799
800void ESPHomeOTAComponent::log_read_error_(const LogString *what) {
801 if (this->remote_closed_) {
802 this->log_remote_closed_(what);
803 return;
804 }
805 ESP_LOGW(TAG, "Read %s failed", LOG_STR_ARG(what));
806}
807
808void ESPHomeOTAComponent::log_start_(const LogString *phase) {
809 char peername[socket::SOCKADDR_STR_LEN];
810#ifdef ESPHOME_OTA_UDP
811 if (this->client_ == nullptr) {
812 // A committed UDP session has already dropped TCP
813#ifdef ESPHOME_OTA_UDP_LWIP
814 ipaddr_ntoa_r(&this->udp_->peer_ip, peername, sizeof(peername));
815#else
816 socket::format_sockaddr_to(reinterpret_cast<const struct sockaddr *>(&this->udp_->peer), this->udp_->peer_len,
817 peername);
818#endif
819 } else
820#endif
821 {
822 this->client_->getpeername_to(peername);
823 }
824 ESP_LOGD(TAG, "Starting %s from %s", LOG_STR_ARG(phase), peername);
825}
826
827void ESPHomeOTAComponent::log_remote_closed_(const LogString *during) {
828 ESP_LOGW(TAG, "Remote closed at %s", LOG_STR_ARG(during));
829}
830
831void ESPHomeOTAComponent::server_failed_(const LogString *msg) {
832 this->log_socket_error_(msg);
833 // No explicit close() needed — listen sockets have no active connections on
834 // failure/shutdown. Destructor handles fd cleanup (close or abort per platform).
835 delete this->server_;
836 this->server_ = nullptr;
837 this->mark_failed();
838}
839
840bool ESPHomeOTAComponent::handle_read_error_(ssize_t read, const LogString *desc) {
841 if (read == -1 && this->would_block_(errno)) {
842 return false; // No data yet, try again next loop
843 }
844
845 if (read <= 0) {
846 read == 0 ? this->log_remote_closed_(desc) : this->log_socket_error_(desc);
847 this->cleanup_connection_();
848 return false;
849 }
850 return true;
851}
852
854 if (written == -1) {
855 if (this->would_block_(errno)) {
856 return false; // Try again next loop
857 }
858 this->log_socket_error_(desc);
859 this->cleanup_connection_();
860 return false;
861 }
862 return true;
863}
864
865bool ESPHomeOTAComponent::try_read_(size_t to_read, const LogString *desc) {
866 // Read bytes into handshake buffer, starting at handshake_buf_pos_
867 size_t bytes_to_read = to_read - this->handshake_buf_pos_;
868 ssize_t read = this->client_->read(this->handshake_buf_ + this->handshake_buf_pos_, bytes_to_read);
869
870 if (!this->handle_read_error_(read, desc)) {
871 return false;
872 }
873
874 this->handshake_buf_pos_ += read;
875 // Return true only if we have all the requested bytes
876 return this->handshake_buf_pos_ >= to_read;
877}
878
879bool ESPHomeOTAComponent::try_write_(size_t to_write, const LogString *desc) {
880 // Write bytes from handshake buffer, starting at handshake_buf_pos_
881 size_t bytes_to_write = to_write - this->handshake_buf_pos_;
882 ssize_t written = this->client_->write(this->handshake_buf_ + this->handshake_buf_pos_, bytes_to_write);
883
884 if (!this->handle_write_error_(written, desc)) {
885 return false;
886 }
887
888 this->handshake_buf_pos_ += written;
889 // Return true only if we have written all the requested bytes
890 return this->handshake_buf_pos_ >= to_write;
891}
892
893bool ESPHomeOTAComponent::read_size_(uint8_t *buf, size_t &size, const LogString *desc) {
894 if (!this->data_readall_(buf, OTA_SIZE_FIELD_BYTES))
895 return false;
896 size = encode_uint32(buf[0], buf[1], buf[2], buf[3]);
897 ESP_LOGV(TAG, "%s is %zu bytes", LOG_STR_ARG(desc), size);
898 return true;
899}
900
902 ota::OTAResponseTypes result = this->backend_->write(data, len);
903 if (result != ota::OTA_RESPONSE_OK) {
904 ESP_LOGW(TAG, "Flash write err %d", result);
905 }
906 return result;
907}
908
910 const size_t remaining = xfer.ota_size - xfer.total;
911 const size_t requested = std::min(remaining, OTA_BUFFER_SIZE);
912 ssize_t read;
913 for (;;) {
914 // A silently-vanished peer (no FIN/RST delivered, e.g. uploader killed
915 // mid-transfer or NAT/router dropped state) must not wedge the device:
916 // read() only fails on EOF or a real error, and lwIP TCP keepalive isn't
917 // enabled here.
918 if (millis() - xfer.last_data_ms > OTA_SOCKET_TIMEOUT_DATA) {
919 ESP_LOGW(TAG, "No data received for %u ms", (unsigned) OTA_SOCKET_TIMEOUT_DATA);
920 return -1;
921 }
922#ifdef USE_OTA_ENCRYPTION
923 if (this->noise_ != nullptr) {
924 // One frame per call; noise_read_data_ waits internally (readall_), so
925 // there is no would-block retry here and failures are already logged.
926 read = this->noise_read_data_(buf, requested);
927 if (read <= 0) {
928 if (this->remote_closed_)
929 this->log_remote_closed_(LOG_STR("data"));
930 return -1;
931 }
932 break;
933 }
934#endif
935 read = this->transport_read_(buf, requested);
936 if (read > 0)
937 break;
938 if (read == 0) {
939 this->log_remote_closed_(LOG_STR("data"));
940 return -1;
941 }
942 if (!this->would_block_(errno)) {
943 this->log_socket_error_(LOG_STR("data"));
944 return -1;
945 }
946 // read() already waited up to SO_RCVTIMEO for data, just feed WDT
947 App.feed_wdt();
948 }
949
950 const uint32_t now = millis();
951 xfer.last_data_ms = now;
952 xfer.total += read;
953 this->ack_received_(xfer);
954 if (now - xfer.last_progress > OTA_PROGRESS_INTERVAL_MS) {
955 xfer.last_progress = now;
956 float percentage = (xfer.total * 100.0f) / xfer.ota_size;
957 ESP_LOGD(TAG, "Progress: %0.1f%%", percentage);
958#ifdef USE_OTA_STATE_LISTENER
959 this->notify_state_(ota::OTA_IN_PROGRESS, percentage, 0);
960#endif
961 // feed watchdog and give other tasks a chance to run
963 }
964 return read;
965}
966
968#if USE_OTA_VERSION == 2
969#ifdef ESPHOME_OTA_UDP
970 // UDP acks every message itself
971 if (this->udp_ != nullptr)
972 return;
973#endif
974 while (xfer.acknowledged + OTA_BLOCK_SIZE <= xfer.total ||
975 (xfer.total == xfer.ota_size && xfer.acknowledged < xfer.ota_size)) {
977 xfer.acknowledged += OTA_BLOCK_SIZE;
978 }
979#endif
980}
981
983#ifdef ESPHOME_OTA_UDP
984 this->udp_ = nullptr; // the link itself lives on handle_data_'s stack
985#endif
986 // Already gone once a UDP session committed
987 if (this->client_ != nullptr)
988 this->client_->close();
989 this->client_ = nullptr;
990 this->client_connect_time_ = 0;
991 this->handshake_buf_pos_ = 0;
993 this->ota_features_ = 0;
994 this->remote_closed_ = false;
995 this->backend_ = nullptr;
996#ifdef USE_OTA_PASSWORD
997 this->cleanup_auth_();
998#endif
999#ifdef USE_OTA_ENCRYPTION
1000 this->noise_ = nullptr;
1001#endif
1002#ifdef USE_OTA_DEFLATE
1003 this->inflate_ = nullptr;
1004#endif
1005 // Intentionally no disable_loop() — letting loop() run one more iteration catches
1006 // any connection that queued on the listener mid-session (otherwise the wake flag,
1007 // set while we were in LOOP state, would be lost to enable_pending_loops_()).
1008}
1009
1014
1015#ifdef USE_OTA_PASSWORD
1016void ESPHomeOTAComponent::log_auth_warning_(const LogString *msg) { ESP_LOGW(TAG, "Auth: %s", LOG_STR_ARG(msg)); }
1017
1019 bool client_supports_sha256 = (this->ota_features_ & CLIENT_FEATURE_SUPPORTS_SHA256_AUTH) != 0;
1020
1021 // Require SHA256
1022 if (!client_supports_sha256) {
1023 this->log_auth_warning_(LOG_STR("SHA256 required"));
1025 return false;
1026 }
1028 return true;
1029}
1030
1032 // Initialize auth buffer if not already done
1033 if (!this->auth_buf_) {
1034 // Select auth type based on client capabilities and configuration
1035 if (!this->select_auth_type_()) {
1036 return false;
1037 }
1038
1039 // Generate nonce - hasher must be created and used in same stack frame
1040 // CRITICAL ESP32-S3 HARDWARE SHA ACCELERATION REQUIREMENTS:
1041 // 1. Hash objects must NEVER be passed to another function (different stack frame)
1042 // 2. NO Variable Length Arrays (VLAs) - they corrupt the stack with hardware DMA
1043 // 3. All hash operations (init/add/calculate) must happen in the SAME function where object is created
1044 // Violating these causes truncated hash output (20 bytes instead of 32) or memory corruption.
1045 //
1046 // Buffer layout after AUTH_READ completes:
1047 // [0]: auth_type (1 byte)
1048 // [1...hex_size]: nonce (hex_size bytes) - our random nonce sent in AUTH_SEND
1049 // [1+hex_size...1+2*hex_size-1]: cnonce (hex_size bytes) - client's nonce
1050 // [1+2*hex_size...1+3*hex_size-1]: response (hex_size bytes) - client's hash
1051
1052 // CRITICAL ESP32-S2/S3 HARDWARE SHA ACCELERATION: Hash object must stay in same stack frame
1053 // (no passing to other functions). All hash operations must happen in this function.
1054 sha256::SHA256 hasher;
1055
1056 const size_t hex_size = hasher.get_size() * 2;
1057 const size_t nonce_len = hasher.get_size() / 4;
1058 const size_t auth_buf_size = 1 + 3 * hex_size;
1059 // Internal RAM first: 128 of these bytes go straight into the hardware SHA engine
1060 this->auth_buf_ =
1062 if (!this->auth_buf_) {
1063 this->log_auth_warning_(LOG_STR("No memory"));
1065 return false;
1066 }
1067 this->auth_buf_pos_ = 0;
1068
1069 char *buf = reinterpret_cast<char *>(this->auth_buf_.get() + 1);
1070 if (!random_bytes(reinterpret_cast<uint8_t *>(buf), nonce_len)) {
1071 this->log_auth_warning_(LOG_STR("Random failed"));
1073 return false;
1074 }
1075
1076 hasher.init();
1077 hasher.add(buf, nonce_len);
1078 hasher.calculate();
1079 this->auth_buf_[0] = this->auth_type_;
1080 hasher.get_hex(buf);
1081
1082 ESP_LOGV(TAG, "Auth: Nonce is %.*s", (int) hex_size, buf);
1083 }
1084
1085 // Try to write auth_type + nonce
1086 constexpr size_t hex_size = SHA256_HEX_SIZE;
1087 const size_t to_write = 1 + hex_size;
1088 size_t remaining = to_write - this->auth_buf_pos_;
1089
1090 ssize_t written = this->client_->write(this->auth_buf_.get() + this->auth_buf_pos_, remaining);
1091 if (!this->handle_write_error_(written, LOG_STR("ack auth"))) {
1092 return false;
1093 }
1094
1095 this->auth_buf_pos_ += written;
1096
1097 // Check if we still have more to write
1098 if (this->auth_buf_pos_ < to_write) {
1099 return false; // More to write, try again next loop
1100 }
1101
1102 // All written, prepare for reading phase
1103 this->auth_buf_pos_ = 0;
1104 return true;
1105}
1106
1108 constexpr size_t hex_size = SHA256_HEX_SIZE;
1109 const size_t to_read = hex_size * 2; // CNonce + Response
1110
1111 // Try to read remaining bytes (CNonce + Response)
1112 // We read cnonce+response starting at offset 1+hex_size (after auth_type and our nonce)
1113 size_t cnonce_offset = 1 + hex_size; // Offset where cnonce should be stored in buffer
1114 size_t remaining = to_read - this->auth_buf_pos_;
1115 ssize_t read = this->client_->read(this->auth_buf_.get() + cnonce_offset + this->auth_buf_pos_, remaining);
1116
1117 if (!this->handle_read_error_(read, LOG_STR("read auth"))) {
1118 return false;
1119 }
1120
1121 this->auth_buf_pos_ += read;
1122
1123 // Check if we still need more data
1124 if (this->auth_buf_pos_ < to_read) {
1125 return false; // More to read, try again next loop
1126 }
1127
1128 // We have all the data, verify it
1129 const char *nonce = reinterpret_cast<char *>(this->auth_buf_.get() + 1);
1130 const char *cnonce = nonce + hex_size;
1131 const char *response = cnonce + hex_size;
1132
1133 // CRITICAL ESP32-S2/S3 HARDWARE SHA ACCELERATION: Hash object must stay in same stack frame
1134 // (no passing to other functions). All hash operations must happen in this function.
1135 sha256::SHA256 hasher;
1136
1137 hasher.init();
1138 hasher.add(this->password_.c_str(), this->password_.length());
1139 hasher.add(nonce, hex_size * 2); // Add both nonce and cnonce (contiguous in buffer)
1140 hasher.calculate();
1141
1142 ESP_LOGV(TAG, "Auth: CNonce is %.*s", (int) hex_size, cnonce);
1143#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1144 char computed_hash[SHA256_HEX_SIZE + 1]; // Buffer for hex-encoded hash (max expected length + null terminator)
1145 hasher.get_hex(computed_hash);
1146 ESP_LOGV(TAG, "Auth: Result is %.*s", (int) hex_size, computed_hash);
1147#endif
1148 ESP_LOGV(TAG, "Auth: Response is %.*s", (int) hex_size, response);
1149
1150 // Compare response
1151 bool matches = hasher.equals_hex(response);
1152
1153 if (!matches) {
1154 this->log_auth_warning_(LOG_STR("Password mismatch"));
1156 return false;
1157 }
1158
1159 // Authentication successful - clean up auth state
1160 this->cleanup_auth_();
1161
1162 return true;
1163}
1164
1166 this->auth_buf_ = nullptr;
1167 this->auth_buf_pos_ = 0;
1168 this->auth_type_ = 0;
1169}
1170#endif // USE_OTA_PASSWORD
1171
1172} // namespace esphome
1173#endif
void feed_wdt()
Feed the task watchdog.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void disable_loop()
Disable this component's loop.
void status_momentary_error(uint32_t length=5000)
Set error status flag and clear it after length ms.
void status_clear_warning()
Definition component.h:309
ESPHomeOTAComponent provides a simple way to integrate Over-the-Air updates into your app using Ardui...
Definition ota_esphome.h:40
static constexpr size_t OTA_BUFFER_SIZE
bool handle_noise_handshake_()
Drive the non-blocking handshake from loop(); returns true once the transport ciphers are ready.
ssize_t receive_data_(uint8_t *buf, DataTransfer &xfer)
bool would_block_(int error_code) const
static constexpr size_t SHA256_HEX_SIZE
static constexpr uint8_t MAGIC_BYTES[5]
bool udp_send_(const uint8_t *data, size_t len)
ota::OTAResponseTypes write_flash_(uint8_t *data, size_t len)
bool writeall_(const uint8_t *buf, size_t len)
bool try_read_(size_t to_read, const LogString *desc)
bool data_readall_(uint8_t *buf, size_t len)
noise::NoiseContext noise_ctx_
ssize_t transport_read_(uint8_t *buf, size_t len)
void ack_written_(DataTransfer &xfer)
bool noise_start_session_(uint8_t server_feature_flags)
Start the responder handshake, on the session reserved at offer time.
ota::OTABackendPtr backend_
bool try_write_(size_t to_write, const LogString *desc)
RAMUniquePtr< NoiseSession > noise_
bool handle_write_error_(ssize_t written, const LogString *desc)
void send_chunk_acks_(DataTransfer &xfer)
bool data_write_byte_(uint8_t byte)
void log_auth_warning_(const LogString *msg)
RAMUniquePtr< InflateSession > inflate_
float get_setup_priority() const override
void send_error_and_cleanup_(ota::OTAResponseTypes error)
bool handle_read_error_(ssize_t read, const LogString *desc)
ssize_t noise_read_data_(uint8_t *buf, size_t capacity)
Blocking read of one data-phase frame, decrypted in place; returns the plaintext size,...
void log_read_error_(const LogString *what)
bool readall_(uint8_t *buf, size_t len)
bool data_write_(const uint8_t *data, size_t len)
RAMUniquePtr< uint8_t[]> auth_buf_
RAMUniquePtr< noise::psk_t > saved_psk_
void ack_received_(DataTransfer &xfer)
uint8_t handshake_buf_[HANDSHAKE_BUF_SIZE]
static constexpr size_t HANDSHAKE_BUF_SIZE
ota::OTAResponseTypes inflate_data_(uint8_t *in, size_t image_size, DataTransfer &xfer)
const noise::NoiseContext & noise_context_() const
void server_failed_(const LogString *msg)
void transition_ota_state_(OTAState next_state)
bool read_size_(uint8_t *buf, size_t &size, const LogString *desc)
socket::ListenSocket * server_
void log_remote_closed_(const LogString *during)
std::unique_ptr< socket::Socket > client_
void log_start_(const LogString *phase)
void log_socket_error_(const LogString *msg)
void get_hex(char *output)
Retrieve the hash as hex characters. Output buffer must hold get_size() * 2 + 1 bytes.
Definition hash_base.h:29
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
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
Definition helpers.h:2459
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
Definition helpers.h:2469
noise::NoiseContext & get_noise_ctx()
Definition api_server.h:92
void set_psk(const uint8_t *psk)
psk points at 32 bytes that outlive the context (PROGMEM or caller owned RAM); nullptr means no key.
Definition noise.h:32
void notify_state_(OTAState state, float progress, uint8_t error)
SHA256 hash implementation.
Definition sha256.h:51
void calculate() override
Definition sha256.cpp:27
size_t get_size() const override
Get the size of the hash in bytes (32 for SHA256)
Definition sha256.h:64
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:25
void init() override
Definition sha256.cpp:19
bool ready() const
Check if the socket has buffered data ready to read.
Definition socket.h:106
int bind(const struct sockaddr *addr, socklen_t addrlen)
int setsockopt(int level, int optname, const void *optval, socklen_t optlen)
std::unique_ptr< BSDSocketImpl > accept_loop_monitored(struct sockaddr *addr, socklen_t *addrlen)
uint16_t addr_len
uint32_t socklen_t
Definition headers.h:109
__int64 ssize_t
Definition httplib.h:178
struct lwip_sock * esphome_lwip_get_sock(int fd)
Look up a LwIP socket struct from a file descriptor.
void esphome_fast_select_set_ota_listener_sock(struct lwip_sock *sock)
Set the listener netconn that the fast-select callback filters OTA wakes against.
APIServer * global_api_server
bool load_saved_noise_psk(noise::psk_t &out)
One-shot read of the provisioned key for a boot without an api server (safe mode); false when there i...
ESPHOME_LOG_TAG(TAG, CRASH_LOG_TAG)
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
Definition util.cpp:72
std::array< uint8_t, 32 > psk_t
Definition noise.h:14
@ OTA_TYPE_UPDATE_PARTITION_TABLE
Definition ota_backend.h:95
void get_running_app_position(uint32_t &offset, size_t &size)
@ OTA_RESPONSE_UPDATE_PREPARE_OK
Definition ota_backend.h:25
@ OTA_RESPONSE_ERROR_ENCRYPTION_REQUIRED
Definition ota_backend.h:53
@ OTA_RESPONSE_SUPPORTS_COMPRESSION
Definition ota_backend.h:29
@ OTA_RESPONSE_BIN_MD5_OK
Definition ota_backend.h:26
@ OTA_RESPONSE_UPDATE_END_OK
Definition ota_backend.h:28
@ OTA_RESPONSE_RECEIVE_OK
Definition ota_backend.h:27
@ OTA_RESPONSE_CHUNK_OK
Definition ota_backend.h:30
@ OTA_RESPONSE_FEATURE_FLAGS
Definition ota_backend.h:31
@ OTA_RESPONSE_ERROR_UNSUPPORTED_OTA_TYPE
Definition ota_backend.h:47
@ OTA_RESPONSE_ERROR_AUTH_INVALID
Definition ota_backend.h:35
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:55
@ OTA_RESPONSE_REQUEST_SHA256_AUTH
Definition ota_backend.h:21
@ OTA_RESPONSE_ERROR_MAGIC
Definition ota_backend.h:33
@ OTA_RESPONSE_HEADER_OK
Definition ota_backend.h:23
std::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.h:55
size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::span< char, SOCKADDR_STR_LEN > buf)
Format sockaddr into caller-provided buffer, returns length written (excluding null)
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.h:175
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
Definition helpers.cpp:20
void esphome_wake_ota_component_any_context()
const void size_t len
Definition hal.h:68
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
uint16_t size
Definition helpers.cpp:34
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1687
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
int written
Definition helpers.h:1340
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t