ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ota_http_request.cpp
Go to the documentation of this file.
1#include "ota_http_request.h"
2
3#include <cctype>
4
7#include "esphome/core/log.h"
8
11
12namespace esphome::http_request {
13
14ESPHOME_LOG_TAG(TAG, "http_request.ota");
15
16void OtaHttpRequestComponent::dump_config() { ESP_LOGCONFIG(TAG, "Over-The-Air updates via HTTP request"); };
17
19 if (this->request_ == nullptr)
20 this->request_ = make_unique<Request>();
21 return *this->request_;
22}
23
24void OtaHttpRequestComponent::set_md5_url(const std::string &url) {
25 if (!this->validate_url_(url)) {
26 if (this->request_ != nullptr)
27 this->request_->md5_url.clear(); // URL was not valid; prevent flashing until it is
28 return;
29 }
30 Request &request = this->get_request_();
31 request.md5_url = url;
32 request.md5_expected.clear(); // to be retrieved later
33}
34
35void OtaHttpRequestComponent::set_url(const std::string &url) {
36 if (!this->validate_url_(url)) {
37 if (this->request_ != nullptr)
38 this->request_->url.clear(); // URL was not valid; prevent flashing until it is
39 return;
40 }
41 this->get_request_().url = url;
42}
43
45 if (this->request_ == nullptr || this->request_->url.empty()) {
46 ESP_LOGE(TAG, "URL not set; cannot start update");
47 return;
48 }
49
50 ESP_LOGI(TAG, "Starting update");
51#ifdef USE_OTA_STATE_LISTENER
52 this->notify_state_(ota::OTA_STARTED, 0.0f, 0);
53#endif
54
55 auto ota_status = this->do_ota_();
56
57 switch (ota_status) {
59#ifdef USE_OTA_STATE_LISTENER
60 this->notify_state_(ota::OTA_COMPLETED, 100.0f, ota_status);
61#endif
62 delay(10);
64 break;
65
66 default:
67#ifdef USE_OTA_STATE_LISTENER
68 this->notify_state_(ota::OTA_ERROR, 0.0f, ota_status);
69#endif
70 this->request_->md5_computed.clear(); // will be reset at next attempt
71 this->request_->md5_expected.clear(); // will be reset at next attempt
72 break;
73 }
74}
75
76void OtaHttpRequestComponent::cleanup_(ota::OTABackendPtr backend, const std::shared_ptr<HttpContainer> &container,
77 bool abort_backend) {
78 if (abort_backend) {
79 ESP_LOGV(TAG, "Aborting OTA backend");
80 backend->abort();
81 }
82 ESP_LOGV(TAG, "Aborting HTTP connection");
83 container->end();
84};
85
88 uint32_t last_progress = 0;
89 uint32_t update_start_time = millis();
90 md5::MD5Digest md5_receive;
91 char md5_receive_str[33];
92
93 if (this->request_->md5_expected.empty() && !this->http_get_md5_()) {
94 return OTA_MD5_INVALID;
95 }
96
97 ESP_LOGD(TAG, "MD5 expected: %s", this->request_->md5_expected.c_str());
98
99 auto url_with_auth = this->get_url_with_auth_(this->request_->url);
100 if (url_with_auth.empty()) {
101 return OTA_BAD_URL;
102 }
103 ESP_LOGVV(TAG, "url_with_auth: %s", url_with_auth.c_str());
104 ESP_LOGI(TAG, "Connecting to: %s", this->request_->url.c_str());
105
106 auto container = this->parent_->get(url_with_auth);
107
108 if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
109 if (container != nullptr)
110 container->end();
112 }
113
114 // we will compute MD5 on the fly for verification -- Arduino OTA seems to ignore it
115 md5_receive.init();
116 ESP_LOGV(TAG, "MD5Digest initialized, OTA backend begin");
117 auto backend = ota::make_ota_backend();
118 auto error_code = backend->begin(container->content_length);
119 if (error_code != ota::OTA_RESPONSE_OK) {
120 ESP_LOGW(TAG, "backend->begin error: %d", error_code);
121 // Nothing to abort: begin() failed, so no OTA handle was opened
122 this->cleanup_(std::move(backend), container, /*abort_backend=*/false);
123 return error_code;
124 }
125
126 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
127 // Use http_read_loop_result() helper instead of checking return values directly
128 uint32_t last_data_time = millis();
129 const uint32_t read_timeout = this->parent_->get_timeout();
130
131 while (container->get_bytes_read() < container->content_length) {
132 // read a maximum of chunk_size bytes into buf. (real read size returned, or negative error code)
133 int bufsize_or_error = container->read(buf, OtaHttpRequestComponent::HTTP_RECV_BUFFER);
134 ESP_LOGVV(TAG, "bytes_read_ = %u, body_length_ = %u, bufsize_or_error = %i", container->get_bytes_read(),
135 container->content_length, bufsize_or_error);
136
137 // feed watchdog and give other tasks a chance to run
138 App.feed_wdt();
139 yield();
140
141 auto result = http_read_loop_result(bufsize_or_error, last_data_time, read_timeout, container->is_read_complete());
142 if (result == HttpReadLoopResult::RETRY)
143 continue;
144 // For non-chunked responses, COMPLETE is unreachable (loop condition checks bytes_read < content_length).
145 // For chunked responses, the decoder sets content_length = bytes_read when the final chunk arrives,
146 // which causes the loop condition to terminate. But COMPLETE can still be returned if the decoder
147 // finishes mid-read, so this is needed for correctness.
148 if (result == HttpReadLoopResult::COMPLETE)
149 break;
150 if (result != HttpReadLoopResult::DATA) {
151 if (result == HttpReadLoopResult::TIMEOUT) {
152 ESP_LOGE(TAG, "Timeout reading data");
153 } else {
154 ESP_LOGE(TAG, "Error reading data: %d", bufsize_or_error);
155 }
156 this->cleanup_(std::move(backend), container, /*abort_backend=*/true);
158 }
159
160 // At this point bufsize_or_error > 0, so it's a valid size
161 if (bufsize_or_error <= OtaHttpRequestComponent::HTTP_RECV_BUFFER) {
162 // add read bytes to MD5
163 md5_receive.add(buf, bufsize_or_error);
164
165 // write bytes to OTA backend
166 error_code = backend->write(buf, bufsize_or_error);
167 if (error_code != ota::OTA_RESPONSE_OK) {
168 // error code explanation available at
169 // https://github.com/esphome/esphome/blob/dev/esphome/components/ota/ota_backend.h
170 ESP_LOGE(TAG, "Error code (%02X) writing binary data to flash at offset %d and size %d", error_code,
171 container->get_bytes_read() - bufsize_or_error, container->content_length);
172 this->cleanup_(std::move(backend), container, /*abort_backend=*/true);
173 return error_code;
174 }
175 }
176
177 uint32_t now = millis();
178 if ((now - last_progress > 1000) or (container->get_bytes_read() == container->content_length)) {
179 last_progress = now;
180 float percentage = container->get_bytes_read() * 100.0f / container->content_length;
181 ESP_LOGD(TAG, "Progress: %0.1f%%", percentage);
182#ifdef USE_OTA_STATE_LISTENER
183 this->notify_state_(ota::OTA_IN_PROGRESS, percentage, 0);
184#endif
185 }
186 } // while
187
188 ESP_LOGI(TAG, "Done in %.0f seconds", float(millis() - update_start_time) / 1000);
189
190 // verify MD5 is as expected and act accordingly
191 md5_receive.calculate();
192 md5_receive.get_hex(md5_receive_str);
193 this->request_->md5_computed = md5_receive_str;
194 if (strncmp(this->request_->md5_computed.c_str(), this->request_->md5_expected.c_str(), MD5_SIZE) != 0) {
195 ESP_LOGE(TAG, "MD5 computed: %s - Aborting due to MD5 mismatch", this->request_->md5_computed.c_str());
196 this->cleanup_(std::move(backend), container, /*abort_backend=*/true);
198 } else {
199 backend->set_update_md5(md5_receive_str);
200 }
201
202 container->end();
203
204 // feed watchdog and give other tasks a chance to run
205 App.feed_wdt();
206 yield();
207 delay(100); // NOLINT
208
209 error_code = backend->end();
210 if (error_code != ota::OTA_RESPONSE_OK) {
211 ESP_LOGW(TAG, "Error ending update! error_code: %d", error_code);
212 this->cleanup_(std::move(backend), container, /*abort_backend=*/true);
213 return error_code;
214 }
215
216 ESP_LOGI(TAG, "Update complete");
218}
219
220// URL-encode characters that are not unreserved per RFC 3986 section 2.3.
221// This is needed for embedding userinfo (username/password) in URLs safely.
222static std::string url_encode(const std::string &str) {
223 std::string result;
224 result.reserve(str.size());
225 for (char c : str) {
226 if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.' || c == '~') {
227 result += c;
228 } else {
229 result += '%';
230 result += format_hex_pretty_char((static_cast<uint8_t>(c) >> 4) & 0x0F);
231 result += format_hex_pretty_char(static_cast<uint8_t>(c) & 0x0F);
232 }
233 }
234 return result;
235}
236
237void OtaHttpRequestComponent::set_password(const std::string &password) {
238 this->get_request_().password = url_encode(password);
239}
240void OtaHttpRequestComponent::set_username(const std::string &username) {
241 this->get_request_().username = url_encode(username);
242}
243
244std::string OtaHttpRequestComponent::get_url_with_auth_(const std::string &url) {
245 if (this->request_->username.empty() || this->request_->password.empty()) {
246 return url;
247 }
248
249 auto start_char = url.find("://");
250 if ((start_char == std::string::npos) || (start_char < 4)) {
251 ESP_LOGE(TAG, "Incorrect URL prefix");
252 return {};
253 }
254
255 ESP_LOGD(TAG, "Using basic HTTP authentication");
256
257 start_char += 3; // skip '://' characters
258 auto url_with_auth = url.substr(0, start_char) + this->request_->username + ":" + this->request_->password + "@" +
259 url.substr(start_char);
260 return url_with_auth;
261}
262
264 if (this->request_->md5_url.empty()) {
265 return false;
266 }
267
268 auto url_with_auth = this->get_url_with_auth_(this->request_->md5_url);
269 if (url_with_auth.empty()) {
270 return false;
271 }
272
273 ESP_LOGVV(TAG, "url_with_auth: %s", url_with_auth.c_str());
274 ESP_LOGI(TAG, "Connecting to: %s", this->request_->md5_url.c_str());
275 auto container = this->parent_->get(url_with_auth);
276 if (container == nullptr) {
277 ESP_LOGE(TAG, "Failed to connect to MD5 URL");
278 return false;
279 }
280 size_t length = container->content_length;
281 if (length == 0) {
282 container->end();
283 return false;
284 }
285 if (length < MD5_SIZE) {
286 ESP_LOGE(TAG, "MD5 file must be %u bytes; %u bytes reported by HTTP server. Aborting", MD5_SIZE, length);
287 container->end();
288 return false;
289 }
290
291 this->request_->md5_expected.resize(MD5_SIZE);
292 auto result = http_read_fully(container.get(), (uint8_t *) this->request_->md5_expected.data(), MD5_SIZE, MD5_SIZE,
293 this->parent_->get_timeout());
294 container->end();
295
296 if (result.status != HttpReadStatus::OK) {
297 if (result.status == HttpReadStatus::TIMEOUT) {
298 ESP_LOGE(TAG, "Timeout reading MD5");
299 } else {
300 ESP_LOGE(TAG, "Error reading MD5: %d", result.error_code);
301 }
302 return false;
303 }
304 return true;
305}
306
307bool OtaHttpRequestComponent::validate_url_(const std::string &url) {
308 if ((url.length() < 8) || !url.starts_with("http") || (url.find("://") == std::string::npos)) {
309 ESP_LOGE(TAG, "URL is invalid and/or must be prefixed with 'http://' or 'https://'");
310 return false;
311 }
312 return true;
313}
314
315} // namespace esphome::http_request
void feed_wdt()
Feed the task watchdog.
void get_hex(char *output)
Retrieve the hash as hex characters. Output buffer must hold get_size() * 2 + 1 bytes.
Definition hash_base.h:29
void cleanup_(ota::OTABackendPtr backend, const std::shared_ptr< HttpContainer > &container, bool abort_backend)
void set_password(const std::string &password)
void set_username(const std::string &username)
std::string get_url_with_auth_(const std::string &url)
void set_md5_url(const std::string &md5_url)
void calculate() override
Compute the digest, based on the provided data.
Definition md5.cpp:16
void add(const uint8_t *data, size_t len) override
Add bytes of data for the digest.
Definition md5.cpp:14
void init() override
Initialize a new MD5 digest computation.
Definition md5.cpp:9
void notify_state_(OTAState state, float progress, uint8_t error)
void yield(void)
@ TIMEOUT
Timeout waiting for data, caller should exit loop.
@ COMPLETE
All content has been read, caller should exit loop.
@ RETRY
No data yet, already delayed, caller should continue loop.
@ DATA
Data was read, process it.
HttpReadLoopResult http_read_loop_result(int bytes_read_or_error, uint32_t &last_data_time, uint32_t timeout_ms, bool is_read_complete)
Process a read result with timeout tracking and delay handling.
ESPHOME_LOG_TAG(TAG, "http_request")
HttpReadResult http_read_fully(HttpContainer *container, uint8_t *buffer, size_t total_size, size_t chunk_size, uint32_t timeout_ms)
Read data from HTTP container into buffer with timeout handling Handles feed_wdt, yield,...
@ TIMEOUT
Timeout waiting for data.
@ OK
Read completed successfully.
decltype(make_ota_backend()) OTABackendPtr
@ OTA_RESPONSE_ERROR_MD5_MISMATCH
Definition ota_backend.h:44
std::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1540
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
Allocated by the first setter, which only runs before a flash, and never freed, so a flash never lose...