blob: 08c8a6724f376ecc2a71fa5ffb66822131cc4649 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2009 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
rspangler@google.com49fdf182009-10-10 00:57:34 +000016
Alex Deymo14c0da82016-07-20 16:45:45 -070017#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070018
Xiaochu Liub5ba7972019-07-11 09:51:06 -070019#include <netinet/in.h>
20#include <resolv.h>
Alex Deymo63cfcf42017-02-23 15:29:47 -080021#include <sys/types.h>
22#include <unistd.h>
23
adlr@google.comc98a7ed2009-12-04 18:54:03 +000024#include <algorithm>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070025#include <string>
26
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070027#include <base/bind.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070028#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070029#include <base/location.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070030#include <base/logging.h>
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070031#include <base/strings/string_split.h>
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -070032#include <android-base/stringprintf.h>
Tianjie934b8472020-06-24 23:10:49 -070033#include <base/threading/thread_task_runner_handle.h>
34
Alex Deymo63cfcf42017-02-23 15:29:47 -080035#ifdef __ANDROID__
36#include <cutils/qtaguid.h>
Alex Deymoeb256552017-03-21 22:52:54 -070037#include <private/android_filesystem_config.h>
Alex Deymo63cfcf42017-02-23 15:29:47 -080038#endif // __ANDROID__
39
Alex Deymo14c0da82016-07-20 16:45:45 -070040#include "update_engine/certificate_checker.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/hardware_interface.h"
42#include "update_engine/common/platform_constants.h"
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -070043#include "update_engine/common/utils.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000044
Alex Deymo60ca1a72015-06-18 18:19:15 -070045using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070046using brillo::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070047using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070048using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000049
50// This is a concrete implementation of HttpFetcher that uses libcurl to do the
51// http work.
52
53namespace chromeos_update_engine {
54
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070055namespace {
Alex Deymo63cfcf42017-02-23 15:29:47 -080056
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080057const int kNoNetworkRetrySeconds = 10;
Alex Deymo63cfcf42017-02-23 15:29:47 -080058
Alex Deymo63cfcf42017-02-23 15:29:47 -080059// libcurl's CURLOPT_SOCKOPTFUNCTION callback function. Called after the socket
60// is created but before it is connected. This callback tags the created socket
61// so the network usage can be tracked in Android.
62int LibcurlSockoptCallback(void* /* clientp */,
63 curl_socket_t curlfd,
64 curlsocktype /* purpose */) {
65#ifdef __ANDROID__
Alex Deymo558fe6a2017-05-19 13:16:20 -070066 // Socket tag used by all network sockets. See qtaguid kernel module for
67 // stats.
68 const int kUpdateEngineSocketTag = 0x55417243; // "CrAU" in little-endian.
Alex Deymoeb256552017-03-21 22:52:54 -070069 qtaguid_tagSocket(curlfd, kUpdateEngineSocketTag, AID_OTA_UPDATE);
Alex Deymo63cfcf42017-02-23 15:29:47 -080070#endif // __ANDROID__
71 return CURL_SOCKOPT_OK;
72}
73
Alex Vakulenkod2779df2014-06-16 13:19:00 -070074} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070075
Alex Deymo13e95182017-03-16 19:06:13 -070076// static
77int LibcurlHttpFetcher::LibcurlCloseSocketCallback(void* clientp,
78 curl_socket_t item) {
79#ifdef __ANDROID__
80 qtaguid_untagSocket(item);
81#endif // __ANDROID__
Tianjie55abd3c2020-06-19 00:22:59 -070082
Alex Deymo13e95182017-03-16 19:06:13 -070083 LibcurlHttpFetcher* fetcher = static_cast<LibcurlHttpFetcher*>(clientp);
84 // Stop watching the socket before closing it.
Kokoa Matsuda91aa2172024-10-16 16:01:04 +090085 for (size_t t = 0; t < std::size(fetcher->fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +090086 fetcher->fd_controller_maps_[t].erase(item);
Alex Deymo13e95182017-03-16 19:06:13 -070087 }
88
89 // Documentation for this callback says to return 0 on success or 1 on error.
90 if (!IGNORE_EINTR(close(item)))
91 return 0;
92 return 1;
93}
94
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -070095LibcurlHttpFetcher::LibcurlHttpFetcher(HardwareInterface* hardware)
96 : hardware_(hardware) {
Alex Deymoc1c17b42015-11-23 03:53:15 -030097 // Dev users want a longer timeout (180 seconds) because they may
98 // be waiting on the dev server to build an image.
99 if (!hardware_->IsOfficialBuild())
100 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700101 if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
Alex Deymoc1c17b42015-11-23 03:53:15 -0300102 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
103}
104
rspangler@google.com49fdf182009-10-10 00:57:34 +0000105LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800106 LOG_IF(ERROR, transfer_in_progress_)
107 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000108 CleanUp();
109}
110
Kelvin Zhang0c184242024-10-25 11:19:27 -0700111bool LibcurlHttpFetcher::GetProxyType(const string& proxy_str,
Gilad Arnold59d9e012013-07-23 16:41:43 -0700112 curl_proxytype* out_type) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700113 auto proxy = ToLower(proxy_str);
114 if (android::base::StartsWith(proxy, "socks5://") ||
115 android::base::StartsWith(proxy, "socks://")) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700116 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
117 return true;
118 }
Kelvin Zhang0c184242024-10-25 11:19:27 -0700119 if (android::base::StartsWith(proxy, "socks4://")) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700120 *out_type = CURLPROXY_SOCKS4A;
121 return true;
122 }
Kelvin Zhang0c184242024-10-25 11:19:27 -0700123 if (android::base::StartsWith(proxy, "http://") ||
124 android::base::StartsWith(proxy, "https://")) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700125 *out_type = CURLPROXY_HTTP;
126 return true;
127 }
Kelvin Zhang0c184242024-10-25 11:19:27 -0700128 if (android::base::StartsWith(proxy, kNoProxy)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700129 // known failure case. don't log.
130 return false;
131 }
132 LOG(INFO) << "Unknown proxy type: " << proxy;
133 return false;
134}
135
Alex Deymof329b932014-10-30 01:37:48 -0700136void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700137 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000138 CHECK(!transfer_in_progress_);
139 url_ = url;
140 curl_multi_handle_ = curl_multi_init();
141 CHECK(curl_multi_handle_);
142
143 curl_handle_ = curl_easy_init();
144 CHECK(curl_handle_);
Alex Deymof2858572016-02-25 11:20:13 -0800145 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000146
Alex Deymo13e95182017-03-16 19:06:13 -0700147 // Tag and untag the socket for network usage stats.
Alex Deymo63cfcf42017-02-23 15:29:47 -0800148 curl_easy_setopt(
149 curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
Alex Deymo13e95182017-03-16 19:06:13 -0700150 curl_easy_setopt(
151 curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
152 curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
Alex Deymo63cfcf42017-02-23 15:29:47 -0800153
Andrew de los Reyes45168102010-11-22 11:13:50 -0800154 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700155 bool is_direct = (GetCurrentProxy() == kNoProxy);
156 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
157 if (is_direct) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800158 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800159 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800160 CHECK_EQ(curl_easy_setopt(
161 curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
162 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800163 // Curl seems to require us to set the protocol
Daniel Zhengda4f7292022-09-02 22:59:32 +0000164 curl_proxytype type{};
Gilad Arnold59d9e012013-07-23 16:41:43 -0700165 if (GetProxyType(GetCurrentProxy(), &type)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800166 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
167 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800168 }
169 }
170
rspangler@google.com49fdf182009-10-10 00:57:34 +0000171 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000172 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800173 CHECK_EQ(
174 curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
175 CURLE_OK);
176 CHECK_EQ(curl_easy_setopt(
177 curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000178 CURLE_OK);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800179 }
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800180
Alex Deymofdd6dec2016-03-03 22:35:43 -0800181 // Setup extra HTTP headers.
182 if (curl_http_headers_) {
183 curl_slist_free_all(curl_http_headers_);
184 curl_http_headers_ = nullptr;
185 }
186 for (const auto& header : extra_headers_) {
187 // curl_slist_append() copies the string.
188 curl_http_headers_ =
189 curl_slist_append(curl_http_headers_, header.second.c_str());
190 }
191 if (post_data_set_) {
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800192 // Set the Content-Type HTTP header, if one was specifically set.
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800193 if (post_content_type_ != kHttpContentTypeUnspecified) {
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700194 const string content_type_attr = android::base::StringPrintf(
Alex Deymofdd6dec2016-03-03 22:35:43 -0800195 "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
196 curl_http_headers_ =
197 curl_slist_append(curl_http_headers_, content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800198 } else {
199 LOG(WARNING) << "no content type set, using libcurl default";
200 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000201 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800202 CHECK_EQ(
203 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
204 CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000205
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800206 if (bytes_downloaded_ > 0 || download_length_) {
207 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000208 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800209 CHECK_GE(resume_offset_, 0);
210
211 // Compute end offset, if one is specified. As per HTTP specification, this
212 // is an inclusive boundary. Make sure it doesn't overflow.
213 size_t end_offset = 0;
214 if (download_length_) {
215 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800216 CHECK_LE((size_t)resume_offset_, end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800217 }
218
219 // Create a string representation of the desired range.
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700220 string range_str = android::base::StringPrintf(
Alex Deymoc00c98a2015-03-17 17:38:00 -0700221 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
222 if (end_offset)
223 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800224 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
225 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000226 }
227
228 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800229 CHECK_EQ(
230 curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
231 CURLE_OK);
232 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700233
David Zeuthen34135a92013-08-06 11:16:16 -0700234 // If the connection drops under |low_speed_limit_bps_| (10
235 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
236 // 180 on non-official builds), reconnect.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800237 CHECK_EQ(curl_easy_setopt(
238 curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700239 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800240 CHECK_EQ(curl_easy_setopt(
241 curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700242 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800243 CHECK_EQ(curl_easy_setopt(
244 curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700245 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700246
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700247 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700248 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700249 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800250 CHECK_EQ(
251 curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
252 CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700253
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700254 // Lock down the appropriate curl options for HTTP or HTTPS depending on
255 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300256 if (hardware_->IsOfficialBuild()) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700257 if (android::base::StartsWith(ToLower(url_), "http://")) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800258 SetCurlOptionsForHttp();
Kelvin Zhang0c184242024-10-25 11:19:27 -0700259 } else if (android::base::StartsWith(ToLower(url_), "https://")) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800260 SetCurlOptionsForHttps();
Amin Hassani565331e2019-06-24 14:11:29 -0700261#ifdef __ANDROID__
Kelvin Zhang0c184242024-10-25 11:19:27 -0700262 } else if (android::base::StartsWith(ToLower(url_), "file://")) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800263 SetCurlOptionsForFile();
Amin Hassani565331e2019-06-24 14:11:29 -0700264#endif // __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800265 } else {
266 LOG(ERROR) << "Received invalid URI: " << url_;
267 // Lock down to no protocol supported for the transfer.
268 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
269 }
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800270 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700271 LOG(INFO) << "Not setting http(s) curl options because we are "
272 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700273 }
274
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000275 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000276 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000277}
278
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800279// Lock down only the protocol in case of HTTP.
280void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
281 LOG(INFO) << "Setting up curl options for HTTP";
282 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
283 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800284 CHECK_EQ(
285 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
286 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800287}
288
289// Security lock-down in official builds: makes sure that peer certificate
290// verification is enabled, restricts the set of trusted certificates,
291// restricts protocols to HTTPS, restricts ciphers to HIGH.
292void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
293 LOG(INFO) << "Setting up curl options for HTTPS";
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800294 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
295 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
Alex Khouderchah84634dc2019-04-04 09:25:39 -0700296 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAINFO, nullptr), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800297 CHECK_EQ(curl_easy_setopt(
298 curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800299 CURLE_OK);
300 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
301 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800302 CHECK_EQ(
303 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
304 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800305 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
306 CURLE_OK);
Alex Deymo33e91e72015-12-01 18:26:08 -0300307 if (server_to_check_ != ServerToCheck::kNone) {
308 CHECK_EQ(
309 curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
310 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800311 CHECK_EQ(curl_easy_setopt(curl_handle_,
312 CURLOPT_SSL_CTX_FUNCTION,
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800313 CertificateChecker::ProcessSSLContext),
314 CURLE_OK);
315 }
316}
317
Alex Deymo56ccb072016-02-05 00:50:48 -0800318// Lock down only the protocol in case of a local file.
319void LibcurlHttpFetcher::SetCurlOptionsForFile() {
320 LOG(INFO) << "Setting up curl options for FILE";
321 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
322 CURLE_OK);
323 CHECK_EQ(
324 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
325 CURLE_OK);
326}
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800327
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000328// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700329void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800330 CHECK(!transfer_in_progress_);
331 url_ = url;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800332
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000333 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000334 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700335 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800336 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700337 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800338 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700339 sent_byte_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800340
341 // If we are paused, we delay these two operations until Unpause is called.
342 if (transfer_paused_) {
343 restart_transfer_on_unpause_ = true;
344 return;
345 }
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800346 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700347 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000348}
349
Darin Petkov9ce452b2010-11-17 14:33:28 -0800350void LibcurlHttpFetcher::ForceTransferTermination() {
351 CleanUp();
352 if (delegate_) {
353 // Note that after the callback returns this object may be destroyed.
354 delegate_->TransferTerminated(this);
355 }
356}
357
rspangler@google.com49fdf182009-10-10 00:57:34 +0000358void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800359 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700360 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800361 } else {
362 ForceTransferTermination();
363 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364}
365
Alex Deymofdd6dec2016-03-03 22:35:43 -0800366void LibcurlHttpFetcher::SetHeader(const string& header_name,
367 const string& header_value) {
368 string header_line = header_name + ": " + header_value;
369 // Avoid the space if no data on the right side of the semicolon.
370 if (header_value.empty())
371 header_line = header_name + ":";
372 TEST_AND_RETURN(header_line.find('\n') == string::npos);
373 TEST_AND_RETURN(header_name.find(':') == string::npos);
Kelvin Zhang0c184242024-10-25 11:19:27 -0700374 extra_headers_[ToLower(header_name)] = header_line;
Alex Deymofdd6dec2016-03-03 22:35:43 -0800375}
376
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700377// Inputs: header_name, header_value
378// Example:
379// extra_headers_ = { {"foo":"foo: 123"}, {"bar":"bar:"} }
380// string tmp = "gibberish";
381// Case 1:
382// GetHeader("foo", &tmp) -> tmp = "123", return true.
383// Case 2:
384// GetHeader("bar", &tmp) -> tmp = "", return true.
385// Case 3:
386// GetHeader("moo", &tmp) -> tmp = "", return false.
387bool LibcurlHttpFetcher::GetHeader(const string& header_name,
388 string* header_value) const {
389 // Initially clear |header_value| to handle both success and failures without
390 // leaving |header_value| in a unclear state.
391 header_value->clear();
Kelvin Zhang0c184242024-10-25 11:19:27 -0700392 auto header_key = ToLower(header_name);
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700393 auto header_line_itr = extra_headers_.find(header_key);
394 // If the |header_name| was never set, indicate so by returning false.
395 if (header_line_itr == extra_headers_.end())
396 return false;
397 // From |SetHeader()| the check for |header_name| to not include ":" is
398 // verified, so finding the first index of ":" is a safe operation.
399 auto header_line = header_line_itr->second;
400 *header_value = header_line.substr(header_line.find(':') + 1);
401 // The following is neccessary to remove the leading ' ' before the header
402 // value that was place only if |header_value| passed to |SetHeader()| was
403 // a non-empty string.
404 header_value->erase(0, 1);
405 return true;
406}
407
Andrew de los Reyescb319332010-07-19 10:55:01 -0700408void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409 CHECK(transfer_in_progress_);
410 int running_handles = 0;
411 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
412
413 // libcurl may request that we immediately call curl_multi_perform after it
414 // returns, so we do. libcurl promises that curl_multi_perform will not block.
415 while (CURLM_CALL_MULTI_PERFORM == retcode) {
416 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700417 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800418 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700419 return;
420 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000421 }
Alex Deymof2858572016-02-25 11:20:13 -0800422
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700423 // When retcode is not |CURLM_OK| at this point, libcurl has an internal error
424 // that it is less likely to recover from (libcurl bug, out-of-memory, etc.).
425 // In case of an update check, we send UMA metrics and log the error.
426 if (is_update_check_ &&
427 (retcode == CURLM_OUT_OF_MEMORY || retcode == CURLM_INTERNAL_ERROR)) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700428 auxiliary_error_code_ = ErrorCode::kInternalLibCurlError;
Xiaochu Liua4fa6602019-08-05 17:06:35 +0000429 LOG(ERROR) << "curl_multi_perform is in an unrecoverable error condition: "
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700430 << retcode;
431 } else if (retcode != CURLM_OK) {
432 LOG(ERROR) << "curl_multi_perform returns error: " << retcode;
433 }
434
Alex Deymof2858572016-02-25 11:20:13 -0800435 // If the transfer completes while paused, we should ignore the failure once
436 // the fetcher is unpaused.
437 if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
438 LOG(INFO) << "Connection closed while paused, ignoring failure.";
439 ignore_failure_ = true;
440 }
441
442 if (running_handles != 0 || transfer_paused_) {
443 // There's either more work to do or we are paused, so we just keep the
444 // file descriptors to watch up to date and exit, until we are done with the
445 // work and we are not paused.
Amin Hassanice99ee72020-10-07 22:24:33 -0700446 //
447 // When there's no |base::SingleThreadTaskRunner| on current thread, it's
448 // not possible to watch file descriptors. Just poll it later. This usually
449 // happens if |brillo::FakeMessageLoop| is used.
Tianjie934b8472020-06-24 23:10:49 -0700450 if (!base::ThreadTaskRunnerHandle::IsSet()) {
Amin Hassani99563202020-09-15 15:30:09 -0700451 MessageLoop::current()->PostDelayedTask(
452 FROM_HERE,
453 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
454 base::Unretained(this)),
455 TimeDelta::FromSeconds(1));
456 return;
Tianjie934b8472020-06-24 23:10:49 -0700457 }
Alex Deymof2858572016-02-25 11:20:13 -0800458 SetupMessageLoopSources();
459 return;
460 }
461
462 // At this point, the transfer was completed in some way (error, connection
463 // closed or download finished).
464
465 GetHttpResponseCode();
466 if (http_response_code_) {
467 LOG(INFO) << "HTTP response code: " << http_response_code_;
468 no_network_retry_count_ = 0;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700469 unresolved_host_state_machine_.UpdateState(false);
Alex Deymof2858572016-02-25 11:20:13 -0800470 } else {
471 LOG(ERROR) << "Unable to get http response code.";
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700472 CURLcode curl_code = GetCurlCode();
473 LOG(ERROR) << "Return code for the transfer: " << curl_code;
474 if (curl_code == CURLE_COULDNT_RESOLVE_HOST) {
475 LOG(ERROR) << "libcurl can not resolve host.";
476 unresolved_host_state_machine_.UpdateState(true);
Amin Hassanid3d84212019-08-17 00:27:44 -0700477 auxiliary_error_code_ = ErrorCode::kUnresolvedHostError;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700478 }
Alex Deymof2858572016-02-25 11:20:13 -0800479 }
480
481 // we're done!
482 CleanUp();
483
Amin Hassanid3d84212019-08-17 00:27:44 -0700484 if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700485 UnresolvedHostStateMachine::State::kRetry) {
486 // Based on
487 // https://curl.haxx.se/docs/todo.html#updated_DNS_server_while_running,
488 // update_engine process should call res_init() and unconditionally retry.
489 res_init();
490 no_network_max_retries_++;
491 LOG(INFO) << "Will retry after reloading resolv.conf because last attempt "
492 "failed to resolve host.";
Amin Hassanid3d84212019-08-17 00:27:44 -0700493 } else if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700494 UnresolvedHostStateMachine::State::kRetriedSuccess) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700495 auxiliary_error_code_ = ErrorCode::kUnresolvedHostRecovered;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700496 }
497
Alex Deymof2858572016-02-25 11:20:13 -0800498 // TODO(petkov): This temporary code tries to deal with the case where the
499 // update engine performs an update check while the network is not ready
500 // (e.g., right after resume). Longer term, we should check if the network
501 // is online/offline and return an appropriate error code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800502 if (!sent_byte_ && http_response_code_ == 0 &&
Alex Deymof2858572016-02-25 11:20:13 -0800503 no_network_retry_count_ < no_network_max_retries_) {
504 no_network_retry_count_++;
Alex Deymob20de692017-02-05 07:47:37 +0000505 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymof2858572016-02-25 11:20:13 -0800506 FROM_HERE,
507 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
508 base::Unretained(this)),
509 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
510 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
511 } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
512 IsHttpResponseError()) {
513 // The transfer completed w/ error and we didn't get any bytes.
514 // If we have another proxy to try, try that.
515 //
516 // TODO(garnold) in fact there are two separate cases here: one case is an
517 // other-than-success return code (including no return code) and no
518 // received bytes, which is necessary due to the way callbacks are
519 // currently processing error conditions; the second is an explicit HTTP
520 // error code, where some data may have been received (as in the case of a
521 // semi-successful multi-chunk fetch). This is a confusing behavior and
522 // should be unified into a complete, coherent interface.
523 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
524 << "), " << bytes_downloaded_ << " bytes downloaded";
525
526 PopProxy(); // Delete the proxy we just gave up on.
527
528 if (HasProxy()) {
529 // We have another proxy. Retry immediately.
530 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymob20de692017-02-05 07:47:37 +0000531 retry_task_id_ = MessageLoop::current()->PostTask(
Alex Deymof2858572016-02-25 11:20:13 -0800532 FROM_HERE,
533 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
534 base::Unretained(this)));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700535 } else {
Alex Deymof2858572016-02-25 11:20:13 -0800536 // Out of proxies. Give up.
537 LOG(INFO) << "No further proxies, indicating transfer complete";
538 if (delegate_)
539 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700540 return;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700541 }
Alex Deymof2858572016-02-25 11:20:13 -0800542 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
543 if (!ignore_failure_)
544 retry_count_++;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800545 LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
546 << " of " << transfer_size_ << " bytes. "
Alex Deymof2858572016-02-25 11:20:13 -0800547 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
548 << "after " << retry_count_ << " attempt(s)";
Darin Petkov192ced42010-07-23 16:20:24 -0700549
Alex Deymof2858572016-02-25 11:20:13 -0800550 if (retry_count_ > max_retry_count_) {
551 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
552 if (delegate_)
553 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700554 return;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000555 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700556 // Need to restart transfer
557 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymob20de692017-02-05 07:47:37 +0000558 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymo021a45e2016-03-15 13:12:05 -0700559 FROM_HERE,
560 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
561 base::Unretained(this)),
562 TimeDelta::FromSeconds(retry_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000563 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800564 LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
565 << bytes_downloaded_ << " bytes downloaded";
Alex Deymof2858572016-02-25 11:20:13 -0800566 if (delegate_) {
567 bool success = IsHttpResponseSuccess();
568 delegate_->TransferComplete(this, success);
569 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700570 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000571 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700572 // If we reach this point is because TransferComplete() was not called in any
573 // of the previous branches. The delegate is allowed to destroy the object
574 // once TransferComplete is called so this would be illegal.
Alex Deymof2858572016-02-25 11:20:13 -0800575 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000576}
577
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800578size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800579 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700580 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800581 const size_t payload_size = size * nmemb;
582
583 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800584 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800585 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
586 << ") or no payload (" << payload_size << "), nothing to do";
587 return 0;
588 }
589
590 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000591 {
Daniel Zhengda4f7292022-09-02 22:59:32 +0000592 double transfer_size_double{};
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000593 CHECK_EQ(curl_easy_getinfo(curl_handle_,
594 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800595 &transfer_size_double),
596 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000597 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
598 if (new_transfer_size > 0) {
599 transfer_size_ = resume_offset_ + new_transfer_size;
600 }
601 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800602 bytes_downloaded_ += payload_size;
Tao Bao028ea412018-12-27 14:12:14 -0800603 if (delegate_) {
604 in_write_callback_ = true;
605 auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
606 in_write_callback_ = false;
607 if (should_terminate) {
608 LOG(INFO) << "Requesting libcurl to terminate transfer.";
609 // Returning an amount that differs from the received size signals an
610 // error condition to libcurl, which will cause the transfer to be
611 // aborted.
612 return 0;
613 }
614 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800615 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000616}
617
618void LibcurlHttpFetcher::Pause() {
Alex Deymof2858572016-02-25 11:20:13 -0800619 if (transfer_paused_) {
620 LOG(ERROR) << "Fetcher already paused.";
621 return;
622 }
623 transfer_paused_ = true;
624 if (!transfer_in_progress_) {
625 // If pause before we started a connection, we don't need to notify curl
626 // about that, we will simply not start the connection later.
627 return;
628 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000629 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000630 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000631}
632
633void LibcurlHttpFetcher::Unpause() {
Alex Deymof2858572016-02-25 11:20:13 -0800634 if (!transfer_paused_) {
635 LOG(ERROR) << "Resume attempted when fetcher not paused.";
636 return;
637 }
638 transfer_paused_ = false;
639 if (restart_transfer_on_unpause_) {
640 restart_transfer_on_unpause_ = false;
641 ResumeTransfer(url_);
642 CurlPerformOnce();
643 return;
644 }
645 if (!transfer_in_progress_) {
646 // If resumed before starting the connection, there's no need to notify
647 // anybody. We will simply start the connection once it is time.
648 return;
649 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000650 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000651 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
Alex Deymof2858572016-02-25 11:20:13 -0800652 // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
653 // now to let the connection continue, otherwise it would be called by the
654 // TimeoutCallback but with a delay.
655 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000656}
657
Alex Deymo29b81532015-07-09 11:51:49 -0700658// This method sets up callbacks with the MessageLoop.
659void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000660 fd_set fd_read;
661 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700662 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000663
664 FD_ZERO(&fd_read);
665 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700666 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000667
668 int fd_max = 0;
669
670 // Ask libcurl for the set of file descriptors we should track on its
671 // behalf.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800672 CHECK_EQ(curl_multi_fdset(
673 curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
674 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000675
676 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700677 // the highest one we're tracking, whichever is larger.
Kokoa Matsuda91aa2172024-10-16 16:01:04 +0900678 for (size_t t = 0; t < std::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900679 if (!fd_controller_maps_[t].empty())
680 fd_max = max(fd_max, fd_controller_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700681 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000682
Darin Petkov60e14152010-10-27 16:57:04 -0700683 // For each fd, if we're not tracking it, track it. If we are tracking it, but
684 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900685 // there should be exactly as many tasks scheduled in
686 // fd_controller_maps_[0|1] as there are read/write fds that we're tracking.
Darin Petkov60e14152010-10-27 16:57:04 -0700687 for (int fd = 0; fd <= fd_max; ++fd) {
688 // Note that fd_exc is unused in the current version of libcurl so is_exc
689 // should always be false.
690 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
691 bool must_track[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800692 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
693 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
Darin Petkov60e14152010-10-27 16:57:04 -0700694 };
695
Kokoa Matsuda91aa2172024-10-16 16:01:04 +0900696 for (size_t t = 0; t < std::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900697 bool tracked =
698 fd_controller_maps_[t].find(fd) != fd_controller_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700699
700 if (!must_track[t]) {
701 // If we have an outstanding io_channel, remove it.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900702 fd_controller_maps_[t].erase(fd);
Darin Petkov60e14152010-10-27 16:57:04 -0700703 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000704 }
Darin Petkov60e14152010-10-27 16:57:04 -0700705
706 // If we are already tracking this fd, continue -- nothing to do.
707 if (tracked)
708 continue;
709
Darin Petkov60e14152010-10-27 16:57:04 -0700710 // Track a new fd.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900711 switch (t) {
712 case 0: // Read
713 fd_controller_maps_[t][fd] =
714 base::FileDescriptorWatcher::WatchReadable(
715 fd,
716 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
717 base::Unretained(this)));
718 break;
719 case 1: // Write
720 fd_controller_maps_[t][fd] =
721 base::FileDescriptorWatcher::WatchWritable(
722 fd,
723 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
724 base::Unretained(this)));
725 }
Darin Petkov60e14152010-10-27 16:57:04 -0700726 static int io_counter = 0;
727 io_counter++;
728 if (io_counter % 50 == 0) {
729 LOG(INFO) << "io_counter = " << io_counter;
730 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700731 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000732 }
733
Darin Petkovb83371f2010-08-17 09:34:49 -0700734 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700735 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Alex Deymof2858572016-02-25 11:20:13 -0800736 VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700737 timeout_id_ = MessageLoop::current()->PostDelayedTask(
738 FROM_HERE,
739 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
740 base::Unretained(this)),
741 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000742 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000743}
744
Alex Deymo60ca1a72015-06-18 18:19:15 -0700745void LibcurlHttpFetcher::RetryTimeoutCallback() {
Alex Deymob20de692017-02-05 07:47:37 +0000746 retry_task_id_ = MessageLoop::kTaskIdNull;
Alex Deymof2858572016-02-25 11:20:13 -0800747 if (transfer_paused_) {
748 restart_transfer_on_unpause_ = true;
749 return;
750 }
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700751 ResumeTransfer(url_);
752 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700753}
754
Alex Deymo60ca1a72015-06-18 18:19:15 -0700755void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700756 // We always re-schedule the callback, even if we don't want to be called
757 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700758 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700759 timeout_id_ = MessageLoop::current()->PostDelayedTask(
760 FROM_HERE,
761 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
762 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700763
764 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
765 // first, since it could be canceled by this call.
766 if (transfer_in_progress_)
767 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000768}
769
770void LibcurlHttpFetcher::CleanUp() {
Alex Deymob20de692017-02-05 07:47:37 +0000771 MessageLoop::current()->CancelTask(retry_task_id_);
772 retry_task_id_ = MessageLoop::kTaskIdNull;
773
Alex Deymo60ca1a72015-06-18 18:19:15 -0700774 MessageLoop::current()->CancelTask(timeout_id_);
775 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000776
Kokoa Matsuda91aa2172024-10-16 16:01:04 +0900777 for (size_t t = 0; t < std::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900778 fd_controller_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000779 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000780
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800781 if (curl_http_headers_) {
782 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700783 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800784 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000785 if (curl_handle_) {
786 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000787 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
788 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000789 }
790 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700791 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000792 }
793 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000794 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700795 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000796 }
797 transfer_in_progress_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800798 transfer_paused_ = false;
799 restart_transfer_on_unpause_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000800}
801
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700802void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700803 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Kelvin Zhang0c184242024-10-25 11:19:27 -0700804 if (android::base::StartsWith(ToLower(url_), "file://")) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800805 // Fake out a valid response code for file:// URLs.
806 http_response_code_ = 299;
807 } else if (curl_easy_getinfo(curl_handle_,
808 CURLINFO_RESPONSE_CODE,
809 &http_response_code) == CURLE_OK) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700810 http_response_code_ = static_cast<int>(http_response_code);
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700811 } else {
812 LOG(ERROR) << "Unable to get http response code from curl_easy_getinfo";
813 }
814}
815
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700816CURLcode LibcurlHttpFetcher::GetCurlCode() {
817 CURLcode curl_code = CURLE_OK;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700818 while (true) {
819 // Repeated calls to |curl_multi_info_read| will return a new struct each
820 // time, until a NULL is returned as a signal that there is no more to get
821 // at this point.
Daniel Zhengda4f7292022-09-02 22:59:32 +0000822 int msgs_in_queue{};
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700823 CURLMsg* curl_msg =
824 curl_multi_info_read(curl_multi_handle_, &msgs_in_queue);
825 if (curl_msg == nullptr)
826 break;
827 // When |curl_msg| is |CURLMSG_DONE|, a transfer of an easy handle is done,
828 // and then data contains the return code for this transfer.
829 if (curl_msg->msg == CURLMSG_DONE) {
830 // Make sure |curl_multi_handle_| has one and only one easy handle
831 // |curl_handle_|.
832 CHECK_EQ(curl_handle_, curl_msg->easy_handle);
833 // Transfer return code reference:
834 // https://curl.haxx.se/libcurl/c/libcurl-errors.html
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700835 curl_code = curl_msg->data.result;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700836 }
837 }
838
839 // Gets connection error if exists.
840 long connect_error = 0; // NOLINT(runtime/int) - curl needs long.
841 CURLcode res =
842 curl_easy_getinfo(curl_handle_, CURLINFO_OS_ERRNO, &connect_error);
843 if (res == CURLE_OK && connect_error) {
844 LOG(ERROR) << "Connect error code from the OS: " << connect_error;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700845 }
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700846
847 return curl_code;
848}
849
850void UnresolvedHostStateMachine::UpdateState(bool failed_to_resolve_host) {
851 switch (state_) {
852 case State::kInit:
853 if (failed_to_resolve_host) {
854 state_ = State::kRetry;
855 }
856 break;
857 case State::kRetry:
858 if (failed_to_resolve_host) {
859 state_ = State::kNotRetry;
860 } else {
861 state_ = State::kRetriedSuccess;
862 }
863 break;
864 case State::kNotRetry:
865 break;
866 case State::kRetriedSuccess:
867 break;
868 default:
869 NOTREACHED();
870 break;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700871 }
872}
873
rspangler@google.com49fdf182009-10-10 00:57:34 +0000874} // namespace chromeos_update_engine