2#ifdef USE_OTA_ENCRYPTION_PROVISIONED
21#ifdef USE_LWIP_FAST_SELECT
31static const char *
const TAG =
"esphome.ota";
33#ifdef USE_OTA_ENCRYPTION
35#ifdef USE_OTA_ENCRYPTION_PROVISIONED
44static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
45static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 20000;
49static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 105000;
57 if (global_esphome_ota_component !=
nullptr) {
63#ifdef USE_OTA_ENCRYPTION_PROVISIONED
79 int err = this->
server_->
setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
111 global_esphome_ota_component =
this;
112#ifdef USE_LWIP_FAST_SELECT
118#ifdef USE_OTA_PARTITIONS
124 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
126 "Over-The-Air updates:\n"
129#ifdef USE_OTA_ENCRYPTION
134#ifdef USE_OTA_ENCRYPTION_REQUIRED
136 LOG_STR_LITERAL(
"required")
137#elif defined(USE_OTA_ENCRYPTION_PROVISIONED)
140 this->
noise_context_().has_psk() ? LOG_STR_LITERAL(
"offered, plaintext accepted")
141 : LOG_STR_LITERAL(
"offered once the api key is provisioned")
142#elif defined(USE_OTA_ENCRYPTION)
144 LOG_STR_LITERAL(
"offered, plaintext accepted")
147#ifdef USE_OTA_PASSWORD
149 ESP_LOGCONFIG(TAG,
" Password configured");
152#ifdef USE_OTA_PARTITIONS
154 " Partition access allowed\n"
156 " Partition address: 0x%" PRIX32
"\n"
157 " Used size: %zu bytes (0x%zX)",
162 " Partition table:\n"
163 " %-12s %-4s %-8s %-10s %-10s",
164 "Name",
"Type",
"Subtype",
"Address",
"Size");
165 esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY,
nullptr);
166 while (it !=
nullptr) {
167 const esp_partition_t *partition = esp_partition_get(it);
168 ESP_LOGCONFIG(TAG,
" %-12s 0x%-2X 0x%-6X 0x%-8" PRIX32
" 0x%-8" PRIX32, partition->label, partition->type,
169 partition->subtype, partition->address, partition->size);
170 it = esp_partition_next(it);
172 esp_partition_iterator_release(it);
173 esp_bootloader_desc_t bootloader_desc;
174 esp_err_t err = esp_ota_get_bootloader_description(
nullptr, &bootloader_desc);
175 ESP_LOGCONFIG(TAG,
" Bootloader: ESP-IDF %s",
176 (err == ESP_OK) ? bootloader_desc.idf_ver : LOG_STR_LITERAL(
"version unknown"));
193static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_COMPRESSION = 0x01;
194static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_SHA256_AUTH = 0x02;
195static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL = 0x04;
196static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_NOISE = 0x08;
198static constexpr uint8_t CLIENT_NOISE_FEATURES =
199 CLIENT_FEATURE_SUPPORTS_NOISE | CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL;
200static constexpr uint8_t SERVER_FEATURE_SUPPORTS_COMPRESSION = 0x01;
201static constexpr uint8_t SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS = 0x02;
202static constexpr uint8_t SERVER_FEATURE_SUPPORTS_NOISE = 0x04;
205#ifdef USE_OTA_ENCRYPTION_REQUIRED
209 return (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL) != 0;
220 if (this->
client_ ==
nullptr) {
229 int err = this->
client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable,
sizeof(
int));
235 err = this->
client_->setblocking(
false);
250 ESP_LOGW(TAG,
"Handshake timeout");
258 if (!this->
try_read_(5, LOG_STR(
"read magic"))) {
264 ESP_LOGW(TAG,
"Magic bytes mismatch! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", this->
handshake_buf_[0],
279 if (!this->
try_write_(2, LOG_STR(
"ack magic"))) {
290 if (!this->
try_read_(1, LOG_STR(
"read feature"))) {
296#ifdef USE_OTA_ENCRYPTION_REQUIRED
298 if ((this->
ota_features_ & CLIENT_NOISE_FEATURES) != CLIENT_NOISE_FEATURES) {
299 ESP_LOGW(TAG,
"Client does not support encryption");
307 const bool supports_compression =
308 (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_COMPRESSION) != 0 && this->
backend_->supports_compression();
314 static_assert(
HANDSHAKE_BUF_SIZE >= 2,
"handshake_buf_ must hold the 2-byte extended-protocol feature ack");
316 this->
handshake_buf_[1] = (supports_compression ? SERVER_FEATURE_SUPPORTS_COMPRESSION : 0);
317#ifdef USE_OTA_PARTITIONS
318 this->
handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS;
320#ifdef USE_OTA_ENCRYPTION_PROVISIONED
325#elif defined(USE_OTA_ENCRYPTION)
337 static constexpr size_t STANDARD_PROTO_ACK_SIZE = 1;
338 static constexpr size_t EXTENDED_PROTO_ACK_SIZE = 2;
339 const size_t ack_size = this->
extended_proto_() ? EXTENDED_PROTO_ACK_SIZE : STANDARD_PROTO_ACK_SIZE;
340 if (!this->
try_write_(ack_size, LOG_STR(
"ack feature"))) {
343#ifdef USE_OTA_ENCRYPTION
346 if ((this->
handshake_buf_[1] & SERVER_FEATURE_SUPPORTS_NOISE) != 0 &&
347 (this->
ota_features_ & CLIENT_NOISE_FEATURES) == CLIENT_NOISE_FEATURES) {
357#ifdef USE_OTA_PASSWORD
370#ifdef USE_OTA_PASSWORD
394#ifdef USE_OTA_ENCRYPTION
449 char *sbuf =
reinterpret_cast<char *
>(buf);
452#if USE_OTA_VERSION == 2
453 size_t size_acknowledged = 0;
460 this->
client_->setsockopt(SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
461 this->
client_->setsockopt(SOL_SOCKET, SO_SNDTIMEO, &tv,
sizeof(tv));
462 this->
client_->setblocking(
true);
475 ESP_LOGV(TAG,
"OTA type is 0x%02x", ota_type);
482 ota_size = (
static_cast<size_t>(buf[0]) << 24) | (
static_cast<size_t>(buf[1]) << 16) |
483 (
static_cast<size_t>(buf[2]) << 8) | buf[3];
484 ESP_LOGV(TAG,
"Size is %zu bytes", ota_size);
486#ifndef USE_OTA_PARTITIONS
499#ifdef USE_OTA_STATE_LISTENER
504 error_code = this->
backend_->begin(ota_size, ota_type);
518 ESP_LOGV(TAG,
"Update: Binary MD5 is %s", sbuf);
519 this->
backend_->set_update_md5(sbuf);
530 while (total < ota_size) {
531 if (
millis() - last_data_ms > OTA_SOCKET_TIMEOUT_DATA) {
532 ESP_LOGW(TAG,
"No data received for %u ms", (
unsigned) OTA_SOCKET_TIMEOUT_DATA);
536 size_t remaining = ota_size - total;
539#ifdef USE_OTA_ENCRYPTION
540 if (this->
noise_ !=
nullptr) {
551 read = this->
client_->read(buf, requested);
553 const int err = errno;
559 ESP_LOGW(TAG,
"Read err %d", err);
562 }
else if (read == 0) {
563 ESP_LOGW(TAG,
"Remote closed");
570 error_code = this->
backend_->write(buf, read);
572 ESP_LOGW(TAG,
"Flash write err %d", error_code);
576#if USE_OTA_VERSION == 2
577 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) {
579 size_acknowledged += OTA_BLOCK_SIZE;
584 if (now - last_progress > 1000) {
586 float percentage = (total * 100.0f) / ota_size;
587 ESP_LOGD(TAG,
"Progress: %0.1f%%", percentage);
588#ifdef USE_OTA_STATE_LISTENER
601 ESP_LOGW(TAG,
"End update err %d", error_code);
616 ESP_LOGI(TAG,
"Update complete");
618#ifdef USE_OTA_STATE_LISTENER
622#ifdef USE_OTA_PARTITIONS
646#ifdef USE_OTA_STATE_LISTENER
654 while (
len - at > 0) {
656 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
657 ESP_LOGW(TAG,
"Timeout reading %zu bytes",
len);
663 const int err = errno;
665 ESP_LOGW(TAG,
"Read err %zu bytes, errno %d",
len, err);
668 }
else if (read == 0) {
669 ESP_LOGW(TAG,
"Remote closed");
684 while (
len - at > 0) {
686 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
687 ESP_LOGW(TAG,
"Timeout writing %zu bytes",
len);
693 const int err = errno;
695 ESP_LOGW(TAG,
"Write err %zu bytes, errno %d",
len, err);
712 ESP_LOGW(TAG,
"Socket %s: errno %d", LOG_STR_ARG(msg), errno);
718 char peername[socket::SOCKADDR_STR_LEN];
719 this->
client_->getpeername_to(peername);
720 ESP_LOGD(TAG,
"Starting %s from %s", LOG_STR_ARG(phase), peername);
724 ESP_LOGW(TAG,
"Remote closed at %s", LOG_STR_ARG(during));
770 this->handshake_buf_pos_ += read;
772 return this->handshake_buf_pos_ >= to_read;
784 this->handshake_buf_pos_ +=
written;
786 return this->handshake_buf_pos_ >= to_write;
797#ifdef USE_OTA_PASSWORD
800#ifdef USE_OTA_ENCRYPTION
813#ifdef USE_OTA_PASSWORD
817 bool client_supports_sha256 = (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_SHA256_AUTH) != 0;
820 if (!client_supports_sha256) {
854 const size_t hex_size = hasher.
get_size() * 2;
855 const size_t nonce_len = hasher.
get_size() / 4;
856 const size_t auth_buf_size = 1 + 3 * hex_size;
867 char *buf =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
868 if (!
random_bytes(
reinterpret_cast<uint8_t *
>(buf), nonce_len)) {
875 hasher.
add(buf, nonce_len);
880 ESP_LOGV(TAG,
"Auth: Nonce is %.*s", (
int) hex_size, buf);
885 const size_t to_write = 1 + hex_size;
893 this->auth_buf_pos_ +=
written;
896 if (this->auth_buf_pos_ < to_write) {
901 this->auth_buf_pos_ = 0;
907 const size_t to_read = hex_size * 2;
911 size_t cnonce_offset = 1 + hex_size;
919 this->auth_buf_pos_ += read;
922 if (this->auth_buf_pos_ < to_read) {
927 const char *nonce =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
928 const char *cnonce = nonce + hex_size;
929 const char *response = cnonce + hex_size;
936 hasher.
add(this->
password_.c_str(), this->password_.length());
937 hasher.
add(nonce, hex_size * 2);
940 ESP_LOGV(TAG,
"Auth: CNonce is %.*s", (
int) hex_size, cnonce);
941#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
944 ESP_LOGV(TAG,
"Auth: Result is %.*s", (
int) hex_size, computed_hash);
946 ESP_LOGV(TAG,
"Auth: Response is %.*s", (
int) 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()
ESPHomeOTAComponent provides a simple way to integrate Over-the-Air updates into your app using Ardui...
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.
bool would_block_(int error_code) const
uint32_t running_app_offset_
uint8_t handshake_buf_pos_
static constexpr size_t SHA256_HEX_SIZE
static constexpr uint8_t MAGIC_BYTES[5]
void yield_and_feed_watchdog_()
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_
bool noise_start_session_(uint8_t server_feature_flags)
Allocate the session and start the responder handshake.
ota::OTABackendPtr backend_
bool try_write_(size_t to_write, const LogString *desc)
void dump_config() override
RAMUniquePtr< NoiseSession > noise_
bool extended_proto_() const
bool handle_write_error_(ssize_t written, const LogString *desc)
bool data_write_byte_(uint8_t byte)
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)
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)
RAMUniquePtr< uint8_t[]> auth_buf_
RAMUniquePtr< noise::psk_t > saved_psk_
uint8_t handshake_buf_[HANDSHAKE_BUF_SIZE]
static constexpr size_t HANDSHAKE_BUF_SIZE
const noise::NoiseContext & noise_context_() const
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.
An STL allocator that uses SPI or internal RAM.
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
noise::NoiseContext & get_noise_ctx()
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.
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.
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...
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
std::array< uint8_t, 32 > psk_t
@ OTA_TYPE_UPDATE_PARTITION_TABLE
void get_running_app_position(uint32_t &offset, size_t &size)
@ OTA_RESPONSE_UPDATE_PREPARE_OK
@ OTA_RESPONSE_ERROR_ENCRYPTION_REQUIRED
@ OTA_RESPONSE_SUPPORTS_COMPRESSION
@ OTA_RESPONSE_BIN_MD5_OK
@ OTA_RESPONSE_UPDATE_END_OK
@ OTA_RESPONSE_RECEIVE_OK
@ OTA_RESPONSE_FEATURE_FLAGS
@ OTA_RESPONSE_ERROR_UNSUPPORTED_OTA_TYPE
@ 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)
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.