2#ifdef USE_OTA_ENCRYPTION_FROM_API
21#ifdef USE_LWIP_FAST_SELECT
31static const char *
const TAG =
"esphome.ota";
33#ifdef USE_OTA_ENCRYPTION
35#ifdef USE_OTA_ENCRYPTION_FROM_API
42static constexpr uint16_t OTA_BLOCK_SIZE = 8192;
43static constexpr uint32_t OTA_SOCKET_TIMEOUT_HANDSHAKE = 20000;
47static constexpr uint32_t OTA_SOCKET_TIMEOUT_DATA = 105000;
55 if (global_esphome_ota_component !=
nullptr) {
67 int err = this->
server_->
setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
99 global_esphome_ota_component =
this;
100#ifdef USE_LWIP_FAST_SELECT
106#ifdef USE_OTA_PARTITIONS
112 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
114 "Over-The-Air updates:\n"
117#ifdef USE_OTA_ENCRYPTION
122#ifdef USE_OTA_ENCRYPTION_REQUIRED
124 LOG_STR_LITERAL(
"required")
125#elif defined(USE_OTA_ENCRYPTION_PROVISIONED)
128 this->
noise_context_().has_psk() ? LOG_STR_LITERAL(
"offered, plaintext accepted")
129 : LOG_STR_LITERAL(
"offered once the api key is provisioned")
130#elif defined(USE_OTA_ENCRYPTION)
132 LOG_STR_LITERAL(
"offered, plaintext accepted")
135#ifdef USE_OTA_PASSWORD
137 ESP_LOGCONFIG(TAG,
" Password configured");
140#ifdef USE_OTA_PARTITIONS
142 " Partition access allowed\n"
144 " Partition address: 0x%" PRIX32
"\n"
145 " Used size: %zu bytes (0x%zX)",
150 " Partition table:\n"
151 " %-12s %-4s %-8s %-10s %-10s",
152 "Name",
"Type",
"Subtype",
"Address",
"Size");
153 esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY,
nullptr);
154 while (it !=
nullptr) {
155 const esp_partition_t *partition = esp_partition_get(it);
156 ESP_LOGCONFIG(TAG,
" %-12s 0x%-2X 0x%-6X 0x%-8" PRIX32
" 0x%-8" PRIX32, partition->label, partition->type,
157 partition->subtype, partition->address, partition->size);
158 it = esp_partition_next(it);
160 esp_partition_iterator_release(it);
161 esp_bootloader_desc_t bootloader_desc;
162 esp_err_t err = esp_ota_get_bootloader_description(
nullptr, &bootloader_desc);
163 ESP_LOGCONFIG(TAG,
" Bootloader: ESP-IDF %s",
164 (err == ESP_OK) ? bootloader_desc.idf_ver : LOG_STR_LITERAL(
"version unknown"));
181static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_COMPRESSION = 0x01;
182static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_SHA256_AUTH = 0x02;
183static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL = 0x04;
184static constexpr uint8_t CLIENT_FEATURE_SUPPORTS_NOISE = 0x08;
186static constexpr uint8_t CLIENT_NOISE_FEATURES =
187 CLIENT_FEATURE_SUPPORTS_NOISE | CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL;
188static constexpr uint8_t SERVER_FEATURE_SUPPORTS_COMPRESSION = 0x01;
189static constexpr uint8_t SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS = 0x02;
190static constexpr uint8_t SERVER_FEATURE_SUPPORTS_NOISE = 0x04;
193#ifdef USE_OTA_ENCRYPTION_REQUIRED
197 return (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_EXTENDED_PROTOCOL) != 0;
208 if (this->
client_ ==
nullptr) {
217 int err = this->
client_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &enable,
sizeof(
int));
223 err = this->
client_->setblocking(
false);
238 ESP_LOGW(TAG,
"Handshake timeout");
246 if (!this->
try_read_(5, LOG_STR(
"read magic"))) {
252 ESP_LOGW(TAG,
"Magic bytes mismatch! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", this->
handshake_buf_[0],
267 if (!this->
try_write_(2, LOG_STR(
"ack magic"))) {
278 if (!this->
try_read_(1, LOG_STR(
"read feature"))) {
284#ifdef USE_OTA_ENCRYPTION_REQUIRED
286 if ((this->
ota_features_ & CLIENT_NOISE_FEATURES) != CLIENT_NOISE_FEATURES) {
287 ESP_LOGW(TAG,
"Client does not support encryption");
295 const bool supports_compression =
296 (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_COMPRESSION) != 0 && this->
backend_->supports_compression();
302 static_assert(
HANDSHAKE_BUF_SIZE >= 2,
"handshake_buf_ must hold the 2-byte extended-protocol feature ack");
304 this->
handshake_buf_[1] = (supports_compression ? SERVER_FEATURE_SUPPORTS_COMPRESSION : 0);
305#ifdef USE_OTA_PARTITIONS
306 this->
handshake_buf_[1] |= SERVER_FEATURE_SUPPORTS_PARTITION_ACCESS;
308#ifdef USE_OTA_ENCRYPTION_PROVISIONED
313#elif defined(USE_OTA_ENCRYPTION)
325 static constexpr size_t STANDARD_PROTO_ACK_SIZE = 1;
326 static constexpr size_t EXTENDED_PROTO_ACK_SIZE = 2;
327 const size_t ack_size = this->
extended_proto_() ? EXTENDED_PROTO_ACK_SIZE : STANDARD_PROTO_ACK_SIZE;
328 if (!this->
try_write_(ack_size, LOG_STR(
"ack feature"))) {
331#ifdef USE_OTA_ENCRYPTION
334 if ((this->
handshake_buf_[1] & SERVER_FEATURE_SUPPORTS_NOISE) != 0 &&
335 (this->
ota_features_ & CLIENT_NOISE_FEATURES) == CLIENT_NOISE_FEATURES) {
345#ifdef USE_OTA_PASSWORD
358#ifdef USE_OTA_PASSWORD
382#ifdef USE_OTA_ENCRYPTION
437 char *sbuf =
reinterpret_cast<char *
>(buf);
440#if USE_OTA_VERSION == 2
441 size_t size_acknowledged = 0;
448 this->
client_->setsockopt(SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
449 this->
client_->setsockopt(SOL_SOCKET, SO_SNDTIMEO, &tv,
sizeof(tv));
450 this->
client_->setblocking(
true);
463 ESP_LOGV(TAG,
"OTA type is 0x%02x", ota_type);
470 ota_size = (
static_cast<size_t>(buf[0]) << 24) | (
static_cast<size_t>(buf[1]) << 16) |
471 (
static_cast<size_t>(buf[2]) << 8) | buf[3];
472 ESP_LOGV(TAG,
"Size is %zu bytes", ota_size);
474#ifndef USE_OTA_PARTITIONS
487#ifdef USE_OTA_STATE_LISTENER
492 error_code = this->
backend_->begin(ota_size, ota_type);
506 ESP_LOGV(TAG,
"Update: Binary MD5 is %s", sbuf);
507 this->
backend_->set_update_md5(sbuf);
518 while (total < ota_size) {
519 if (
millis() - last_data_ms > OTA_SOCKET_TIMEOUT_DATA) {
520 ESP_LOGW(TAG,
"No data received for %u ms", (
unsigned) OTA_SOCKET_TIMEOUT_DATA);
524 size_t remaining = ota_size - total;
527#ifdef USE_OTA_ENCRYPTION
528 if (this->
noise_ !=
nullptr) {
539 read = this->
client_->read(buf, requested);
541 const int err = errno;
547 ESP_LOGW(TAG,
"Read err %d", err);
550 }
else if (read == 0) {
551 ESP_LOGW(TAG,
"Remote closed");
558 error_code = this->
backend_->write(buf, read);
560 ESP_LOGW(TAG,
"Flash write err %d", error_code);
564#if USE_OTA_VERSION == 2
565 while (size_acknowledged + OTA_BLOCK_SIZE <= total || (total == ota_size && size_acknowledged < ota_size)) {
567 size_acknowledged += OTA_BLOCK_SIZE;
572 if (now - last_progress > 1000) {
574 float percentage = (total * 100.0f) / ota_size;
575 ESP_LOGD(TAG,
"Progress: %0.1f%%", percentage);
576#ifdef USE_OTA_STATE_LISTENER
589 ESP_LOGW(TAG,
"End update err %d", error_code);
604 ESP_LOGI(TAG,
"Update complete");
606#ifdef USE_OTA_STATE_LISTENER
610#ifdef USE_OTA_PARTITIONS
634#ifdef USE_OTA_STATE_LISTENER
642 while (
len - at > 0) {
644 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
645 ESP_LOGW(TAG,
"Timeout reading %zu bytes",
len);
651 const int err = errno;
653 ESP_LOGW(TAG,
"Read err %zu bytes, errno %d",
len, err);
656 }
else if (read == 0) {
657 ESP_LOGW(TAG,
"Remote closed");
672 while (
len - at > 0) {
674 if (now - start > OTA_SOCKET_TIMEOUT_DATA) {
675 ESP_LOGW(TAG,
"Timeout writing %zu bytes",
len);
681 const int err = errno;
683 ESP_LOGW(TAG,
"Write err %zu bytes, errno %d",
len, err);
700 ESP_LOGW(TAG,
"Socket %s: errno %d", LOG_STR_ARG(msg), errno);
706 char peername[socket::SOCKADDR_STR_LEN];
707 this->
client_->getpeername_to(peername);
708 ESP_LOGD(TAG,
"Starting %s from %s", LOG_STR_ARG(phase), peername);
712 ESP_LOGW(TAG,
"Remote closed at %s", LOG_STR_ARG(during));
758 this->handshake_buf_pos_ += read;
760 return this->handshake_buf_pos_ >= to_read;
772 this->handshake_buf_pos_ +=
written;
774 return this->handshake_buf_pos_ >= to_write;
785#ifdef USE_OTA_PASSWORD
788#ifdef USE_OTA_ENCRYPTION
801#ifdef USE_OTA_PASSWORD
805 bool client_supports_sha256 = (this->
ota_features_ & CLIENT_FEATURE_SUPPORTS_SHA256_AUTH) != 0;
808 if (!client_supports_sha256) {
842 const size_t hex_size = hasher.
get_size() * 2;
843 const size_t nonce_len = hasher.
get_size() / 4;
844 const size_t auth_buf_size = 1 + 3 * hex_size;
845 this->
auth_buf_ = std::make_unique<uint8_t[]>(auth_buf_size);
848 char *buf =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
849 if (!
random_bytes(
reinterpret_cast<uint8_t *
>(buf), nonce_len)) {
856 hasher.
add(buf, nonce_len);
861 ESP_LOGV(TAG,
"Auth: Nonce is %.*s", (
int) hex_size, buf);
866 const size_t to_write = 1 + hex_size;
874 this->auth_buf_pos_ +=
written;
877 if (this->auth_buf_pos_ < to_write) {
882 this->auth_buf_pos_ = 0;
888 const size_t to_read = hex_size * 2;
892 size_t cnonce_offset = 1 + hex_size;
900 this->auth_buf_pos_ += read;
903 if (this->auth_buf_pos_ < to_read) {
908 const char *nonce =
reinterpret_cast<char *
>(this->
auth_buf_.get() + 1);
909 const char *cnonce = nonce + hex_size;
910 const char *response = cnonce + hex_size;
917 hasher.
add(this->
password_.c_str(), this->password_.length());
918 hasher.
add(nonce, hex_size * 2);
921 ESP_LOGV(TAG,
"Auth: CNonce is %.*s", (
int) hex_size, cnonce);
922#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
925 ESP_LOGV(TAG,
"Auth: Result is %.*s", (
int) hex_size, computed_hash);
927 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
std::unique_ptr< uint8_t[]> auth_buf_
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)
std::unique_ptr< NoiseSession > noise_
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.
noise::NoiseContext & get_noise_ctx()
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
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
@ 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.