blob: 1599aac150b5043656975c32182ea5f75f461ba8 [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>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
Tianjie934b8472020-06-24 23:10:49 -070034#include <base/threading/thread_task_runner_handle.h>
35
Alex Deymo63cfcf42017-02-23 15:29:47 -080036#ifdef __ANDROID__
37#include <cutils/qtaguid.h>
Alex Deymoeb256552017-03-21 22:52:54 -070038#include <private/android_filesystem_config.h>
Alex Deymo63cfcf42017-02-23 15:29:47 -080039#endif // __ANDROID__
40
Alex Deymo14c0da82016-07-20 16:45:45 -070041#include "update_engine/certificate_checker.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080042#include "update_engine/common/hardware_interface.h"
43#include "update_engine/common/platform_constants.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.
hscham00b6aa22020-02-20 12:32:06 +090085 for (size_t t = 0; t < base::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
Alex Deymo33e91e72015-12-01 18:26:08 -030095LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
96 HardwareInterface* hardware)
97 : HttpFetcher(proxy_resolver), hardware_(hardware) {
Alex Deymoc1c17b42015-11-23 03:53:15 -030098 // Dev users want a longer timeout (180 seconds) because they may
99 // be waiting on the dev server to build an image.
100 if (!hardware_->IsOfficialBuild())
101 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700102 if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
Alex Deymoc1c17b42015-11-23 03:53:15 -0300103 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
104}
105
rspangler@google.com49fdf182009-10-10 00:57:34 +0000106LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800107 LOG_IF(ERROR, transfer_in_progress_)
108 << "Destroying the fetcher while a transfer is in progress.";
Alex Deymo71f67622017-02-03 21:30:24 -0800109 CancelProxyResolution();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000110 CleanUp();
111}
112
Alex Deymof329b932014-10-30 01:37:48 -0700113bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -0700114 curl_proxytype* out_type) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800115 if (base::StartsWith(
116 proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
117 base::StartsWith(
118 proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700119 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
120 return true;
121 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800122 if (base::StartsWith(
123 proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700124 *out_type = CURLPROXY_SOCKS4A;
125 return true;
126 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800127 if (base::StartsWith(
128 proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
129 base::StartsWith(
130 proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700131 *out_type = CURLPROXY_HTTP;
132 return true;
133 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800134 if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700135 // known failure case. don't log.
136 return false;
137 }
138 LOG(INFO) << "Unknown proxy type: " << proxy;
139 return false;
140}
141
Alex Deymof329b932014-10-30 01:37:48 -0700142void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700143 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000144 CHECK(!transfer_in_progress_);
145 url_ = url;
146 curl_multi_handle_ = curl_multi_init();
147 CHECK(curl_multi_handle_);
148
149 curl_handle_ = curl_easy_init();
150 CHECK(curl_handle_);
Alex Deymof2858572016-02-25 11:20:13 -0800151 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000152
Alex Deymo13e95182017-03-16 19:06:13 -0700153 // Tag and untag the socket for network usage stats.
Alex Deymo63cfcf42017-02-23 15:29:47 -0800154 curl_easy_setopt(
155 curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
Alex Deymo13e95182017-03-16 19:06:13 -0700156 curl_easy_setopt(
157 curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
158 curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
Alex Deymo63cfcf42017-02-23 15:29:47 -0800159
Andrew de los Reyes45168102010-11-22 11:13:50 -0800160 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700161 bool is_direct = (GetCurrentProxy() == kNoProxy);
162 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
163 if (is_direct) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800164 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800165 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800166 CHECK_EQ(curl_easy_setopt(
167 curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
168 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800169 // Curl seems to require us to set the protocol
170 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700171 if (GetProxyType(GetCurrentProxy(), &type)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800172 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
173 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800174 }
175 }
176
rspangler@google.com49fdf182009-10-10 00:57:34 +0000177 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000178 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800179 CHECK_EQ(
180 curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
181 CURLE_OK);
182 CHECK_EQ(curl_easy_setopt(
183 curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000184 CURLE_OK);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800185 }
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800186
Alex Deymofdd6dec2016-03-03 22:35:43 -0800187 // Setup extra HTTP headers.
188 if (curl_http_headers_) {
189 curl_slist_free_all(curl_http_headers_);
190 curl_http_headers_ = nullptr;
191 }
192 for (const auto& header : extra_headers_) {
193 // curl_slist_append() copies the string.
194 curl_http_headers_ =
195 curl_slist_append(curl_http_headers_, header.second.c_str());
196 }
197 if (post_data_set_) {
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800198 // Set the Content-Type HTTP header, if one was specifically set.
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800199 if (post_content_type_ != kHttpContentTypeUnspecified) {
Alex Deymofdd6dec2016-03-03 22:35:43 -0800200 const string content_type_attr = base::StringPrintf(
201 "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
202 curl_http_headers_ =
203 curl_slist_append(curl_http_headers_, content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800204 } else {
205 LOG(WARNING) << "no content type set, using libcurl default";
206 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000207 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800208 CHECK_EQ(
209 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
210 CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000211
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800212 if (bytes_downloaded_ > 0 || download_length_) {
213 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000214 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800215 CHECK_GE(resume_offset_, 0);
216
217 // Compute end offset, if one is specified. As per HTTP specification, this
218 // is an inclusive boundary. Make sure it doesn't overflow.
219 size_t end_offset = 0;
220 if (download_length_) {
221 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800222 CHECK_LE((size_t)resume_offset_, end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800223 }
224
225 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700226 string range_str = base::StringPrintf(
227 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
228 if (end_offset)
229 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800230 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
231 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000232 }
233
234 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800235 CHECK_EQ(
236 curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
237 CURLE_OK);
238 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700239
David Zeuthen34135a92013-08-06 11:16:16 -0700240 // If the connection drops under |low_speed_limit_bps_| (10
241 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
242 // 180 on non-official builds), reconnect.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800243 CHECK_EQ(curl_easy_setopt(
244 curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700245 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800246 CHECK_EQ(curl_easy_setopt(
247 curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700248 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800249 CHECK_EQ(curl_easy_setopt(
250 curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700251 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700252
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700253 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700254 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700255 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800256 CHECK_EQ(
257 curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
258 CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700259
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700260 // Lock down the appropriate curl options for HTTP or HTTPS depending on
261 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300262 if (hardware_->IsOfficialBuild()) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800263 if (base::StartsWith(
264 url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800265 SetCurlOptionsForHttp();
Alex Deymo56ccb072016-02-05 00:50:48 -0800266 } else if (base::StartsWith(
267 url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800268 SetCurlOptionsForHttps();
Amin Hassani565331e2019-06-24 14:11:29 -0700269#ifdef __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800270 } else if (base::StartsWith(
271 url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
272 SetCurlOptionsForFile();
Amin Hassani565331e2019-06-24 14:11:29 -0700273#endif // __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800274 } else {
275 LOG(ERROR) << "Received invalid URI: " << url_;
276 // Lock down to no protocol supported for the transfer.
277 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
278 }
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800279 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700280 LOG(INFO) << "Not setting http(s) curl options because we are "
281 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700282 }
283
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000284 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000285 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000286}
287
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800288// Lock down only the protocol in case of HTTP.
289void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
290 LOG(INFO) << "Setting up curl options for HTTP";
291 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
292 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800293 CHECK_EQ(
294 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
295 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800296}
297
298// Security lock-down in official builds: makes sure that peer certificate
299// verification is enabled, restricts the set of trusted certificates,
300// restricts protocols to HTTPS, restricts ciphers to HIGH.
301void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
302 LOG(INFO) << "Setting up curl options for HTTPS";
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800303 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
304 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
Alex Khouderchah84634dc2019-04-04 09:25:39 -0700305 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAINFO, nullptr), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800306 CHECK_EQ(curl_easy_setopt(
307 curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800308 CURLE_OK);
309 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
310 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800311 CHECK_EQ(
312 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
313 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800314 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
315 CURLE_OK);
Alex Deymo33e91e72015-12-01 18:26:08 -0300316 if (server_to_check_ != ServerToCheck::kNone) {
317 CHECK_EQ(
318 curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
319 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800320 CHECK_EQ(curl_easy_setopt(curl_handle_,
321 CURLOPT_SSL_CTX_FUNCTION,
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800322 CertificateChecker::ProcessSSLContext),
323 CURLE_OK);
324 }
325}
326
Alex Deymo56ccb072016-02-05 00:50:48 -0800327// Lock down only the protocol in case of a local file.
328void LibcurlHttpFetcher::SetCurlOptionsForFile() {
329 LOG(INFO) << "Setting up curl options for FILE";
330 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
331 CURLE_OK);
332 CHECK_EQ(
333 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
334 CURLE_OK);
335}
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800336
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000337// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700338void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800339 CHECK(!transfer_in_progress_);
340 url_ = url;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800341 auto closure =
342 base::Bind(&LibcurlHttpFetcher::ProxiesResolved, base::Unretained(this));
Daniel Erate5f6f252017-04-20 12:09:58 -0600343 ResolveProxiesForUrl(url_, closure);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800344}
345
346void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000347 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000348 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700349 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800350 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700351 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800352 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700353 sent_byte_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800354
355 // If we are paused, we delay these two operations until Unpause is called.
356 if (transfer_paused_) {
357 restart_transfer_on_unpause_ = true;
358 return;
359 }
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800360 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700361 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000362}
363
Darin Petkov9ce452b2010-11-17 14:33:28 -0800364void LibcurlHttpFetcher::ForceTransferTermination() {
Alex Deymo71f67622017-02-03 21:30:24 -0800365 CancelProxyResolution();
Darin Petkov9ce452b2010-11-17 14:33:28 -0800366 CleanUp();
367 if (delegate_) {
368 // Note that after the callback returns this object may be destroyed.
369 delegate_->TransferTerminated(this);
370 }
371}
372
rspangler@google.com49fdf182009-10-10 00:57:34 +0000373void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800374 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700375 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800376 } else {
377 ForceTransferTermination();
378 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000379}
380
Alex Deymofdd6dec2016-03-03 22:35:43 -0800381void LibcurlHttpFetcher::SetHeader(const string& header_name,
382 const string& header_value) {
383 string header_line = header_name + ": " + header_value;
384 // Avoid the space if no data on the right side of the semicolon.
385 if (header_value.empty())
386 header_line = header_name + ":";
387 TEST_AND_RETURN(header_line.find('\n') == string::npos);
388 TEST_AND_RETURN(header_name.find(':') == string::npos);
389 extra_headers_[base::ToLowerASCII(header_name)] = header_line;
390}
391
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700392// Inputs: header_name, header_value
393// Example:
394// extra_headers_ = { {"foo":"foo: 123"}, {"bar":"bar:"} }
395// string tmp = "gibberish";
396// Case 1:
397// GetHeader("foo", &tmp) -> tmp = "123", return true.
398// Case 2:
399// GetHeader("bar", &tmp) -> tmp = "", return true.
400// Case 3:
401// GetHeader("moo", &tmp) -> tmp = "", return false.
402bool LibcurlHttpFetcher::GetHeader(const string& header_name,
403 string* header_value) const {
404 // Initially clear |header_value| to handle both success and failures without
405 // leaving |header_value| in a unclear state.
406 header_value->clear();
407 auto header_key = base::ToLowerASCII(header_name);
408 auto header_line_itr = extra_headers_.find(header_key);
409 // If the |header_name| was never set, indicate so by returning false.
410 if (header_line_itr == extra_headers_.end())
411 return false;
412 // From |SetHeader()| the check for |header_name| to not include ":" is
413 // verified, so finding the first index of ":" is a safe operation.
414 auto header_line = header_line_itr->second;
415 *header_value = header_line.substr(header_line.find(':') + 1);
416 // The following is neccessary to remove the leading ' ' before the header
417 // value that was place only if |header_value| passed to |SetHeader()| was
418 // a non-empty string.
419 header_value->erase(0, 1);
420 return true;
421}
422
Andrew de los Reyescb319332010-07-19 10:55:01 -0700423void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000424 CHECK(transfer_in_progress_);
425 int running_handles = 0;
426 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
427
428 // libcurl may request that we immediately call curl_multi_perform after it
429 // returns, so we do. libcurl promises that curl_multi_perform will not block.
430 while (CURLM_CALL_MULTI_PERFORM == retcode) {
431 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700432 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800433 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700434 return;
435 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000436 }
Alex Deymof2858572016-02-25 11:20:13 -0800437
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700438 // When retcode is not |CURLM_OK| at this point, libcurl has an internal error
439 // that it is less likely to recover from (libcurl bug, out-of-memory, etc.).
440 // In case of an update check, we send UMA metrics and log the error.
441 if (is_update_check_ &&
442 (retcode == CURLM_OUT_OF_MEMORY || retcode == CURLM_INTERNAL_ERROR)) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700443 auxiliary_error_code_ = ErrorCode::kInternalLibCurlError;
Xiaochu Liua4fa6602019-08-05 17:06:35 +0000444 LOG(ERROR) << "curl_multi_perform is in an unrecoverable error condition: "
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700445 << retcode;
446 } else if (retcode != CURLM_OK) {
447 LOG(ERROR) << "curl_multi_perform returns error: " << retcode;
448 }
449
Alex Deymof2858572016-02-25 11:20:13 -0800450 // If the transfer completes while paused, we should ignore the failure once
451 // the fetcher is unpaused.
452 if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
453 LOG(INFO) << "Connection closed while paused, ignoring failure.";
454 ignore_failure_ = true;
455 }
456
457 if (running_handles != 0 || transfer_paused_) {
458 // There's either more work to do or we are paused, so we just keep the
459 // file descriptors to watch up to date and exit, until we are done with the
460 // work and we are not paused.
Amin Hassanice99ee72020-10-07 22:24:33 -0700461 //
462 // When there's no |base::SingleThreadTaskRunner| on current thread, it's
463 // not possible to watch file descriptors. Just poll it later. This usually
464 // happens if |brillo::FakeMessageLoop| is used.
Tianjie934b8472020-06-24 23:10:49 -0700465 if (!base::ThreadTaskRunnerHandle::IsSet()) {
Amin Hassani99563202020-09-15 15:30:09 -0700466 MessageLoop::current()->PostDelayedTask(
467 FROM_HERE,
468 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
469 base::Unretained(this)),
470 TimeDelta::FromSeconds(1));
471 return;
Tianjie934b8472020-06-24 23:10:49 -0700472 }
Alex Deymof2858572016-02-25 11:20:13 -0800473 SetupMessageLoopSources();
474 return;
475 }
476
477 // At this point, the transfer was completed in some way (error, connection
478 // closed or download finished).
479
480 GetHttpResponseCode();
481 if (http_response_code_) {
482 LOG(INFO) << "HTTP response code: " << http_response_code_;
483 no_network_retry_count_ = 0;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700484 unresolved_host_state_machine_.UpdateState(false);
Alex Deymof2858572016-02-25 11:20:13 -0800485 } else {
486 LOG(ERROR) << "Unable to get http response code.";
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700487 CURLcode curl_code = GetCurlCode();
488 LOG(ERROR) << "Return code for the transfer: " << curl_code;
489 if (curl_code == CURLE_COULDNT_RESOLVE_HOST) {
490 LOG(ERROR) << "libcurl can not resolve host.";
491 unresolved_host_state_machine_.UpdateState(true);
Amin Hassanid3d84212019-08-17 00:27:44 -0700492 auxiliary_error_code_ = ErrorCode::kUnresolvedHostError;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700493 }
Alex Deymof2858572016-02-25 11:20:13 -0800494 }
495
496 // we're done!
497 CleanUp();
498
Amin Hassanid3d84212019-08-17 00:27:44 -0700499 if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700500 UnresolvedHostStateMachine::State::kRetry) {
501 // Based on
502 // https://curl.haxx.se/docs/todo.html#updated_DNS_server_while_running,
503 // update_engine process should call res_init() and unconditionally retry.
504 res_init();
505 no_network_max_retries_++;
506 LOG(INFO) << "Will retry after reloading resolv.conf because last attempt "
507 "failed to resolve host.";
Amin Hassanid3d84212019-08-17 00:27:44 -0700508 } else if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700509 UnresolvedHostStateMachine::State::kRetriedSuccess) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700510 auxiliary_error_code_ = ErrorCode::kUnresolvedHostRecovered;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700511 }
512
Alex Deymof2858572016-02-25 11:20:13 -0800513 // TODO(petkov): This temporary code tries to deal with the case where the
514 // update engine performs an update check while the network is not ready
515 // (e.g., right after resume). Longer term, we should check if the network
516 // is online/offline and return an appropriate error code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800517 if (!sent_byte_ && http_response_code_ == 0 &&
Alex Deymof2858572016-02-25 11:20:13 -0800518 no_network_retry_count_ < no_network_max_retries_) {
519 no_network_retry_count_++;
Alex Deymob20de692017-02-05 07:47:37 +0000520 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymof2858572016-02-25 11:20:13 -0800521 FROM_HERE,
522 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
523 base::Unretained(this)),
524 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
525 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
526 } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
527 IsHttpResponseError()) {
528 // The transfer completed w/ error and we didn't get any bytes.
529 // If we have another proxy to try, try that.
530 //
531 // TODO(garnold) in fact there are two separate cases here: one case is an
532 // other-than-success return code (including no return code) and no
533 // received bytes, which is necessary due to the way callbacks are
534 // currently processing error conditions; the second is an explicit HTTP
535 // error code, where some data may have been received (as in the case of a
536 // semi-successful multi-chunk fetch). This is a confusing behavior and
537 // should be unified into a complete, coherent interface.
538 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
539 << "), " << bytes_downloaded_ << " bytes downloaded";
540
541 PopProxy(); // Delete the proxy we just gave up on.
542
543 if (HasProxy()) {
544 // We have another proxy. Retry immediately.
545 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymob20de692017-02-05 07:47:37 +0000546 retry_task_id_ = MessageLoop::current()->PostTask(
Alex Deymof2858572016-02-25 11:20:13 -0800547 FROM_HERE,
548 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
549 base::Unretained(this)));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700550 } else {
Alex Deymof2858572016-02-25 11:20:13 -0800551 // Out of proxies. Give up.
552 LOG(INFO) << "No further proxies, indicating transfer complete";
553 if (delegate_)
554 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700555 return;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700556 }
Alex Deymof2858572016-02-25 11:20:13 -0800557 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
558 if (!ignore_failure_)
559 retry_count_++;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800560 LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
561 << " of " << transfer_size_ << " bytes. "
Alex Deymof2858572016-02-25 11:20:13 -0800562 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
563 << "after " << retry_count_ << " attempt(s)";
Darin Petkov192ced42010-07-23 16:20:24 -0700564
Alex Deymof2858572016-02-25 11:20:13 -0800565 if (retry_count_ > max_retry_count_) {
566 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
567 if (delegate_)
568 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700569 return;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000570 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700571 // Need to restart transfer
572 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymob20de692017-02-05 07:47:37 +0000573 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymo021a45e2016-03-15 13:12:05 -0700574 FROM_HERE,
575 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
576 base::Unretained(this)),
577 TimeDelta::FromSeconds(retry_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000578 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800579 LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
580 << bytes_downloaded_ << " bytes downloaded";
Alex Deymof2858572016-02-25 11:20:13 -0800581 if (delegate_) {
582 bool success = IsHttpResponseSuccess();
583 delegate_->TransferComplete(this, success);
584 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700585 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000586 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700587 // If we reach this point is because TransferComplete() was not called in any
588 // of the previous branches. The delegate is allowed to destroy the object
589 // once TransferComplete is called so this would be illegal.
Alex Deymof2858572016-02-25 11:20:13 -0800590 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000591}
592
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800593size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800594 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700595 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800596 const size_t payload_size = size * nmemb;
597
598 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800599 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800600 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
601 << ") or no payload (" << payload_size << "), nothing to do";
602 return 0;
603 }
604
605 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000606 {
607 double transfer_size_double;
608 CHECK_EQ(curl_easy_getinfo(curl_handle_,
609 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800610 &transfer_size_double),
611 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000612 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
613 if (new_transfer_size > 0) {
614 transfer_size_ = resume_offset_ + new_transfer_size;
615 }
616 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800617 bytes_downloaded_ += payload_size;
Tao Bao028ea412018-12-27 14:12:14 -0800618 if (delegate_) {
619 in_write_callback_ = true;
620 auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
621 in_write_callback_ = false;
622 if (should_terminate) {
623 LOG(INFO) << "Requesting libcurl to terminate transfer.";
624 // Returning an amount that differs from the received size signals an
625 // error condition to libcurl, which will cause the transfer to be
626 // aborted.
627 return 0;
628 }
629 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800630 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000631}
632
633void LibcurlHttpFetcher::Pause() {
Alex Deymof2858572016-02-25 11:20:13 -0800634 if (transfer_paused_) {
635 LOG(ERROR) << "Fetcher already paused.";
636 return;
637 }
638 transfer_paused_ = true;
639 if (!transfer_in_progress_) {
640 // If pause before we started a connection, we don't need to notify curl
641 // about that, we will simply not start the connection later.
642 return;
643 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000645 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646}
647
648void LibcurlHttpFetcher::Unpause() {
Alex Deymof2858572016-02-25 11:20:13 -0800649 if (!transfer_paused_) {
650 LOG(ERROR) << "Resume attempted when fetcher not paused.";
651 return;
652 }
653 transfer_paused_ = false;
654 if (restart_transfer_on_unpause_) {
655 restart_transfer_on_unpause_ = false;
656 ResumeTransfer(url_);
657 CurlPerformOnce();
658 return;
659 }
660 if (!transfer_in_progress_) {
661 // If resumed before starting the connection, there's no need to notify
662 // anybody. We will simply start the connection once it is time.
663 return;
664 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000665 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000666 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
Alex Deymof2858572016-02-25 11:20:13 -0800667 // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
668 // now to let the connection continue, otherwise it would be called by the
669 // TimeoutCallback but with a delay.
670 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000671}
672
Alex Deymo29b81532015-07-09 11:51:49 -0700673// This method sets up callbacks with the MessageLoop.
674void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000675 fd_set fd_read;
676 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700677 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000678
679 FD_ZERO(&fd_read);
680 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700681 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000682
683 int fd_max = 0;
684
685 // Ask libcurl for the set of file descriptors we should track on its
686 // behalf.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800687 CHECK_EQ(curl_multi_fdset(
688 curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
689 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000690
691 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700692 // the highest one we're tracking, whichever is larger.
hscham00b6aa22020-02-20 12:32:06 +0900693 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900694 if (!fd_controller_maps_[t].empty())
695 fd_max = max(fd_max, fd_controller_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700696 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000697
Darin Petkov60e14152010-10-27 16:57:04 -0700698 // For each fd, if we're not tracking it, track it. If we are tracking it, but
699 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900700 // there should be exactly as many tasks scheduled in
701 // fd_controller_maps_[0|1] as there are read/write fds that we're tracking.
Darin Petkov60e14152010-10-27 16:57:04 -0700702 for (int fd = 0; fd <= fd_max; ++fd) {
703 // Note that fd_exc is unused in the current version of libcurl so is_exc
704 // should always be false.
705 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
706 bool must_track[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800707 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
708 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
Darin Petkov60e14152010-10-27 16:57:04 -0700709 };
710
hscham00b6aa22020-02-20 12:32:06 +0900711 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900712 bool tracked =
713 fd_controller_maps_[t].find(fd) != fd_controller_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700714
715 if (!must_track[t]) {
716 // If we have an outstanding io_channel, remove it.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900717 fd_controller_maps_[t].erase(fd);
Darin Petkov60e14152010-10-27 16:57:04 -0700718 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000719 }
Darin Petkov60e14152010-10-27 16:57:04 -0700720
721 // If we are already tracking this fd, continue -- nothing to do.
722 if (tracked)
723 continue;
724
Darin Petkov60e14152010-10-27 16:57:04 -0700725 // Track a new fd.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900726 switch (t) {
727 case 0: // Read
728 fd_controller_maps_[t][fd] =
729 base::FileDescriptorWatcher::WatchReadable(
730 fd,
731 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
732 base::Unretained(this)));
733 break;
734 case 1: // Write
735 fd_controller_maps_[t][fd] =
736 base::FileDescriptorWatcher::WatchWritable(
737 fd,
738 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
739 base::Unretained(this)));
740 }
Darin Petkov60e14152010-10-27 16:57:04 -0700741 static int io_counter = 0;
742 io_counter++;
743 if (io_counter % 50 == 0) {
744 LOG(INFO) << "io_counter = " << io_counter;
745 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700746 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000747 }
748
Darin Petkovb83371f2010-08-17 09:34:49 -0700749 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700750 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Alex Deymof2858572016-02-25 11:20:13 -0800751 VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700752 timeout_id_ = MessageLoop::current()->PostDelayedTask(
753 FROM_HERE,
754 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
755 base::Unretained(this)),
756 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000757 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000758}
759
Alex Deymo60ca1a72015-06-18 18:19:15 -0700760void LibcurlHttpFetcher::RetryTimeoutCallback() {
Alex Deymob20de692017-02-05 07:47:37 +0000761 retry_task_id_ = MessageLoop::kTaskIdNull;
Alex Deymof2858572016-02-25 11:20:13 -0800762 if (transfer_paused_) {
763 restart_transfer_on_unpause_ = true;
764 return;
765 }
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700766 ResumeTransfer(url_);
767 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700768}
769
Alex Deymo60ca1a72015-06-18 18:19:15 -0700770void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700771 // We always re-schedule the callback, even if we don't want to be called
772 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700773 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700774 timeout_id_ = MessageLoop::current()->PostDelayedTask(
775 FROM_HERE,
776 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
777 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700778
779 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
780 // first, since it could be canceled by this call.
781 if (transfer_in_progress_)
782 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000783}
784
785void LibcurlHttpFetcher::CleanUp() {
Alex Deymob20de692017-02-05 07:47:37 +0000786 MessageLoop::current()->CancelTask(retry_task_id_);
787 retry_task_id_ = MessageLoop::kTaskIdNull;
788
Alex Deymo60ca1a72015-06-18 18:19:15 -0700789 MessageLoop::current()->CancelTask(timeout_id_);
790 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000791
hscham00b6aa22020-02-20 12:32:06 +0900792 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900793 fd_controller_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000794 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000795
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800796 if (curl_http_headers_) {
797 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700798 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800799 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000800 if (curl_handle_) {
801 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000802 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
803 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000804 }
805 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700806 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000807 }
808 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000809 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700810 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000811 }
812 transfer_in_progress_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800813 transfer_paused_ = false;
814 restart_transfer_on_unpause_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000815}
816
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700817void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700818 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Alex Deymo56ccb072016-02-05 00:50:48 -0800819 if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
820 // Fake out a valid response code for file:// URLs.
821 http_response_code_ = 299;
822 } else if (curl_easy_getinfo(curl_handle_,
823 CURLINFO_RESPONSE_CODE,
824 &http_response_code) == CURLE_OK) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700825 http_response_code_ = static_cast<int>(http_response_code);
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700826 } else {
827 LOG(ERROR) << "Unable to get http response code from curl_easy_getinfo";
828 }
829}
830
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700831CURLcode LibcurlHttpFetcher::GetCurlCode() {
832 CURLcode curl_code = CURLE_OK;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700833 while (true) {
834 // Repeated calls to |curl_multi_info_read| will return a new struct each
835 // time, until a NULL is returned as a signal that there is no more to get
836 // at this point.
837 int msgs_in_queue;
838 CURLMsg* curl_msg =
839 curl_multi_info_read(curl_multi_handle_, &msgs_in_queue);
840 if (curl_msg == nullptr)
841 break;
842 // When |curl_msg| is |CURLMSG_DONE|, a transfer of an easy handle is done,
843 // and then data contains the return code for this transfer.
844 if (curl_msg->msg == CURLMSG_DONE) {
845 // Make sure |curl_multi_handle_| has one and only one easy handle
846 // |curl_handle_|.
847 CHECK_EQ(curl_handle_, curl_msg->easy_handle);
848 // Transfer return code reference:
849 // https://curl.haxx.se/libcurl/c/libcurl-errors.html
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700850 curl_code = curl_msg->data.result;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700851 }
852 }
853
854 // Gets connection error if exists.
855 long connect_error = 0; // NOLINT(runtime/int) - curl needs long.
856 CURLcode res =
857 curl_easy_getinfo(curl_handle_, CURLINFO_OS_ERRNO, &connect_error);
858 if (res == CURLE_OK && connect_error) {
859 LOG(ERROR) << "Connect error code from the OS: " << connect_error;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700860 }
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700861
862 return curl_code;
863}
864
865void UnresolvedHostStateMachine::UpdateState(bool failed_to_resolve_host) {
866 switch (state_) {
867 case State::kInit:
868 if (failed_to_resolve_host) {
869 state_ = State::kRetry;
870 }
871 break;
872 case State::kRetry:
873 if (failed_to_resolve_host) {
874 state_ = State::kNotRetry;
875 } else {
876 state_ = State::kRetriedSuccess;
877 }
878 break;
879 case State::kNotRetry:
880 break;
881 case State::kRetriedSuccess:
882 break;
883 default:
884 NOTREACHED();
885 break;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700886 }
887}
888
rspangler@google.com49fdf182009-10-10 00:57:34 +0000889} // namespace chromeos_update_engine