ESPHome 2025.9.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
12#include "esphome/core/hal.h"
13#include "esphome/core/log.h"
14#include "esphome/core/util.h"
15
16#include <cerrno>
17#include <cstdio>
18
19namespace esphome {
20
21static const char *const TAG = "esphome.ota";
22static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
23static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 10000; // milliseconds for initial handshake
24static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 90000; // milliseconds for data transfer
25
27#ifdef USE_OTA_STATE_CALLBACK
29#endif
30
31 this->server_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0); // monitored for incoming connections
32 if (this->server_ == nullptr) {
33 this->log_socket_error_("creation");
34 this->mark_failed();
35 return;
36 }
37 int enable = 1;
38 int err = this->server_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
39 if (err != 0) {
40 this->log_socket_error_("reuseaddr");
41 // we can still continue
42 }
43 err = this->server_->setblocking(false);
44 if (err != 0) {
45 this->log_socket_error_("non-blocking");
46 this->mark_failed();
47 return;
48 }
49
50 struct sockaddr_storage server;
51
52 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
53 if (sl == 0) {
54 this->log_socket_error_("set sockaddr");
55 this->mark_failed();
56 return;
57 }
58
59 err = this->server_->bind((struct sockaddr *) &server, sizeof(server));
60 if (err != 0) {
61 this->log_socket_error_("bind");
62 this->mark_failed();
63 return;
64 }
65
66 err = this->server_->listen(4);
67 if (err != 0) {
68 this->log_socket_error_("listen");
69 this->mark_failed();
70 return;
71 }
72}
73
75 ESP_LOGCONFIG(TAG,
76 "Over-The-Air updates:\n"
77 " Address: %s:%u\n"
78 " Version: %d",
79 network::get_use_address().c_str(), this->port_, USE_OTA_VERSION);
80#ifdef USE_OTA_PASSWORD
81 if (!this->password_.empty()) {
82 ESP_LOGCONFIG(TAG, " Password configured");
83 }
84#endif
85}
86
88 // Skip handle_handshake_() call if no client connected and no incoming connections
89 // This optimization reduces idle loop overhead when OTA is not active
90 // Note: No need to check server_ for null as the component is marked failed in setup()
91 // if server_ creation fails
92 if (this->client_ != nullptr || this->server_->ready()) {
93 this->handle_handshake_();
94 }
95}
96
97static const uint8_t FEATURE_SUPPORTS_COMPRESSION = 0x01;
98
105
106 if (this->client_ == nullptr) {
107 // We already checked server_->ready() in loop(), so we can accept directly
108 struct sockaddr_storage source_addr;
109 socklen_t addr_len = sizeof(source_addr);
110 int enable = 1;
111
112 this->client_ = this->server_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
113 if (this->client_ == nullptr)
114 return;
115 int err = this->client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(int));
116 if (err != 0) {
117 this->log_socket_error_("nodelay");
118 this->cleanup_connection_();
119 return;
120 }
121 err = this->client_->setblocking(false);
122 if (err != 0) {
123 this->log_socket_error_("non-blocking");
124 this->cleanup_connection_();
125 return;
126 }
127 this->log_start_("handshake");
129 }
130
131 // Check for handshake timeout
132 uint32_t now = App.get_loop_component_start_time();
133 if (now - this->client_connect_time_ > OTA_SOCKET_TIMEOUT_HANDSHAKE) {
134 ESP_LOGW(TAG, "Handshake timeout");
135 this->cleanup_connection_();
136 return;
137 }
138
139 // Try to read first byte of magic bytes
140 uint8_t first_byte;
141 ssize_t read = this->client_->read(&first_byte, 1);
142
143 if (read == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
144 return; // No data yet, try again next loop
145 }
146
147 if (read <= 0) {
148 // Error or connection closed
149 if (read == -1) {
150 this->log_socket_error_("reading first byte");
151 } else {
152 ESP_LOGW(TAG, "Remote closed during handshake");
153 }
154 this->cleanup_connection_();
155 return;
156 }
157
158 // Got first byte, check if it's the magic byte
159 if (first_byte != 0x6C) {
160 ESP_LOGW(TAG, "Invalid initial byte: 0x%02X", first_byte);
161 this->cleanup_connection_();
162 return;
163 }
164
165 // First byte is valid, continue with data handling
166 this->handle_data_();
167}
168
176 bool update_started = false;
177 size_t total = 0;
178 uint32_t last_progress = 0;
179 uint8_t buf[1024];
180 char *sbuf = reinterpret_cast<char *>(buf);
181 size_t ota_size;
182 uint8_t ota_features;
183 std::unique_ptr<ota::OTABackend> backend;
184 (void) ota_features;
185#if USE_OTA_VERSION == 2
186 size_t size_acknowledged = 0;
187#endif
188
189 // Read remaining 4 bytes of magic (we already read the first byte 0x6C in handle_handshake_)
190 if (!this->readall_(buf, 4)) {
191 this->log_read_error_("magic bytes");
192 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
193 }
194 // Check remaining magic bytes: 0x26, 0xF7, 0x5C, 0x45
195 if (buf[0] != 0x26 || buf[1] != 0xF7 || buf[2] != 0x5C || buf[3] != 0x45) {
196 ESP_LOGW(TAG, "Magic bytes mismatch! 0x6C-0x%02X-0x%02X-0x%02X-0x%02X", buf[0], buf[1], buf[2], buf[3]);
198 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
199 }
200
201 // Send OK and version - 2 bytes
202 buf[0] = ota::OTA_RESPONSE_OK;
203 buf[1] = USE_OTA_VERSION;
204 this->writeall_(buf, 2);
205
206 backend = ota::make_ota_backend();
207
208 // Read features - 1 byte
209 if (!this->readall_(buf, 1)) {
210 this->log_read_error_("features");
211 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
212 }
213 ota_features = buf[0]; // NOLINT
214 ESP_LOGV(TAG, "Features: 0x%02X", ota_features);
215
216 // Acknowledge header - 1 byte
218 if ((ota_features & FEATURE_SUPPORTS_COMPRESSION) != 0 && backend->supports_compression()) {
220 }
221
222 this->writeall_(buf, 1);
223
224#ifdef USE_OTA_PASSWORD
225 if (!this->password_.empty()) {
227 this->writeall_(buf, 1);
228 md5::MD5Digest md5{};
229 md5.init();
230 sprintf(sbuf, "%08" PRIx32, random_uint32());
231 md5.add(sbuf, 8);
232 md5.calculate();
233 md5.get_hex(sbuf);
234 ESP_LOGV(TAG, "Auth: Nonce is %s", sbuf);
235
236 // Send nonce, 32 bytes hex MD5
237 if (!this->writeall_(reinterpret_cast<uint8_t *>(sbuf), 32)) {
238 ESP_LOGW(TAG, "Auth: Writing nonce failed");
239 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
240 }
241
242 // prepare challenge
243 md5.init();
244 md5.add(this->password_.c_str(), this->password_.length());
245 // add nonce
246 md5.add(sbuf, 32);
247
248 // Receive cnonce, 32 bytes hex MD5
249 if (!this->readall_(buf, 32)) {
250 ESP_LOGW(TAG, "Auth: Reading cnonce failed");
251 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
252 }
253 sbuf[32] = '\0';
254 ESP_LOGV(TAG, "Auth: CNonce is %s", sbuf);
255 // add cnonce
256 md5.add(sbuf, 32);
257
258 // calculate result
259 md5.calculate();
260 md5.get_hex(sbuf);
261 ESP_LOGV(TAG, "Auth: Result is %s", sbuf);
262
263 // Receive result, 32 bytes hex MD5
264 if (!this->readall_(buf + 64, 32)) {
265 ESP_LOGW(TAG, "Auth: Reading response failed");
266 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
267 }
268 sbuf[64 + 32] = '\0';
269 ESP_LOGV(TAG, "Auth: Response is %s", sbuf + 64);
270
271 bool matches = true;
272 for (uint8_t i = 0; i < 32; i++)
273 matches = matches && buf[i] == buf[64 + i];
274
275 if (!matches) {
276 ESP_LOGW(TAG, "Auth failed! Passwords do not match");
278 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
279 }
280 }
281#endif // USE_OTA_PASSWORD
282
283 // Acknowledge auth OK - 1 byte
285 this->writeall_(buf, 1);
286
287 // Read size, 4 bytes MSB first
288 if (!this->readall_(buf, 4)) {
289 this->log_read_error_("size");
290 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
291 }
292 ota_size = 0;
293 for (uint8_t i = 0; i < 4; i++) {
294 ota_size <<= 8;
295 ota_size |= buf[i];
296 }
297 ESP_LOGV(TAG, "Size is %u bytes", ota_size);
298
299 // Now that we've passed authentication and are actually
300 // starting the update, set the warning status and notify
301 // listeners. This ensures that port scanners do not
302 // accidentally trigger the update process.
303 this->log_start_("update");
304 this->status_set_warning();
305#ifdef USE_OTA_STATE_CALLBACK
306 this->state_callback_.call(ota::OTA_STARTED, 0.0f, 0);
307#endif
308
309 // This will block for a few seconds as it locks flash
310 error_code = backend->begin(ota_size);
311 if (error_code != ota::OTA_RESPONSE_OK)
312 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
313 update_started = true;
314
315 // Acknowledge prepare OK - 1 byte
317 this->writeall_(buf, 1);
318
319 // Read binary MD5, 32 bytes
320 if (!this->readall_(buf, 32)) {
321 this->log_read_error_("MD5 checksum");
322 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
323 }
324 sbuf[32] = '\0';
325 ESP_LOGV(TAG, "Update: Binary MD5 is %s", sbuf);
326 backend->set_update_md5(sbuf);
327
328 // Acknowledge MD5 OK - 1 byte
330 this->writeall_(buf, 1);
331
332 while (total < ota_size) {
333 // TODO: timeout check
334 size_t requested = std::min(sizeof(buf), ota_size - total);
335 ssize_t read = this->client_->read(buf, requested);
336 if (read == -1) {
337 if (errno == EAGAIN || errno == EWOULDBLOCK) {
339 continue;
340 }
341 ESP_LOGW(TAG, "Read error, errno %d", errno);
342 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
343 } else if (read == 0) {
344 // $ man recv
345 // "When a stream socket peer has performed an orderly shutdown, the return value will
346 // be 0 (the traditional "end-of-file" return)."
347 ESP_LOGW(TAG, "Remote closed connection");
348 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
349 }
350
351 error_code = backend->write(buf, read);
352 if (error_code != ota::OTA_RESPONSE_OK) {
353 ESP_LOGW(TAG, "Flash write error, code: %d", error_code);
354 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
355 }
356 total += read;
357#if USE_OTA_VERSION == 2
358 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) {
360 this->writeall_(buf, 1);
361 size_acknowledged += OTA_BLOCK_SIZE;
362 }
363#endif
364
365 uint32_t now = millis();
366 if (now - last_progress > 1000) {
367 last_progress = now;
368 float percentage = (total * 100.0f) / ota_size;
369 ESP_LOGD(TAG, "Progress: %0.1f%%", percentage);
370#ifdef USE_OTA_STATE_CALLBACK
371 this->state_callback_.call(ota::OTA_IN_PROGRESS, percentage, 0);
372#endif
373 // feed watchdog and give other tasks a chance to run
375 }
376 }
377
378 // Acknowledge receive OK - 1 byte
380 this->writeall_(buf, 1);
381
382 error_code = backend->end();
383 if (error_code != ota::OTA_RESPONSE_OK) {
384 ESP_LOGW(TAG, "Error ending update! code: %d", error_code);
385 goto error; // NOLINT(cppcoreguidelines-avoid-goto)
386 }
387
388 // Acknowledge Update end OK - 1 byte
390 this->writeall_(buf, 1);
391
392 // Read ACK
393 if (!this->readall_(buf, 1) || buf[0] != ota::OTA_RESPONSE_OK) {
394 this->log_read_error_("ack");
395 // do not go to error, this is not fatal
396 }
397
398 this->cleanup_connection_();
399 delay(10);
400 ESP_LOGI(TAG, "Update complete");
401 this->status_clear_warning();
402#ifdef USE_OTA_STATE_CALLBACK
403 this->state_callback_.call(ota::OTA_COMPLETED, 100.0f, 0);
404#endif
405 delay(100); // NOLINT
407
408error:
409 buf[0] = static_cast<uint8_t>(error_code);
410 this->writeall_(buf, 1);
411 this->cleanup_connection_();
412
413 if (backend != nullptr && update_started) {
414 backend->abort();
415 }
416
417 this->status_momentary_error("onerror", 5000);
418#ifdef USE_OTA_STATE_CALLBACK
419 this->state_callback_.call(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
420#endif
421}
422
423bool ESPHomeOTAComponent::readall_(uint8_t *buf, size_t len) {
424 uint32_t start = millis();
425 uint32_t at = 0;
426 while (len - at > 0) {
427 uint32_t now = millis();
428 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
429 ESP_LOGW(TAG, "Timeout reading %d bytes", len);
430 return false;
431 }
432
433 ssize_t read = this->client_->read(buf + at, len - at);
434 if (read == -1) {
435 if (errno != EAGAIN && errno != EWOULDBLOCK) {
436 ESP_LOGW(TAG, "Error reading %d bytes, errno %d", len, errno);
437 return false;
438 }
439 } else if (read == 0) {
440 ESP_LOGW(TAG, "Remote closed connection");
441 return false;
442 } else {
443 at += read;
444 }
446 }
447
448 return true;
449}
450bool ESPHomeOTAComponent::writeall_(const uint8_t *buf, size_t len) {
451 uint32_t start = millis();
452 uint32_t at = 0;
453 while (len - at > 0) {
454 uint32_t now = millis();
455 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
456 ESP_LOGW(TAG, "Timeout writing %d bytes", len);
457 return false;
458 }
459
460 ssize_t written = this->client_->write(buf + at, len - at);
461 if (written == -1) {
462 if (errno != EAGAIN && errno != EWOULDBLOCK) {
463 ESP_LOGW(TAG, "Error writing %d bytes, errno %d", len, errno);
464 return false;
465 }
466 } else {
467 at += written;
468 }
470 }
471 return true;
472}
473
475uint16_t ESPHomeOTAComponent::get_port() const { return this->port_; }
476void ESPHomeOTAComponent::set_port(uint16_t port) { this->port_ = port; }
477
478void ESPHomeOTAComponent::log_socket_error_(const char *msg) { ESP_LOGW(TAG, "Socket %s: errno %d", msg, errno); }
479
480void ESPHomeOTAComponent::log_read_error_(const char *what) { ESP_LOGW(TAG, "Read %s failed", what); }
481
482void ESPHomeOTAComponent::log_start_(const char *phase) {
483 ESP_LOGD(TAG, "Starting %s from %s", phase, this->client_->getpeername().c_str());
484}
485
487 this->client_->close();
488 this->client_ = nullptr;
489 this->client_connect_time_ = 0;
490}
491
496
497} // namespace esphome
498#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 writeall_(const uint8_t *buf, size_t len)
void log_start_(const char *phase)
void log_socket_error_(const char *msg)
float get_setup_priority() const override
bool readall_(uint8_t *buf, size_t len)
void set_port(uint16_t port)
Manually set the port OTA should listen on.
std::unique_ptr< socket::Socket > server_
Definition ota_esphome.h:47
void log_read_error_(const char *what)
std::unique_ptr< socket::Socket > client_
Definition ota_esphome.h:48
void init()
Initialize a new MD5 digest computation.
Definition md5.cpp:11
StateCallbackManager state_callback_
Definition ota_backend.h:91
uint32_t socklen_t
Definition headers.h:97
__int64 ssize_t
Definition httplib.h:175
std::string 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:20
@ OTA_RESPONSE_SUPPORTS_COMPRESSION
Definition ota_backend.h:24
@ OTA_RESPONSE_BIN_MD5_OK
Definition ota_backend.h:21
@ OTA_RESPONSE_UPDATE_END_OK
Definition ota_backend.h:23
@ OTA_RESPONSE_RECEIVE_OK
Definition ota_backend.h:22
@ OTA_RESPONSE_CHUNK_OK
Definition ota_backend.h:25
@ OTA_RESPONSE_ERROR_AUTH_INVALID
Definition ota_backend.h:29
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:40
@ OTA_RESPONSE_ERROR_MAGIC
Definition ota_backend.h:27
@ OTA_RESPONSE_HEADER_OK
Definition ota_backend.h:18
@ 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:57
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
std::string size_t len
Definition helpers.h:279
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.