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