18#ifdef USE_LWIP_FAST_SELECT
28static const char *
const TAG =
"esphome.ota";
29static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
30static constexpr size_t OTA_BUFFER_SIZE = 1024;
31static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 20000;
32static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 90000;
36static ESPHomeOTAComponent *global_esphome_ota_component =
nullptr;
40 if (global_esphome_ota_component !=
nullptr) {
52 int err = this->
server_->
setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
84 global_esphome_ota_component =
this;
85#ifdef USE_LWIP_FAST_SELECT
94 "Over-The-Air updates:\n"
98#ifdef USE_OTA_PASSWORD
100 ESP_LOGCONFIG(TAG,
" Password configured");
117static const uint8_t FEATURE_SUPPORTS_COMPRESSION = 0x01;
118static const uint8_t FEATURE_SUPPORTS_SHA256_AUTH = 0x02;
127 if (this->
client_ ==
nullptr) {
136 int err = this->
client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable,
sizeof(
int));
142 err = this->
client_->setblocking(
false);
157 ESP_LOGW(TAG,
"Handshake timeout");
165 if (!this->
try_read_(5, LOG_STR(
"read magic"))) {
170 static const uint8_t MAGIC_BYTES[5] = {0x6C, 0x26, 0xF7, 0x5C, 0x45};
172 ESP_LOGW(TAG,
"Magic bytes mismatch! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", this->
handshake_buf_[0],
187 if (!this->
try_write_(2, LOG_STR(
"ack magic"))) {
198 if (!this->
try_read_(1, LOG_STR(
"read feature"))) {
205 ((this->
ota_features_ & FEATURE_SUPPORTS_COMPRESSION) != 0 && this->
backend_->supports_compression())
213 if (!this->
try_write_(1, LOG_STR(
"ack feature"))) {
216#ifdef USE_OTA_PASSWORD
229#ifdef USE_OTA_PASSWORD
292 bool update_started =
false;
295 uint8_t buf[OTA_BUFFER_SIZE];
296 char *sbuf =
reinterpret_cast<char *
>(buf);
298#if USE_OTA_VERSION == 2
299 size_t size_acknowledged = 0;
306 this->
client_->setsockopt(SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
307 this->
client_->setsockopt(SOL_SOCKET, SO_SNDTIMEO, &tv,
sizeof(tv));
308 this->
client_->setblocking(
true);
318 ota_size = (
static_cast<size_t>(buf[0]) << 24) | (
static_cast<size_t>(buf[1]) << 16) |
319 (
static_cast<size_t>(buf[2]) << 8) | buf[3];
320 ESP_LOGV(TAG,
"Size is %u bytes", ota_size);
328#ifdef USE_OTA_STATE_LISTENER
333 error_code = this->
backend_->begin(ota_size);
336 update_started =
true;
347 ESP_LOGV(TAG,
"Update: Binary MD5 is %s", sbuf);
348 this->
backend_->set_update_md5(sbuf);
353 while (total < ota_size) {
355 size_t remaining = ota_size - total;
356 size_t requested = remaining < OTA_BUFFER_SIZE ? remaining : OTA_BUFFER_SIZE;
359 const int err = errno;
365 ESP_LOGW(TAG,
"Read err %d", err);
367 }
else if (read == 0) {
368 ESP_LOGW(TAG,
"Remote closed");
372 error_code = this->
backend_->write(buf, read);
374 ESP_LOGW(TAG,
"Flash write err %d", error_code);
378#if USE_OTA_VERSION == 2
379 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) {
381 size_acknowledged += OTA_BLOCK_SIZE;
386 if (now - last_progress > 1000) {
388 float percentage = (total * 100.0f) / ota_size;
389 ESP_LOGD(TAG,
"Progress: %0.1f%%", percentage);
390#ifdef USE_OTA_STATE_LISTENER
403 ESP_LOGW(TAG,
"End update err %d", error_code);
418 ESP_LOGI(TAG,
"Update complete");
420#ifdef USE_OTA_STATE_LISTENER
427 this->
write_byte_(
static_cast<uint8_t
>(error_code));
430 if (this->
backend_ !=
nullptr && update_started) {
437#ifdef USE_OTA_STATE_LISTENER
445 while (
len - at > 0) {
447 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
448 ESP_LOGW(TAG,
"Timeout reading %zu bytes",
len);
454 const int err = errno;
456 ESP_LOGW(TAG,
"Read err %zu bytes, errno %d",
len, err);
459 }
else if (read == 0) {
460 ESP_LOGW(TAG,
"Remote closed");
475 while (
len - at > 0) {
477 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
478 ESP_LOGW(TAG,
"Timeout writing %zu bytes",
len);
484 const int err = errno;
486 ESP_LOGW(TAG,
"Write err %zu bytes, errno %d",
len, err);
505 ESP_LOGW(TAG,
"Socket %s: errno %d", LOG_STR_ARG(msg), errno);
511 char peername[socket::SOCKADDR_STR_LEN];
512 this->
client_->getpeername_to(peername);
513 ESP_LOGD(TAG,
"Starting %s from %s", LOG_STR_ARG(phase), peername);
517 ESP_LOGW(TAG,
"Remote closed at %s", LOG_STR_ARG(during));
563 this->handshake_buf_pos_ += read;
565 return this->handshake_buf_pos_ >= to_read;
577 this->handshake_buf_pos_ +=
written;
579 return this->handshake_buf_pos_ >= to_write;
590#ifdef USE_OTA_PASSWORD
603#ifdef USE_OTA_PASSWORD
607 bool client_supports_sha256 = (this->
ota_features_ & FEATURE_SUPPORTS_SHA256_AUTH) != 0;
610 if (!client_supports_sha256) {
644 const size_t hex_size = hasher.
get_size() * 2;
645 const size_t nonce_len = hasher.
get_size() / 4;
646 const size_t auth_buf_size = 1 + 3 * hex_size;
647 this->
auth_buf_ = std::make_unique<uint8_t[]>(auth_buf_size);
650 char *buf =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
651 if (!
random_bytes(
reinterpret_cast<uint8_t *
>(buf), nonce_len)) {
658 hasher.
add(buf, nonce_len);
663 ESP_LOGV(TAG,
"Auth: Nonce is %.*s", hex_size, buf);
668 const size_t to_write = 1 + hex_size;
676 this->auth_buf_pos_ +=
written;
679 if (this->auth_buf_pos_ < to_write) {
684 this->auth_buf_pos_ = 0;
690 const size_t to_read = hex_size * 2;
694 size_t cnonce_offset = 1 + hex_size;
702 this->auth_buf_pos_ += read;
705 if (this->auth_buf_pos_ < to_read) {
710 const char *nonce =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
711 const char *cnonce = nonce + hex_size;
712 const char *response = cnonce + hex_size;
719 hasher.
add(this->
password_.c_str(), this->password_.length());
720 hasher.
add(nonce, hex_size * 2);
723 ESP_LOGV(TAG,
"Auth: CNonce is %.*s", hex_size, cnonce);
724#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
727 ESP_LOGV(TAG,
"Auth: Result is %.*s", hex_size, computed_hash);
729 ESP_LOGV(TAG,
"Auth: Response is %.*s", hex_size, response);
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 status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
void status_set_warning()
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_clear_warning()
bool would_block_(int error_code) const
uint8_t handshake_buf_pos_
uint16_t get_port() const
static constexpr size_t SHA256_HEX_SIZE
void yield_and_feed_watchdog_()
bool writeall_(const uint8_t *buf, size_t len)
bool try_read_(size_t to_read, const LogString *desc)
ota::OTABackendPtr backend_
bool try_write_(size_t to_write, const LogString *desc)
void dump_config() override
std::unique_ptr< uint8_t[]> auth_buf_
bool handle_write_error_(ssize_t written, const LogString *desc)
uint8_t handshake_buf_[5]
void log_auth_warning_(const LogString *msg)
uint32_t client_connect_time_
float get_setup_priority() const override
void send_error_and_cleanup_(ota::OTAResponseTypes error)
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)
void server_failed_(const LogString *msg)
void transition_ota_state_(OTAState next_state)
void cleanup_connection_()
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.
bool equals_hex(const char *expected)
Compare the hash against a provided hex-encoded hash.
void notify_state_(OTAState state, float progress, uint8_t error)
SHA256 hash implementation.
void calculate() override
size_t get_size() const override
Get the size of the hash in bytes (32 for SHA256)
void add(const uint8_t *data, size_t len) override
int setblocking(bool blocking)
bool ready() const
Check if the socket has buffered data ready to read.
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)
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.
ESPHOME_ALWAYS_INLINE const char * get_use_address()
Get the active network hostname.
@ OTA_RESPONSE_UPDATE_PREPARE_OK
@ OTA_RESPONSE_SUPPORTS_COMPRESSION
@ OTA_RESPONSE_BIN_MD5_OK
@ OTA_RESPONSE_UPDATE_END_OK
@ OTA_RESPONSE_RECEIVE_OK
@ OTA_RESPONSE_ERROR_AUTH_INVALID
@ OTA_RESPONSE_ERROR_UNKNOWN
@ OTA_RESPONSE_REQUEST_SHA256_AUTH
@ OTA_RESPONSE_ERROR_MAGIC
std::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
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)
Providing packet encoding functions for exchanging data with a remote host.
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
void esphome_wake_ota_component_any_context()
void HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
Application App
Global storage of Application pointer - only one Application can exist.