ESPHome  2023.11.6
ota_component.cpp
Go to the documentation of this file.
1 #include "ota_component.h"
2 #include "ota_backend.h"
7 #include "ota_backend_esp_idf.h"
8 
9 #include "esphome/core/log.h"
11 #include "esphome/core/hal.h"
12 #include "esphome/core/util.h"
15 
16 #include <cerrno>
17 #include <cstdio>
18 
19 namespace esphome {
20 namespace ota {
21 
22 static const char *const TAG = "ota";
23 
24 static const uint8_t OTA_VERSION_1_0 = 1;
25 
26 OTAComponent *global_ota_component = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
27 
28 std::unique_ptr<OTABackend> make_ota_backend() {
29 #ifdef USE_ARDUINO
30 #ifdef USE_ESP8266
31  return make_unique<ArduinoESP8266OTABackend>();
32 #endif // USE_ESP8266
33 #ifdef USE_ESP32
34  return make_unique<ArduinoESP32OTABackend>();
35 #endif // USE_ESP32
36 #endif // USE_ARDUINO
37 #ifdef USE_ESP_IDF
38  return make_unique<IDFOTABackend>();
39 #endif // USE_ESP_IDF
40 #ifdef USE_RP2040
41  return make_unique<ArduinoRP2040OTABackend>();
42 #endif // USE_RP2040
43 #ifdef USE_LIBRETINY
44  return make_unique<ArduinoLibreTinyOTABackend>();
45 #endif
46 }
47 
48 OTAComponent::OTAComponent() { global_ota_component = this; }
49 
51  server_ = socket::socket_ip(SOCK_STREAM, 0);
52  if (server_ == nullptr) {
53  ESP_LOGW(TAG, "Could not create socket.");
54  this->mark_failed();
55  return;
56  }
57  int enable = 1;
58  int err = server_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
59  if (err != 0) {
60  ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
61  // we can still continue
62  }
63  err = server_->setblocking(false);
64  if (err != 0) {
65  ESP_LOGW(TAG, "Socket unable to set nonblocking mode: errno %d", err);
66  this->mark_failed();
67  return;
68  }
69 
70  struct sockaddr_storage server;
71 
72  socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
73  if (sl == 0) {
74  ESP_LOGW(TAG, "Socket unable to set sockaddr: errno %d", errno);
75  this->mark_failed();
76  return;
77  }
78 
79  err = server_->bind((struct sockaddr *) &server, sizeof(server));
80  if (err != 0) {
81  ESP_LOGW(TAG, "Socket unable to bind: errno %d", errno);
82  this->mark_failed();
83  return;
84  }
85 
86  err = server_->listen(4);
87  if (err != 0) {
88  ESP_LOGW(TAG, "Socket unable to listen: errno %d", errno);
89  this->mark_failed();
90  return;
91  }
92 
93  this->dump_config();
94 }
95 
97  ESP_LOGCONFIG(TAG, "Over-The-Air Updates:");
98  ESP_LOGCONFIG(TAG, " Address: %s:%u", network::get_use_address().c_str(), this->port_);
99 #ifdef USE_OTA_PASSWORD
100  if (!this->password_.empty()) {
101  ESP_LOGCONFIG(TAG, " Using Password.");
102  }
103 #endif
104  if (this->has_safe_mode_ && this->safe_mode_rtc_value_ > 1 &&
106  ESP_LOGW(TAG, "Last Boot was an unhandled reset, will proceed to safe mode in %" PRIu32 " restarts",
108  }
109 }
110 
112  this->handle_();
113 
114  if (this->has_safe_mode_ && (millis() - this->safe_mode_start_time_) > this->safe_mode_enable_time_) {
115  this->has_safe_mode_ = false;
116  // successful boot, reset counter
117  ESP_LOGI(TAG, "Boot seems successful, resetting boot loop counter.");
118  this->clean_rtc();
119  }
120 }
121 
122 static const uint8_t FEATURE_SUPPORTS_COMPRESSION = 0x01;
123 
126  bool update_started = false;
127  size_t total = 0;
128  uint32_t last_progress = 0;
129  uint8_t buf[1024];
130  char *sbuf = reinterpret_cast<char *>(buf);
131  size_t ota_size;
132  uint8_t ota_features;
133  std::unique_ptr<OTABackend> backend;
134  (void) ota_features;
135 
136  if (client_ == nullptr) {
137  struct sockaddr_storage source_addr;
138  socklen_t addr_len = sizeof(source_addr);
139  client_ = server_->accept((struct sockaddr *) &source_addr, &addr_len);
140  }
141  if (client_ == nullptr)
142  return;
143 
144  int enable = 1;
145  int err = client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(int));
146  if (err != 0) {
147  ESP_LOGW(TAG, "Socket could not enable tcp nodelay, errno: %d", errno);
148  return;
149  }
150 
151  ESP_LOGD(TAG, "Starting OTA Update from %s...", this->client_->getpeername().c_str());
152  this->status_set_warning();
153 #ifdef USE_OTA_STATE_CALLBACK
154  this->state_callback_.call(OTA_STARTED, 0.0f, 0);
155 #endif
156 
157  if (!this->readall_(buf, 5)) {
158  ESP_LOGW(TAG, "Reading magic bytes failed!");
159  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
160  }
161  // 0x6C, 0x26, 0xF7, 0x5C, 0x45
162  if (buf[0] != 0x6C || buf[1] != 0x26 || buf[2] != 0xF7 || buf[3] != 0x5C || buf[4] != 0x45) {
163  ESP_LOGW(TAG, "Magic bytes do not match! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", buf[0], buf[1], buf[2], buf[3],
164  buf[4]);
165  error_code = OTA_RESPONSE_ERROR_MAGIC;
166  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
167  }
168 
169  // Send OK and version - 2 bytes
170  buf[0] = OTA_RESPONSE_OK;
171  buf[1] = OTA_VERSION_1_0;
172  this->writeall_(buf, 2);
173 
174  backend = make_ota_backend();
175 
176  // Read features - 1 byte
177  if (!this->readall_(buf, 1)) {
178  ESP_LOGW(TAG, "Reading features failed!");
179  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
180  }
181  ota_features = buf[0]; // NOLINT
182  ESP_LOGV(TAG, "OTA features is 0x%02X", ota_features);
183 
184  // Acknowledge header - 1 byte
185  buf[0] = OTA_RESPONSE_HEADER_OK;
186  if ((ota_features & FEATURE_SUPPORTS_COMPRESSION) != 0 && backend->supports_compression()) {
188  }
189 
190  this->writeall_(buf, 1);
191 
192 #ifdef USE_OTA_PASSWORD
193  if (!this->password_.empty()) {
194  buf[0] = OTA_RESPONSE_REQUEST_AUTH;
195  this->writeall_(buf, 1);
196  md5::MD5Digest md5{};
197  md5.init();
198  sprintf(sbuf, "%08" PRIx32, random_uint32());
199  md5.add(sbuf, 8);
200  md5.calculate();
201  md5.get_hex(sbuf);
202  ESP_LOGV(TAG, "Auth: Nonce is %s", sbuf);
203 
204  // Send nonce, 32 bytes hex MD5
205  if (!this->writeall_(reinterpret_cast<uint8_t *>(sbuf), 32)) {
206  ESP_LOGW(TAG, "Auth: Writing nonce failed!");
207  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
208  }
209 
210  // prepare challenge
211  md5.init();
212  md5.add(this->password_.c_str(), this->password_.length());
213  // add nonce
214  md5.add(sbuf, 32);
215 
216  // Receive cnonce, 32 bytes hex MD5
217  if (!this->readall_(buf, 32)) {
218  ESP_LOGW(TAG, "Auth: Reading cnonce failed!");
219  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
220  }
221  sbuf[32] = '\0';
222  ESP_LOGV(TAG, "Auth: CNonce is %s", sbuf);
223  // add cnonce
224  md5.add(sbuf, 32);
225 
226  // calculate result
227  md5.calculate();
228  md5.get_hex(sbuf);
229  ESP_LOGV(TAG, "Auth: Result is %s", sbuf);
230 
231  // Receive result, 32 bytes hex MD5
232  if (!this->readall_(buf + 64, 32)) {
233  ESP_LOGW(TAG, "Auth: Reading response failed!");
234  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
235  }
236  sbuf[64 + 32] = '\0';
237  ESP_LOGV(TAG, "Auth: Response is %s", sbuf + 64);
238 
239  bool matches = true;
240  for (uint8_t i = 0; i < 32; i++)
241  matches = matches && buf[i] == buf[64 + i];
242 
243  if (!matches) {
244  ESP_LOGW(TAG, "Auth failed! Passwords do not match!");
245  error_code = OTA_RESPONSE_ERROR_AUTH_INVALID;
246  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
247  }
248  }
249 #endif // USE_OTA_PASSWORD
250 
251  // Acknowledge auth OK - 1 byte
252  buf[0] = OTA_RESPONSE_AUTH_OK;
253  this->writeall_(buf, 1);
254 
255  // Read size, 4 bytes MSB first
256  if (!this->readall_(buf, 4)) {
257  ESP_LOGW(TAG, "Reading size failed!");
258  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
259  }
260  ota_size = 0;
261  for (uint8_t i = 0; i < 4; i++) {
262  ota_size <<= 8;
263  ota_size |= buf[i];
264  }
265  ESP_LOGV(TAG, "OTA size is %u bytes", ota_size);
266 
267  error_code = backend->begin(ota_size);
268  if (error_code != OTA_RESPONSE_OK)
269  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
270  update_started = true;
271 
272  // Acknowledge prepare OK - 1 byte
274  this->writeall_(buf, 1);
275 
276  // Read binary MD5, 32 bytes
277  if (!this->readall_(buf, 32)) {
278  ESP_LOGW(TAG, "Reading binary MD5 checksum failed!");
279  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
280  }
281  sbuf[32] = '\0';
282  ESP_LOGV(TAG, "Update: Binary MD5 is %s", sbuf);
283  backend->set_update_md5(sbuf);
284 
285  // Acknowledge MD5 OK - 1 byte
286  buf[0] = OTA_RESPONSE_BIN_MD5_OK;
287  this->writeall_(buf, 1);
288 
289  while (total < ota_size) {
290  // TODO: timeout check
291  size_t requested = std::min(sizeof(buf), ota_size - total);
292  ssize_t read = this->client_->read(buf, requested);
293  if (read == -1) {
294  if (errno == EAGAIN || errno == EWOULDBLOCK) {
295  App.feed_wdt();
296  delay(1);
297  continue;
298  }
299  ESP_LOGW(TAG, "Error receiving data for update, errno: %d", errno);
300  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
301  } else if (read == 0) {
302  // $ man recv
303  // "When a stream socket peer has performed an orderly shutdown, the return value will
304  // be 0 (the traditional "end-of-file" return)."
305  ESP_LOGW(TAG, "Remote end closed connection");
306  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
307  }
308 
309  error_code = backend->write(buf, read);
310  if (error_code != OTA_RESPONSE_OK) {
311  ESP_LOGW(TAG, "Error writing binary data to flash!, error_code: %d", error_code);
312  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
313  }
314  total += read;
315 
316  uint32_t now = millis();
317  if (now - last_progress > 1000) {
318  last_progress = now;
319  float percentage = (total * 100.0f) / ota_size;
320  ESP_LOGD(TAG, "OTA in progress: %0.1f%%", percentage);
321 #ifdef USE_OTA_STATE_CALLBACK
322  this->state_callback_.call(OTA_IN_PROGRESS, percentage, 0);
323 #endif
324  // feed watchdog and give other tasks a chance to run
325  App.feed_wdt();
326  yield();
327  }
328  }
329 
330  // Acknowledge receive OK - 1 byte
331  buf[0] = OTA_RESPONSE_RECEIVE_OK;
332  this->writeall_(buf, 1);
333 
334  error_code = backend->end();
335  if (error_code != OTA_RESPONSE_OK) {
336  ESP_LOGW(TAG, "Error ending OTA!, error_code: %d", error_code);
337  goto error; // NOLINT(cppcoreguidelines-avoid-goto)
338  }
339 
340  // Acknowledge Update end OK - 1 byte
342  this->writeall_(buf, 1);
343 
344  // Read ACK
345  if (!this->readall_(buf, 1) || buf[0] != OTA_RESPONSE_OK) {
346  ESP_LOGW(TAG, "Reading back acknowledgement failed!");
347  // do not go to error, this is not fatal
348  }
349 
350  this->client_->close();
351  this->client_ = nullptr;
352  delay(10);
353  ESP_LOGI(TAG, "OTA update finished!");
354  this->status_clear_warning();
355 #ifdef USE_OTA_STATE_CALLBACK
356  this->state_callback_.call(OTA_COMPLETED, 100.0f, 0);
357 #endif
358  delay(100); // NOLINT
359  App.safe_reboot();
360 
361 error:
362  buf[0] = static_cast<uint8_t>(error_code);
363  this->writeall_(buf, 1);
364  this->client_->close();
365  this->client_ = nullptr;
366 
367  if (backend != nullptr && update_started) {
368  backend->abort();
369  }
370 
371  this->status_momentary_error("onerror", 5000);
372 #ifdef USE_OTA_STATE_CALLBACK
373  this->state_callback_.call(OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
374 #endif
375 }
376 
377 bool OTAComponent::readall_(uint8_t *buf, size_t len) {
378  uint32_t start = millis();
379  uint32_t at = 0;
380  while (len - at > 0) {
381  uint32_t now = millis();
382  if (now - start > 1000) {
383  ESP_LOGW(TAG, "Timed out reading %d bytes of data", len);
384  return false;
385  }
386 
387  ssize_t read = this->client_->read(buf + at, len - at);
388  if (read == -1) {
389  if (errno == EAGAIN || errno == EWOULDBLOCK) {
390  App.feed_wdt();
391  delay(1);
392  continue;
393  }
394  ESP_LOGW(TAG, "Failed to read %d bytes of data, errno: %d", len, errno);
395  return false;
396  } else if (read == 0) {
397  ESP_LOGW(TAG, "Remote closed connection");
398  return false;
399  } else {
400  at += read;
401  }
402  App.feed_wdt();
403  delay(1);
404  }
405 
406  return true;
407 }
408 bool OTAComponent::writeall_(const uint8_t *buf, size_t len) {
409  uint32_t start = millis();
410  uint32_t at = 0;
411  while (len - at > 0) {
412  uint32_t now = millis();
413  if (now - start > 1000) {
414  ESP_LOGW(TAG, "Timed out writing %d bytes of data", len);
415  return false;
416  }
417 
418  ssize_t written = this->client_->write(buf + at, len - at);
419  if (written == -1) {
420  if (errno == EAGAIN || errno == EWOULDBLOCK) {
421  App.feed_wdt();
422  delay(1);
423  continue;
424  }
425  ESP_LOGW(TAG, "Failed to write %d bytes of data, errno: %d", len, errno);
426  return false;
427  } else {
428  at += written;
429  }
430  App.feed_wdt();
431  delay(1);
432  }
433  return true;
434 }
435 
437 uint16_t OTAComponent::get_port() const { return this->port_; }
438 void OTAComponent::set_port(uint16_t port) { this->port_ = port; }
439 
440 void OTAComponent::set_safe_mode_pending(const bool &pending) {
441  if (!this->has_safe_mode_)
442  return;
443 
444  uint32_t current_rtc = this->read_rtc_();
445 
446  if (pending && current_rtc != esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) {
447  ESP_LOGI(TAG, "Device will enter safe mode on next boot.");
449  }
450 
451  if (!pending && current_rtc == esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC) {
452  ESP_LOGI(TAG, "Safe mode pending has been cleared");
453  this->clean_rtc();
454  }
455 }
458 }
459 
460 bool OTAComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time) {
461  this->has_safe_mode_ = true;
462  this->safe_mode_start_time_ = millis();
463  this->safe_mode_enable_time_ = enable_time;
464  this->safe_mode_num_attempts_ = num_attempts;
465  this->rtc_ = global_preferences->make_preference<uint32_t>(233825507UL, false);
466  this->safe_mode_rtc_value_ = this->read_rtc_();
467 
468  bool is_manual_safe_mode = this->safe_mode_rtc_value_ == esphome::ota::OTAComponent::ENTER_SAFE_MODE_MAGIC;
469 
470  if (is_manual_safe_mode) {
471  ESP_LOGI(TAG, "Safe mode has been entered manually");
472  } else {
473  ESP_LOGCONFIG(TAG, "There have been %" PRIu32 " suspected unsuccessful boot attempts.", this->safe_mode_rtc_value_);
474  }
475 
476  if (this->safe_mode_rtc_value_ >= num_attempts || is_manual_safe_mode) {
477  this->clean_rtc();
478 
479  if (!is_manual_safe_mode) {
480  ESP_LOGE(TAG, "Boot loop detected. Proceeding to safe mode.");
481  }
482 
483  this->status_set_error();
484  this->set_timeout(enable_time, []() {
485  ESP_LOGE(TAG, "No OTA attempt made, restarting.");
486  App.reboot();
487  });
488 
489  // Delay here to allow power to stabilise before Wi-Fi/Ethernet is initialised.
490  delay(300); // NOLINT
491  App.setup();
492 
493  ESP_LOGI(TAG, "Waiting for OTA attempt.");
494 
495  return true;
496  } else {
497  // increment counter
498  this->write_rtc_(this->safe_mode_rtc_value_ + 1);
499  return false;
500  }
501 }
503  this->rtc_.save(&val);
505 }
507  uint32_t val;
508  if (!this->rtc_.load(&val))
509  return 0;
510  return val;
511 }
515  this->clean_rtc();
516 }
517 
518 #ifdef USE_OTA_STATE_CALLBACK
519 void OTAComponent::add_on_state_callback(std::function<void(OTAState, float, uint8_t)> &&callback) {
520  this->state_callback_.add(std::move(callback));
521 }
522 #endif
523 
524 } // namespace ota
525 } // namespace esphome
void init()
Initialize a new MD5 digest computation.
Definition: md5.cpp:10
std::unique_ptr< Socket > socket_ip(int type, int protocol)
Create a socket in the newest available IP domain (IPv6 or IPv4) of the given type and protocol...
Definition: socket.cpp:12
uint32_t safe_mode_enable_time_
The time safe mode should be on for.
Definition: ota_component.h:95
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition: component.cpp:25
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:53
std::string get_use_address()
Get the active network hostname.
Definition: util.cpp:52
ESPPreferenceObject rtc_
Definition: ota_component.h:98
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition: helpers.cpp:185
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:68
void add_on_state_callback(std::function< void(OTAState, float, uint8_t)> &&callback)
uint32_t socklen_t
Definition: headers.h:97
mopeka_std_values val[4]
void setup()
Set up all the registered components. Call this at the end of your setup() function.
Definition: application.cpp:28
uint32_t safe_mode_start_time_
stores when safe mode was enabled.
Definition: ota_component.h:94
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
void status_momentary_error(const std::string &name, uint32_t length=5000)
Definition: component.cpp:159
bool readall_(uint8_t *buf, size_t len)
bool save(const T *src)
Definition: preferences.h:21
static const uint32_t ENTER_SAFE_MODE_MAGIC
a magic number to indicate that safe mode should be entered on next boot
void set_port(uint16_t port)
Manually set the port OTA should listen on.
ESPPreferences * global_preferences
void status_clear_warning()
Definition: component.cpp:153
std::unique_ptr< socket::Socket > client_
Definition: ota_component.h:91
float get_setup_priority() const override
bool has_safe_mode_
stores whether safe mode can be enabled.
Definition: ota_component.h:93
std::unique_ptr< OTABackend > make_ota_backend()
void write_rtc_(uint32_t val)
Application App
Global storage of Application pointer - only one Application can exist.
void on_safe_shutdown() override
void status_set_warning()
Definition: component.cpp:145
OTAComponent * global_ota_component
bool should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time)
std::string size_t len
Definition: helpers.h:292
void IRAM_ATTR HOT yield()
Definition: core.cpp:24
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:112
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
virtual bool sync()=0
Commit pending writes to flash.
void set_safe_mode_pending(const bool &pending)
Set to true if the next startup will enter safe mode.
bool writeall_(const uint8_t *buf, size_t len)
std::unique_ptr< socket::Socket > server_
Definition: ota_component.h:90
CallbackManager< void(OTAState, float, uint8_t)> state_callback_
OTAComponent provides a simple way to integrate Over-the-Air updates into your app using ArduinoOTA...
Definition: ota_component.h:43
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26