ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
ota_esphome.cpp
Go to the documentation of this file.
1#include "ota_esphome.h"
2#ifdef USE_OTA
3#ifdef USE_OTA_PASSWORD
4#ifdef USE_OTA_MD5
6#endif
7#ifdef USE_OTA_SHA256
9#endif
10#endif
19#include "esphome/core/hal.h"
21#include "esphome/core/log.h"
22#include "esphome/core/util.h"
23
24#include <cerrno>
25#include <cstdio>
26
27namespace esphome {
28
29static const char *const TAG = "esphome.ota";
30static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
31static constexpr size_t OTA_BUFFER_SIZE = 1024; // buffer size for OTA data transfer
32static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 20000; // milliseconds for initial handshake
33static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 90000; // milliseconds for data transfer
34
35#ifdef USE_OTA_PASSWORD
36#ifdef USE_OTA_MD5
37static constexpr size_t MD5_HEX_SIZE = 32; // MD5 hash as hex string (16 bytes * 2)
38#endif
39#ifdef USE_OTA_SHA256
40static constexpr size_t SHA256_HEX_SIZE = 64; // SHA256 hash as hex string (32 bytes * 2)
41#endif
42#endif // USE_OTA_PASSWORD
43
45#ifdef USE_OTA_STATE_CALLBACK
47#endif
48
49 this->server_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0); // monitored for incoming connections
50 if (this->server_ == nullptr) {
51 this->log_socket_error_(LOG_STR("creation"));
52 this->mark_failed();
53 return;
54 }
55 int enable = 1;
56 int err = this->server_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
57 if (err != 0) {
58 this->log_socket_error_(LOG_STR("reuseaddr"));
59 // we can still continue
60 }
61 err = this->server_->setblocking(false);
62 if (err != 0) {
63 this->log_socket_error_(LOG_STR("non-blocking"));
64 this->mark_failed();
65 return;
66 }
67
68 struct sockaddr_storage server;
69
70 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
71 if (sl == 0) {
72 this->log_socket_error_(LOG_STR("set sockaddr"));
73 this->mark_failed();
74 return;
75 }
76
77 err = this->server_->bind((struct sockaddr *) &server, sizeof(server));
78 if (err != 0) {
79 this->log_socket_error_(LOG_STR("bind"));
80 this->mark_failed();
81 return;
82 }
83
84 err = this->server_->listen(1); // Only one client at a time
85 if (err != 0) {
86 this->log_socket_error_(LOG_STR("listen"));
87 this->mark_failed();
88 return;
89 }
90}
91
93 ESP_LOGCONFIG(TAG,
94 "Over-The-Air updates:\n"
95 " Address: %s:%u\n"
96 " Version: %d",
97 network::get_use_address(), this->port_, USE_OTA_VERSION);
98#ifdef USE_OTA_PASSWORD
99 if (!this->password_.empty()) {
100 ESP_LOGCONFIG(TAG, " Password configured");
101 }
102#endif
103}
104
106 // Skip handle_handshake_() call if no client connected and no incoming connections
107 // This optimization reduces idle loop overhead when OTA is not active
108 // Note: No need to check server_ for null as the component is marked failed in setup()
109 // if server_ creation fails
110 if (this->client_ != nullptr || this->server_->ready()) {
111 this->handle_handshake_();
112 }
113}
114
115static const uint8_t FEATURE_SUPPORTS_COMPRESSION = 0x01;
116#ifdef USE_OTA_SHA256
117static const uint8_t FEATURE_SUPPORTS_SHA256_AUTH = 0x02;
118#endif
119
120// Temporary flag to allow MD5 downgrade for ~3 versions (until 2026.1.0)
121// This allows users to downgrade via OTA if they encounter issues after updating.
122// Without this, users would need to do a serial flash to downgrade.
123// TODO: Remove this flag and all associated code in 2026.1.0
124#define ALLOW_OTA_DOWNGRADE_MD5
125
132
133 if (this->client_ == nullptr) {
134 // We already checked server_->ready() in loop(), so we can accept directly
135 struct sockaddr_storage source_addr;
136 socklen_t addr_len = sizeof(source_addr);
137 int enable = 1;
138
139 this->client_ = this->server_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
140 if (this->client_ == nullptr)
141 return;
142 int err = this->client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(int));
143 if (err != 0) {
144 this->log_socket_error_(LOG_STR("nodelay"));
145 this->cleanup_connection_();
146 return;
147 }
148 err = this->client_->setblocking(false);
149 if (err != 0) {
150 this->log_socket_error_(LOG_STR("non-blocking"));
151 this->cleanup_connection_();
152 return;
153 }
154 this->log_start_(LOG_STR("handshake"));
156 this->handshake_buf_pos_ = 0; // Reset handshake buffer position
158 }
159
160 // Check for handshake timeout
161 uint32_t now = App.get_loop_component_start_time();
162 if (now - this->client_connect_time_ > OTA_SOCKET_TIMEOUT_HANDSHAKE) {
163 ESP_LOGW(TAG, "Handshake timeout");
164 this->cleanup_connection_();
165 return;
166 }
167
168 switch (this->ota_state_) {
170 // Try to read remaining magic bytes (5 total)
171 if (!this->try_read_(5, LOG_STR("read magic"))) {
172 return;
173 }
174
175 // Validate magic bytes
176 static const uint8_t MAGIC_BYTES[5] = {0x6C, 0x26, 0xF7, 0x5C, 0x45};
177 if (memcmp(this->handshake_buf_, MAGIC_BYTES, 5) != 0) {
178 ESP_LOGW(TAG, "Magic bytes mismatch! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", this->handshake_buf_[0],
179 this->handshake_buf_[1], this->handshake_buf_[2], this->handshake_buf_[3], this->handshake_buf_[4]);
181 return;
182 }
183
184 // Magic bytes valid, move to next state
187 this->handshake_buf_[1] = USE_OTA_VERSION;
188 [[fallthrough]];
189 }
190
191 case OTAState::MAGIC_ACK: {
192 // Send OK and version - 2 bytes
193 if (!this->try_write_(2, LOG_STR("ack magic"))) {
194 return;
195 }
196 // All bytes sent, create backend and move to next state
199 [[fallthrough]];
200 }
201
203 // Read features - 1 byte
204 if (!this->try_read_(1, LOG_STR("read feature"))) {
205 return;
206 }
207 this->ota_features_ = this->handshake_buf_[0];
208 ESP_LOGV(TAG, "Features: 0x%02X", this->ota_features_);
210 this->handshake_buf_[0] =
211 ((this->ota_features_ & FEATURE_SUPPORTS_COMPRESSION) != 0 && this->backend_->supports_compression())
214 [[fallthrough]];
215 }
216
218 // Acknowledge header - 1 byte
219 if (!this->try_write_(1, LOG_STR("ack feature"))) {
220 return;
221 }
222#ifdef USE_OTA_PASSWORD
223 // If password is set, move to auth phase
224 if (!this->password_.empty()) {
226 } else
227#endif
228 {
229 // No password, move directly to data phase
231 }
232 [[fallthrough]];
233 }
234
235#ifdef USE_OTA_PASSWORD
236 case OTAState::AUTH_SEND: {
237 // Non-blocking authentication send
238 if (!this->handle_auth_send_()) {
239 return;
240 }
242 [[fallthrough]];
243 }
244
245 case OTAState::AUTH_READ: {
246 // Non-blocking authentication read & verify
247 if (!this->handle_auth_read_()) {
248 return;
249 }
251 [[fallthrough]];
252 }
253#endif
254
255 case OTAState::DATA:
256 this->handle_data_();
257 return;
258
259 default:
260 break;
261 }
262}
263
273 bool update_started = false;
274 size_t total = 0;
275 uint32_t last_progress = 0;
276 uint8_t buf[OTA_BUFFER_SIZE];
277 char *sbuf = reinterpret_cast<char *>(buf);
278 size_t ota_size;
279#if USE_OTA_VERSION == 2
280 size_t size_acknowledged = 0;
281#endif
282
283 // Acknowledge auth OK - 1 byte
285
286 // Read size, 4 bytes MSB first
287 if (!this->readall_(buf, 4)) {
288 this->log_read_error_(LOG_STR("size"));
289 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
290 }
291 ota_size = (static_cast<size_t>(buf[0]) << 24) | (static_cast<size_t>(buf[1]) << 16) |
292 (static_cast<size_t>(buf[2]) << 8) | buf[3];
293 ESP_LOGV(TAG, "Size is %u bytes", ota_size);
294
295 // Now that we've passed authentication and are actually
296 // starting the update, set the warning status and notify
297 // listeners. This ensures that port scanners do not
298 // accidentally trigger the update process.
299 this->log_start_(LOG_STR("update"));
300 this->status_set_warning();
301#ifdef USE_OTA_STATE_CALLBACK
302 this->state_callback_.call(ota::OTA_STARTED, 0.0f, 0);
303#endif
304
305 // This will block for a few seconds as it locks flash
306 error_code = this->backend_->begin(ota_size);
307 if (error_code != ota::OTA_RESPONSE_OK)
308 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
309 update_started = true;
310
311 // Acknowledge prepare OK - 1 byte
313
314 // Read binary MD5, 32 bytes
315 if (!this->readall_(buf, 32)) {
316 this->log_read_error_(LOG_STR("MD5 checksum"));
317 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
318 }
319 sbuf[32] = '\0';
320 ESP_LOGV(TAG, "Update: Binary MD5 is %s", sbuf);
321 this->backend_->set_update_md5(sbuf);
322
323 // Acknowledge MD5 OK - 1 byte
325
326 while (total < ota_size) {
327 // TODO: timeout check
328 size_t remaining = ota_size - total;
329 size_t requested = remaining < OTA_BUFFER_SIZE ? remaining : OTA_BUFFER_SIZE;
330 ssize_t read = this->client_->read(buf, requested);
331 if (read == -1) {
332 if (this->would_block_(errno)) {
334 continue;
335 }
336 ESP_LOGW(TAG, "Read err %d", errno);
337 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
338 } else if (read == 0) {
339 ESP_LOGW(TAG, "Remote closed");
340 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
341 }
342
343 error_code = this->backend_->write(buf, read);
344 if (error_code != ota::OTA_RESPONSE_OK) {
345 ESP_LOGW(TAG, "Flash write err %d", error_code);
346 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
347 }
348 total += read;
349#if USE_OTA_VERSION == 2
350 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) {
352 size_acknowledged += OTA_BLOCK_SIZE;
353 }
354#endif
355
356 uint32_t now = millis();
357 if (now - last_progress > 1000) {
358 last_progress = now;
359 float percentage = (total * 100.0f) / ota_size;
360 ESP_LOGD(TAG, "Progress: %0.1f%%", percentage);
361#ifdef USE_OTA_STATE_CALLBACK
362 this->state_callback_.call(ota::OTA_IN_PROGRESS, percentage, 0);
363#endif
364 // feed watchdog and give other tasks a chance to run
366 }
367 }
368
369 // Acknowledge receive OK - 1 byte
371
372 error_code = this->backend_->end();
373 if (error_code != ota::OTA_RESPONSE_OK) {
374 ESP_LOGW(TAG, "End update err %d", error_code);
375 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
376 }
377
378 // Acknowledge Update end OK - 1 byte
380
381 // Read ACK
382 if (!this->readall_(buf, 1) || buf[0] != ota::OTA_RESPONSE_OK) {
383 this->log_read_error_(LOG_STR("ack"));
384 // do not go to error, this is not fatal
385 }
386
387 this->cleanup_connection_();
388 delay(10);
389 ESP_LOGI(TAG, "Update complete");
390 this->status_clear_warning();
391#ifdef USE_OTA_STATE_CALLBACK
392 this->state_callback_.call(ota::OTA_COMPLETED, 100.0f, 0);
393#endif
394 delay(100); // NOLINT
396
397error:
398 this->write_byte_(static_cast<uint8_t>(error_code));
399 this->cleanup_connection_();
400
401 if (this->backend_ != nullptr && update_started) {
402 this->backend_->abort();
403 }
404
405 this->status_momentary_error("onerror", 5000);
406#ifdef USE_OTA_STATE_CALLBACK
407 this->state_callback_.call(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
408#endif
409}
410
411bool ESPHomeOTAComponent::readall_(uint8_t *buf, size_t len) {
412 uint32_t start = millis();
413 uint32_t at = 0;
414 while (len - at > 0) {
415 uint32_t now = millis();
416 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
417 ESP_LOGW(TAG, "Timeout reading %d bytes", len);
418 return false;
419 }
420
421 ssize_t read = this->client_->read(buf + at, len - at);
422 if (read == -1) {
423 if (!this->would_block_(errno)) {
424 ESP_LOGW(TAG, "Read err %d bytes, errno %d", len, errno);
425 return false;
426 }
427 } else if (read == 0) {
428 ESP_LOGW(TAG, "Remote closed");
429 return false;
430 } else {
431 at += read;
432 }
434 }
435
436 return true;
437}
438bool ESPHomeOTAComponent::writeall_(const uint8_t *buf, size_t len) {
439 uint32_t start = millis();
440 uint32_t at = 0;
441 while (len - at > 0) {
442 uint32_t now = millis();
443 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
444 ESP_LOGW(TAG, "Timeout writing %d bytes", len);
445 return false;
446 }
447
448 ssize_t written = this->client_->write(buf + at, len - at);
449 if (written == -1) {
450 if (!this->would_block_(errno)) {
451 ESP_LOGW(TAG, "Write err %d bytes, errno %d", len, errno);
452 return false;
453 }
454 } else {
455 at += written;
456 }
458 }
459 return true;
460}
461
463uint16_t ESPHomeOTAComponent::get_port() const { return this->port_; }
464void ESPHomeOTAComponent::set_port(uint16_t port) { this->port_ = port; }
465
466void ESPHomeOTAComponent::log_socket_error_(const LogString *msg) {
467 ESP_LOGW(TAG, "Socket %s: errno %d", LOG_STR_ARG(msg), errno);
468}
469
470void ESPHomeOTAComponent::log_read_error_(const LogString *what) { ESP_LOGW(TAG, "Read %s failed", LOG_STR_ARG(what)); }
471
472void ESPHomeOTAComponent::log_start_(const LogString *phase) {
473 ESP_LOGD(TAG, "Starting %s from %s", LOG_STR_ARG(phase), this->client_->getpeername().c_str());
474}
475
476void ESPHomeOTAComponent::log_remote_closed_(const LogString *during) {
477 ESP_LOGW(TAG, "Remote closed at %s", LOG_STR_ARG(during));
478}
479
480bool ESPHomeOTAComponent::handle_read_error_(ssize_t read, const LogString *desc) {
481 if (read == -1 && this->would_block_(errno)) {
482 return false; // No data yet, try again next loop
483 }
484
485 if (read <= 0) {
486 read == 0 ? this->log_remote_closed_(desc) : this->log_socket_error_(desc);
487 this->cleanup_connection_();
488 return false;
489 }
490 return true;
491}
492
493bool ESPHomeOTAComponent::handle_write_error_(ssize_t written, const LogString *desc) {
494 if (written == -1) {
495 if (this->would_block_(errno)) {
496 return false; // Try again next loop
497 }
498 this->log_socket_error_(desc);
499 this->cleanup_connection_();
500 return false;
501 }
502 return true;
503}
504
505bool ESPHomeOTAComponent::try_read_(size_t to_read, const LogString *desc) {
506 // Read bytes into handshake buffer, starting at handshake_buf_pos_
507 size_t bytes_to_read = to_read - this->handshake_buf_pos_;
508 ssize_t read = this->client_->read(this->handshake_buf_ + this->handshake_buf_pos_, bytes_to_read);
509
510 if (!this->handle_read_error_(read, desc)) {
511 return false;
512 }
513
514 this->handshake_buf_pos_ += read;
515 // Return true only if we have all the requested bytes
516 return this->handshake_buf_pos_ >= to_read;
517}
518
519bool ESPHomeOTAComponent::try_write_(size_t to_write, const LogString *desc) {
520 // Write bytes from handshake buffer, starting at handshake_buf_pos_
521 size_t bytes_to_write = to_write - this->handshake_buf_pos_;
522 ssize_t written = this->client_->write(this->handshake_buf_ + this->handshake_buf_pos_, bytes_to_write);
523
524 if (!this->handle_write_error_(written, desc)) {
525 return false;
526 }
527
528 this->handshake_buf_pos_ += written;
529 // Return true only if we have written all the requested bytes
530 return this->handshake_buf_pos_ >= to_write;
531}
532
534 this->client_->close();
535 this->client_ = nullptr;
536 this->client_connect_time_ = 0;
537 this->handshake_buf_pos_ = 0;
539 this->ota_features_ = 0;
540 this->backend_ = nullptr;
541#ifdef USE_OTA_PASSWORD
542 this->cleanup_auth_();
543#endif
544}
545
550
551#ifdef USE_OTA_PASSWORD
552void ESPHomeOTAComponent::log_auth_warning_(const LogString *msg) { ESP_LOGW(TAG, "Auth: %s", LOG_STR_ARG(msg)); }
553
555#ifdef USE_OTA_SHA256
556 bool client_supports_sha256 = (this->ota_features_ & FEATURE_SUPPORTS_SHA256_AUTH) != 0;
557
558#ifdef ALLOW_OTA_DOWNGRADE_MD5
559 // Allow fallback to MD5 if client doesn't support SHA256
560 if (client_supports_sha256) {
562 return true;
563 }
564#ifdef USE_OTA_MD5
565 this->log_auth_warning_(LOG_STR("Using deprecated MD5"));
567 return true;
568#else
569 this->log_auth_warning_(LOG_STR("SHA256 required"));
571 return false;
572#endif // USE_OTA_MD5
573
574#else // !ALLOW_OTA_DOWNGRADE_MD5
575 // Require SHA256
576 if (!client_supports_sha256) {
577 this->log_auth_warning_(LOG_STR("SHA256 required"));
579 return false;
580 }
582 return true;
583#endif // ALLOW_OTA_DOWNGRADE_MD5
584
585#else // !USE_OTA_SHA256
586#ifdef USE_OTA_MD5
587 // Only MD5 available
589 return true;
590#else
591 // No auth methods available
592 this->log_auth_warning_(LOG_STR("No auth methods available"));
594 return false;
595#endif // USE_OTA_MD5
596#endif // USE_OTA_SHA256
597}
598
600 // Initialize auth buffer if not already done
601 if (!this->auth_buf_) {
602 // Select auth type based on client capabilities and configuration
603 if (!this->select_auth_type_()) {
604 return false;
605 }
606
607 // Generate nonce - hasher must be created and used in same stack frame
608 // CRITICAL ESP32-S3 HARDWARE SHA ACCELERATION REQUIREMENTS:
609 // 1. Hash objects must NEVER be passed to another function (different stack frame)
610 // 2. NO Variable Length Arrays (VLAs) - they corrupt the stack with hardware DMA
611 // 3. All hash operations (init/add/calculate) must happen in the SAME function where object is created
612 // Violating these causes truncated hash output (20 bytes instead of 32) or memory corruption.
613 //
614 // Buffer layout after AUTH_READ completes:
615 // [0]: auth_type (1 byte)
616 // [1...hex_size]: nonce (hex_size bytes) - our random nonce sent in AUTH_SEND
617 // [1+hex_size...1+2*hex_size-1]: cnonce (hex_size bytes) - client's nonce
618 // [1+2*hex_size...1+3*hex_size-1]: response (hex_size bytes) - client's hash
619
620 // Declare both hash objects in same stack frame, use pointer to select.
621 // NOTE: Both objects are declared here even though only one is used. This is REQUIRED for ESP32-S3
622 // hardware SHA acceleration - the object must exist in this stack frame for all operations.
623 // Do NOT try to "optimize" by creating the object inside the if block, as it would go out of scope.
624#ifdef USE_OTA_SHA256
625 sha256::SHA256 sha_hasher;
626#endif
627#ifdef USE_OTA_MD5
628 md5::MD5Digest md5_hasher;
629#endif
630 HashBase *hasher = nullptr;
631
632#ifdef USE_OTA_SHA256
634 hasher = &sha_hasher;
635 }
636#endif
637#ifdef USE_OTA_MD5
639 hasher = &md5_hasher;
640 }
641#endif
642
643 const size_t hex_size = hasher->get_size() * 2;
644 const size_t nonce_len = hasher->get_size() / 4;
645 const size_t auth_buf_size = 1 + 3 * hex_size;
646 this->auth_buf_ = std::make_unique<uint8_t[]>(auth_buf_size);
647 this->auth_buf_pos_ = 0;
648
649 char *buf = reinterpret_cast<char *>(this->auth_buf_.get() + 1);
650 if (!random_bytes(reinterpret_cast<uint8_t *>(buf), nonce_len)) {
651 this->log_auth_warning_(LOG_STR("Random failed"));
653 return false;
654 }
655
656 hasher->init();
657 hasher->add(buf, nonce_len);
658 hasher->calculate();
659 this->auth_buf_[0] = this->auth_type_;
660 hasher->get_hex(buf);
661
662#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
663 char log_buf[65]; // Fixed size for SHA256 hex (64) + null, works for MD5 (32) too
664 memcpy(log_buf, buf, hex_size);
665 log_buf[hex_size] = '\0';
666 ESP_LOGV(TAG, "Auth: Nonce is %s", log_buf);
667#endif
668 }
669
670 // Try to write auth_type + nonce
671 size_t hex_size = this->get_auth_hex_size_();
672 const size_t to_write = 1 + hex_size;
673 size_t remaining = to_write - this->auth_buf_pos_;
674
675 ssize_t written = this->client_->write(this->auth_buf_.get() + this->auth_buf_pos_, remaining);
676 if (!this->handle_write_error_(written, LOG_STR("ack auth"))) {
677 return false;
678 }
679
680 this->auth_buf_pos_ += written;
681
682 // Check if we still have more to write
683 if (this->auth_buf_pos_ < to_write) {
684 return false; // More to write, try again next loop
685 }
686
687 // All written, prepare for reading phase
688 this->auth_buf_pos_ = 0;
689 return true;
690}
691
693 size_t hex_size = this->get_auth_hex_size_();
694 const size_t to_read = hex_size * 2; // CNonce + Response
695
696 // Try to read remaining bytes (CNonce + Response)
697 // We read cnonce+response starting at offset 1+hex_size (after auth_type and our nonce)
698 size_t cnonce_offset = 1 + hex_size; // Offset where cnonce should be stored in buffer
699 size_t remaining = to_read - this->auth_buf_pos_;
700 ssize_t read = this->client_->read(this->auth_buf_.get() + cnonce_offset + this->auth_buf_pos_, remaining);
701
702 if (!this->handle_read_error_(read, LOG_STR("read auth"))) {
703 return false;
704 }
705
706 this->auth_buf_pos_ += read;
707
708 // Check if we still need more data
709 if (this->auth_buf_pos_ < to_read) {
710 return false; // More to read, try again next loop
711 }
712
713 // We have all the data, verify it
714 const char *nonce = reinterpret_cast<char *>(this->auth_buf_.get() + 1);
715 const char *cnonce = nonce + hex_size;
716 const char *response = cnonce + hex_size;
717
718 // CRITICAL ESP32-S3: Hash objects must stay in same stack frame (no passing to other functions).
719 // Declare both hash objects in same stack frame, use pointer to select.
720 // NOTE: Both objects are declared here even though only one is used. This is REQUIRED for ESP32-S3
721 // hardware SHA acceleration - the object must exist in this stack frame for all operations.
722 // Do NOT try to "optimize" by creating the object inside the if block, as it would go out of scope.
723#ifdef USE_OTA_SHA256
724 sha256::SHA256 sha_hasher;
725#endif
726#ifdef USE_OTA_MD5
727 md5::MD5Digest md5_hasher;
728#endif
729 HashBase *hasher = nullptr;
730
731#ifdef USE_OTA_SHA256
733 hasher = &sha_hasher;
734 }
735#endif
736#ifdef USE_OTA_MD5
738 hasher = &md5_hasher;
739 }
740#endif
741
742 hasher->init();
743 hasher->add(this->password_.c_str(), this->password_.length());
744 hasher->add(nonce, hex_size * 2); // Add both nonce and cnonce (contiguous in buffer)
745 hasher->calculate();
746
747#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
748 char log_buf[65]; // Fixed size for SHA256 hex (64) + null, works for MD5 (32) too
749 // Log CNonce
750 memcpy(log_buf, cnonce, hex_size);
751 log_buf[hex_size] = '\0';
752 ESP_LOGV(TAG, "Auth: CNonce is %s", log_buf);
753
754 // Log computed hash
755 hasher->get_hex(log_buf);
756 log_buf[hex_size] = '\0';
757 ESP_LOGV(TAG, "Auth: Result is %s", log_buf);
758
759 // Log received response
760 memcpy(log_buf, response, hex_size);
761 log_buf[hex_size] = '\0';
762 ESP_LOGV(TAG, "Auth: Response is %s", log_buf);
763#endif
764
765 // Compare response
766 bool matches = hasher->equals_hex(response);
767
768 if (!matches) {
769 this->log_auth_warning_(LOG_STR("Password mismatch"));
771 return false;
772 }
773
774 // Authentication successful - clean up auth state
775 this->cleanup_auth_();
776
777 return true;
778}
779
781#ifdef USE_OTA_SHA256
783 return SHA256_HEX_SIZE;
784 }
785#endif
786#ifdef USE_OTA_MD5
787 return MD5_HEX_SIZE;
788#else
789#ifndef USE_OTA_SHA256
790#error "Either USE_OTA_MD5 or USE_OTA_SHA256 must be defined when USE_OTA_PASSWORD is enabled"
791#endif
792#endif
793}
794
796 this->auth_buf_ = nullptr;
797 this->auth_buf_pos_ = 0;
798 this->auth_type_ = 0;
799}
800#endif // USE_OTA_PASSWORD
801
802} // namespace esphome
803#endif
void feed_wdt(uint32_t time=0)
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.
virtual void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
void status_momentary_error(const std::string &name, uint32_t length=5000)
void status_clear_warning()
bool would_block_(int error_code) const
Definition ota_esphome.h:61
std::unique_ptr< ota::OTABackend > backend_
Definition ota_esphome.h:87
bool writeall_(const uint8_t *buf, size_t len)
bool try_read_(size_t to_read, const LogString *desc)
bool try_write_(size_t to_write, const LogString *desc)
std::unique_ptr< uint8_t[]> auth_buf_
Definition ota_esphome.h:96
bool handle_write_error_(ssize_t written, const LogString *desc)
void log_auth_warning_(const LogString *msg)
float get_setup_priority() const override
void send_error_and_cleanup_(ota::OTAResponseTypes error)
Definition ota_esphome.h:74
bool handle_read_error_(ssize_t read, const LogString *desc)
void log_read_error_(const LogString *what)
bool readall_(uint8_t *buf, size_t len)
void set_port(uint16_t port)
Manually set the port OTA should listen on.
bool write_byte_(uint8_t byte)
Definition ota_esphome.h:56
std::unique_ptr< socket::Socket > server_
Definition ota_esphome.h:85
void transition_ota_state_(OTAState next_state)
Definition ota_esphome.h:64
void log_remote_closed_(const LogString *during)
std::unique_ptr< socket::Socket > client_
Definition ota_esphome.h:86
void log_start_(const LogString *phase)
void log_socket_error_(const LogString *msg)
Base class for hash algorithms.
Definition hash_base.h:11
void get_hex(char *output)
Retrieve the hash as hex characters.
Definition hash_base.h:29
bool equals_hex(const char *expected)
Compare the hash against a provided hex-encoded hash.
Definition hash_base.h:41
virtual void calculate()=0
Compute the hash based on provided data.
virtual void init()=0
Initialize a new hash computation.
virtual size_t get_size() const =0
Get the size of the hash in bytes (16 for MD5, 32 for SHA256)
virtual void add(const uint8_t *data, size_t len)=0
Add bytes of data for the hash.
StateCallbackManager state_callback_
Definition ota_backend.h:92
uint16_t addr_len
uint32_t socklen_t
Definition headers.h:97
__int64 ssize_t
Definition httplib.h:178
const char * get_use_address()
Get the active network hostname.
Definition util.cpp:88
void register_ota_platform(OTAComponent *ota_caller)
std::unique_ptr< ota::OTABackend > make_ota_backend()
@ OTA_RESPONSE_UPDATE_PREPARE_OK
Definition ota_backend.h:21
@ OTA_RESPONSE_SUPPORTS_COMPRESSION
Definition ota_backend.h:25
@ OTA_RESPONSE_BIN_MD5_OK
Definition ota_backend.h:22
@ OTA_RESPONSE_UPDATE_END_OK
Definition ota_backend.h:24
@ OTA_RESPONSE_RECEIVE_OK
Definition ota_backend.h:23
@ OTA_RESPONSE_CHUNK_OK
Definition ota_backend.h:26
@ OTA_RESPONSE_ERROR_AUTH_INVALID
Definition ota_backend.h:30
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:41
@ OTA_RESPONSE_REQUEST_SHA256_AUTH
Definition ota_backend.h:17
@ OTA_RESPONSE_ERROR_MAGIC
Definition ota_backend.h:28
@ OTA_RESPONSE_HEADER_OK
Definition ota_backend.h:19
@ OTA_RESPONSE_REQUEST_AUTH
Definition ota_backend.h:16
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:66
std::unique_ptr< Socket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.cpp:44
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().
Definition socket.cpp:82
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
std::string size_t len
Definition helpers.h:500
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:31
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.