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