blob: 06722fd68020b4de6ab583bd6f2d82f26e092da8 [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
Alex Deymo63cfcf42017-02-23 15:29:47 -080019#include <sys/types.h>
20#include <unistd.h>
21
adlr@google.comc98a7ed2009-12-04 18:54:03 +000022#include <algorithm>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070023#include <string>
24
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070025#include <base/bind.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070026#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070027#include <base/location.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070028#include <base/logging.h>
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070029#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070030#include <base/strings/string_util.h>
31#include <base/strings/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070032
Alex Deymo63cfcf42017-02-23 15:29:47 -080033#ifdef __ANDROID__
34#include <cutils/qtaguid.h>
Alex Deymoeb256552017-03-21 22:52:54 -070035#include <private/android_filesystem_config.h>
Alex Deymo63cfcf42017-02-23 15:29:47 -080036#endif // __ANDROID__
37
Alex Deymo14c0da82016-07-20 16:45:45 -070038#include "update_engine/certificate_checker.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080039#include "update_engine/common/hardware_interface.h"
40#include "update_engine/common/platform_constants.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000041
Alex Deymo60ca1a72015-06-18 18:19:15 -070042using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070043using brillo::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070044using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070045using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000046
47// This is a concrete implementation of HttpFetcher that uses libcurl to do the
48// http work.
49
50namespace chromeos_update_engine {
51
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070052namespace {
Alex Deymo63cfcf42017-02-23 15:29:47 -080053
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080054const int kNoNetworkRetrySeconds = 10;
Alex Deymo63cfcf42017-02-23 15:29:47 -080055
Alex Deymo63cfcf42017-02-23 15:29:47 -080056// libcurl's CURLOPT_SOCKOPTFUNCTION callback function. Called after the socket
57// is created but before it is connected. This callback tags the created socket
58// so the network usage can be tracked in Android.
59int LibcurlSockoptCallback(void* /* clientp */,
60 curl_socket_t curlfd,
61 curlsocktype /* purpose */) {
62#ifdef __ANDROID__
Alex Deymo558fe6a2017-05-19 13:16:20 -070063 // Socket tag used by all network sockets. See qtaguid kernel module for
64 // stats.
65 const int kUpdateEngineSocketTag = 0x55417243; // "CrAU" in little-endian.
Alex Deymoeb256552017-03-21 22:52:54 -070066 qtaguid_tagSocket(curlfd, kUpdateEngineSocketTag, AID_OTA_UPDATE);
Alex Deymo63cfcf42017-02-23 15:29:47 -080067#endif // __ANDROID__
68 return CURL_SOCKOPT_OK;
69}
70
Alex Vakulenkod2779df2014-06-16 13:19:00 -070071} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070072
Alex Deymo13e95182017-03-16 19:06:13 -070073// static
74int LibcurlHttpFetcher::LibcurlCloseSocketCallback(void* clientp,
75 curl_socket_t item) {
76#ifdef __ANDROID__
77 qtaguid_untagSocket(item);
78#endif // __ANDROID__
79 LibcurlHttpFetcher* fetcher = static_cast<LibcurlHttpFetcher*>(clientp);
80 // Stop watching the socket before closing it.
81 for (size_t t = 0; t < arraysize(fetcher->fd_task_maps_); ++t) {
82 const auto fd_task_pair = fetcher->fd_task_maps_[t].find(item);
83 if (fd_task_pair != fetcher->fd_task_maps_[t].end()) {
84 if (!MessageLoop::current()->CancelTask(fd_task_pair->second)) {
85 LOG(WARNING) << "Error canceling the watch task "
86 << fd_task_pair->second << " for "
87 << (t ? "writing" : "reading") << " the fd " << item;
88 }
89 fetcher->fd_task_maps_[t].erase(item);
90 }
91 }
92
93 // Documentation for this callback says to return 0 on success or 1 on error.
94 if (!IGNORE_EINTR(close(item)))
95 return 0;
96 return 1;
97}
98
Alex Deymo33e91e72015-12-01 18:26:08 -030099LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
100 HardwareInterface* hardware)
101 : HttpFetcher(proxy_resolver), hardware_(hardware) {
Alex Deymoc1c17b42015-11-23 03:53:15 -0300102 // Dev users want a longer timeout (180 seconds) because they may
103 // be waiting on the dev server to build an image.
104 if (!hardware_->IsOfficialBuild())
105 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700106 if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
Alex Deymoc1c17b42015-11-23 03:53:15 -0300107 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
108}
109
rspangler@google.com49fdf182009-10-10 00:57:34 +0000110LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800111 LOG_IF(ERROR, transfer_in_progress_)
112 << "Destroying the fetcher while a transfer is in progress.";
Alex Deymo71f67622017-02-03 21:30:24 -0800113 CancelProxyResolution();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000114 CleanUp();
115}
116
Alex Deymof329b932014-10-30 01:37:48 -0700117bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -0700118 curl_proxytype* out_type) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800119 if (base::StartsWith(
120 proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
121 base::StartsWith(
122 proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700123 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
124 return true;
125 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800126 if (base::StartsWith(
127 proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700128 *out_type = CURLPROXY_SOCKS4A;
129 return true;
130 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800131 if (base::StartsWith(
132 proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
133 base::StartsWith(
134 proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700135 *out_type = CURLPROXY_HTTP;
136 return true;
137 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800138 if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700139 // known failure case. don't log.
140 return false;
141 }
142 LOG(INFO) << "Unknown proxy type: " << proxy;
143 return false;
144}
145
Alex Deymof329b932014-10-30 01:37:48 -0700146void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700147 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000148 CHECK(!transfer_in_progress_);
149 url_ = url;
150 curl_multi_handle_ = curl_multi_init();
151 CHECK(curl_multi_handle_);
152
153 curl_handle_ = curl_easy_init();
154 CHECK(curl_handle_);
Alex Deymof2858572016-02-25 11:20:13 -0800155 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000156
Alex Deymo13e95182017-03-16 19:06:13 -0700157 // Tag and untag the socket for network usage stats.
Alex Deymo63cfcf42017-02-23 15:29:47 -0800158 curl_easy_setopt(
159 curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
Alex Deymo13e95182017-03-16 19:06:13 -0700160 curl_easy_setopt(
161 curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
162 curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
Alex Deymo63cfcf42017-02-23 15:29:47 -0800163
Andrew de los Reyes45168102010-11-22 11:13:50 -0800164 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700165 bool is_direct = (GetCurrentProxy() == kNoProxy);
166 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
167 if (is_direct) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800168 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800169 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800170 CHECK_EQ(curl_easy_setopt(
171 curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
172 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800173 // Curl seems to require us to set the protocol
174 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700175 if (GetProxyType(GetCurrentProxy(), &type)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800176 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
177 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800178 }
179 }
180
rspangler@google.com49fdf182009-10-10 00:57:34 +0000181 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000182 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800183 CHECK_EQ(
184 curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
185 CURLE_OK);
186 CHECK_EQ(curl_easy_setopt(
187 curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000188 CURLE_OK);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800189 }
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800190
Alex Deymofdd6dec2016-03-03 22:35:43 -0800191 // Setup extra HTTP headers.
192 if (curl_http_headers_) {
193 curl_slist_free_all(curl_http_headers_);
194 curl_http_headers_ = nullptr;
195 }
196 for (const auto& header : extra_headers_) {
197 // curl_slist_append() copies the string.
198 curl_http_headers_ =
199 curl_slist_append(curl_http_headers_, header.second.c_str());
200 }
201 if (post_data_set_) {
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800202 // Set the Content-Type HTTP header, if one was specifically set.
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800203 if (post_content_type_ != kHttpContentTypeUnspecified) {
Alex Deymofdd6dec2016-03-03 22:35:43 -0800204 const string content_type_attr = base::StringPrintf(
205 "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
206 curl_http_headers_ =
207 curl_slist_append(curl_http_headers_, content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800208 } else {
209 LOG(WARNING) << "no content type set, using libcurl default";
210 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000211 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800212 CHECK_EQ(
213 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
214 CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000215
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800216 if (bytes_downloaded_ > 0 || download_length_) {
217 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000218 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800219 CHECK_GE(resume_offset_, 0);
220
221 // Compute end offset, if one is specified. As per HTTP specification, this
222 // is an inclusive boundary. Make sure it doesn't overflow.
223 size_t end_offset = 0;
224 if (download_length_) {
225 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800226 CHECK_LE((size_t)resume_offset_, end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800227 }
228
229 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700230 string range_str = base::StringPrintf(
231 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
232 if (end_offset)
233 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800234 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
235 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000236 }
237
238 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800239 CHECK_EQ(
240 curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
241 CURLE_OK);
242 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700243
David Zeuthen34135a92013-08-06 11:16:16 -0700244 // If the connection drops under |low_speed_limit_bps_| (10
245 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
246 // 180 on non-official builds), reconnect.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800247 CHECK_EQ(curl_easy_setopt(
248 curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700249 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800250 CHECK_EQ(curl_easy_setopt(
251 curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700252 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800253 CHECK_EQ(curl_easy_setopt(
254 curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700255 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700256
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700257 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700258 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700259 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800260 CHECK_EQ(
261 curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
262 CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700263
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700264 // Lock down the appropriate curl options for HTTP or HTTPS depending on
265 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300266 if (hardware_->IsOfficialBuild()) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800267 if (base::StartsWith(
268 url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800269 SetCurlOptionsForHttp();
Alex Deymo56ccb072016-02-05 00:50:48 -0800270 } else if (base::StartsWith(
271 url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800272 SetCurlOptionsForHttps();
Amin Hassani565331e2019-06-24 14:11:29 -0700273#ifdef __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800274 } else if (base::StartsWith(
275 url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
276 SetCurlOptionsForFile();
Amin Hassani565331e2019-06-24 14:11:29 -0700277#endif // __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800278 } else {
279 LOG(ERROR) << "Received invalid URI: " << url_;
280 // Lock down to no protocol supported for the transfer.
281 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
282 }
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800283 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700284 LOG(INFO) << "Not setting http(s) curl options because we are "
285 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700286 }
287
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000288 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000289 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000290}
291
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800292// Lock down only the protocol in case of HTTP.
293void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
294 LOG(INFO) << "Setting up curl options for HTTP";
295 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
296 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800297 CHECK_EQ(
298 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
299 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800300}
301
302// Security lock-down in official builds: makes sure that peer certificate
303// verification is enabled, restricts the set of trusted certificates,
304// restricts protocols to HTTPS, restricts ciphers to HIGH.
305void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
306 LOG(INFO) << "Setting up curl options for HTTPS";
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800307 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
308 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
Alex Khouderchah84634dc2019-04-04 09:25:39 -0700309 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAINFO, nullptr), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800310 CHECK_EQ(curl_easy_setopt(
311 curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800312 CURLE_OK);
313 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
314 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800315 CHECK_EQ(
316 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
317 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800318 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
319 CURLE_OK);
Alex Deymo33e91e72015-12-01 18:26:08 -0300320 if (server_to_check_ != ServerToCheck::kNone) {
321 CHECK_EQ(
322 curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
323 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800324 CHECK_EQ(curl_easy_setopt(curl_handle_,
325 CURLOPT_SSL_CTX_FUNCTION,
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800326 CertificateChecker::ProcessSSLContext),
327 CURLE_OK);
328 }
329}
330
Alex Deymo56ccb072016-02-05 00:50:48 -0800331// Lock down only the protocol in case of a local file.
332void LibcurlHttpFetcher::SetCurlOptionsForFile() {
333 LOG(INFO) << "Setting up curl options for FILE";
334 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
335 CURLE_OK);
336 CHECK_EQ(
337 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
338 CURLE_OK);
339}
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800340
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000341// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700342void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800343 CHECK(!transfer_in_progress_);
344 url_ = url;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800345 auto closure =
346 base::Bind(&LibcurlHttpFetcher::ProxiesResolved, base::Unretained(this));
Daniel Erate5f6f252017-04-20 12:09:58 -0600347 ResolveProxiesForUrl(url_, closure);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800348}
349
350void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000351 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000352 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700353 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800354 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700355 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800356 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700357 sent_byte_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800358
359 // If we are paused, we delay these two operations until Unpause is called.
360 if (transfer_paused_) {
361 restart_transfer_on_unpause_ = true;
362 return;
363 }
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800364 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700365 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000366}
367
Darin Petkov9ce452b2010-11-17 14:33:28 -0800368void LibcurlHttpFetcher::ForceTransferTermination() {
Alex Deymo71f67622017-02-03 21:30:24 -0800369 CancelProxyResolution();
Darin Petkov9ce452b2010-11-17 14:33:28 -0800370 CleanUp();
371 if (delegate_) {
372 // Note that after the callback returns this object may be destroyed.
373 delegate_->TransferTerminated(this);
374 }
375}
376
rspangler@google.com49fdf182009-10-10 00:57:34 +0000377void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800378 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700379 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800380 } else {
381 ForceTransferTermination();
382 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000383}
384
Alex Deymofdd6dec2016-03-03 22:35:43 -0800385void LibcurlHttpFetcher::SetHeader(const string& header_name,
386 const string& header_value) {
387 string header_line = header_name + ": " + header_value;
388 // Avoid the space if no data on the right side of the semicolon.
389 if (header_value.empty())
390 header_line = header_name + ":";
391 TEST_AND_RETURN(header_line.find('\n') == string::npos);
392 TEST_AND_RETURN(header_name.find(':') == string::npos);
393 extra_headers_[base::ToLowerASCII(header_name)] = header_line;
394}
395
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700396// Inputs: header_name, header_value
397// Example:
398// extra_headers_ = { {"foo":"foo: 123"}, {"bar":"bar:"} }
399// string tmp = "gibberish";
400// Case 1:
401// GetHeader("foo", &tmp) -> tmp = "123", return true.
402// Case 2:
403// GetHeader("bar", &tmp) -> tmp = "", return true.
404// Case 3:
405// GetHeader("moo", &tmp) -> tmp = "", return false.
406bool LibcurlHttpFetcher::GetHeader(const string& header_name,
407 string* header_value) const {
408 // Initially clear |header_value| to handle both success and failures without
409 // leaving |header_value| in a unclear state.
410 header_value->clear();
411 auto header_key = base::ToLowerASCII(header_name);
412 auto header_line_itr = extra_headers_.find(header_key);
413 // If the |header_name| was never set, indicate so by returning false.
414 if (header_line_itr == extra_headers_.end())
415 return false;
416 // From |SetHeader()| the check for |header_name| to not include ":" is
417 // verified, so finding the first index of ":" is a safe operation.
418 auto header_line = header_line_itr->second;
419 *header_value = header_line.substr(header_line.find(':') + 1);
420 // The following is neccessary to remove the leading ' ' before the header
421 // value that was place only if |header_value| passed to |SetHeader()| was
422 // a non-empty string.
423 header_value->erase(0, 1);
424 return true;
425}
426
Andrew de los Reyescb319332010-07-19 10:55:01 -0700427void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000428 CHECK(transfer_in_progress_);
429 int running_handles = 0;
430 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
431
432 // libcurl may request that we immediately call curl_multi_perform after it
433 // returns, so we do. libcurl promises that curl_multi_perform will not block.
434 while (CURLM_CALL_MULTI_PERFORM == retcode) {
435 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700436 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800437 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700438 return;
439 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000440 }
Alex Deymof2858572016-02-25 11:20:13 -0800441
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700442 // When retcode is not |CURLM_OK| at this point, libcurl has an internal error
443 // that it is less likely to recover from (libcurl bug, out-of-memory, etc.).
444 // In case of an update check, we send UMA metrics and log the error.
445 if (is_update_check_ &&
446 (retcode == CURLM_OUT_OF_MEMORY || retcode == CURLM_INTERNAL_ERROR)) {
447 delegate_->ReportUpdateCheckMetrics(
448 metrics::CheckResult::kUnset,
449 metrics::CheckReaction::kUnset,
450 metrics::DownloadErrorCode::kInternalError);
Xiaochu Liu1329fd82019-05-16 17:27:34 -0700451 // According to https://curl.haxx.se/libcurl/c/libcurl-errors.html:
452 // CURLM_INTERNAL_ERROR and CURLM_OUT_OF_MEMORY are two libcurl error codes
453 // that caller has no way to recover on its own. Thus, we exit and let the
454 // system respawn update_engine to start from a fresh state and recover.
455 LOG(FATAL) << "curl_multi_perform is in an unrecoverable error condition: "
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700456 << retcode;
457 } else if (retcode != CURLM_OK) {
458 LOG(ERROR) << "curl_multi_perform returns error: " << retcode;
459 }
460
Alex Deymof2858572016-02-25 11:20:13 -0800461 // If the transfer completes while paused, we should ignore the failure once
462 // the fetcher is unpaused.
463 if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
464 LOG(INFO) << "Connection closed while paused, ignoring failure.";
465 ignore_failure_ = true;
466 }
467
468 if (running_handles != 0 || transfer_paused_) {
469 // There's either more work to do or we are paused, so we just keep the
470 // file descriptors to watch up to date and exit, until we are done with the
471 // work and we are not paused.
472 SetupMessageLoopSources();
473 return;
474 }
475
476 // At this point, the transfer was completed in some way (error, connection
477 // closed or download finished).
478
479 GetHttpResponseCode();
480 if (http_response_code_) {
481 LOG(INFO) << "HTTP response code: " << http_response_code_;
482 no_network_retry_count_ = 0;
483 } else {
484 LOG(ERROR) << "Unable to get http response code.";
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700485 LogCurlHandleInfo();
Alex Deymof2858572016-02-25 11:20:13 -0800486 }
487
488 // we're done!
489 CleanUp();
490
491 // TODO(petkov): This temporary code tries to deal with the case where the
492 // update engine performs an update check while the network is not ready
493 // (e.g., right after resume). Longer term, we should check if the network
494 // is online/offline and return an appropriate error code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800495 if (!sent_byte_ && http_response_code_ == 0 &&
Alex Deymof2858572016-02-25 11:20:13 -0800496 no_network_retry_count_ < no_network_max_retries_) {
497 no_network_retry_count_++;
Alex Deymob20de692017-02-05 07:47:37 +0000498 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymof2858572016-02-25 11:20:13 -0800499 FROM_HERE,
500 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
501 base::Unretained(this)),
502 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
503 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
504 } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
505 IsHttpResponseError()) {
506 // The transfer completed w/ error and we didn't get any bytes.
507 // If we have another proxy to try, try that.
508 //
509 // TODO(garnold) in fact there are two separate cases here: one case is an
510 // other-than-success return code (including no return code) and no
511 // received bytes, which is necessary due to the way callbacks are
512 // currently processing error conditions; the second is an explicit HTTP
513 // error code, where some data may have been received (as in the case of a
514 // semi-successful multi-chunk fetch). This is a confusing behavior and
515 // should be unified into a complete, coherent interface.
516 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
517 << "), " << bytes_downloaded_ << " bytes downloaded";
518
519 PopProxy(); // Delete the proxy we just gave up on.
520
521 if (HasProxy()) {
522 // We have another proxy. Retry immediately.
523 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymob20de692017-02-05 07:47:37 +0000524 retry_task_id_ = MessageLoop::current()->PostTask(
Alex Deymof2858572016-02-25 11:20:13 -0800525 FROM_HERE,
526 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
527 base::Unretained(this)));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700528 } else {
Alex Deymof2858572016-02-25 11:20:13 -0800529 // Out of proxies. Give up.
530 LOG(INFO) << "No further proxies, indicating transfer complete";
531 if (delegate_)
532 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700533 return;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700534 }
Alex Deymof2858572016-02-25 11:20:13 -0800535 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
536 if (!ignore_failure_)
537 retry_count_++;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800538 LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
539 << " of " << transfer_size_ << " bytes. "
Alex Deymof2858572016-02-25 11:20:13 -0800540 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
541 << "after " << retry_count_ << " attempt(s)";
Darin Petkov192ced42010-07-23 16:20:24 -0700542
Alex Deymof2858572016-02-25 11:20:13 -0800543 if (retry_count_ > max_retry_count_) {
544 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
545 if (delegate_)
546 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700547 return;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000548 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700549 // Need to restart transfer
550 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymob20de692017-02-05 07:47:37 +0000551 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymo021a45e2016-03-15 13:12:05 -0700552 FROM_HERE,
553 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
554 base::Unretained(this)),
555 TimeDelta::FromSeconds(retry_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000556 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800557 LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
558 << bytes_downloaded_ << " bytes downloaded";
Alex Deymof2858572016-02-25 11:20:13 -0800559 if (delegate_) {
560 bool success = IsHttpResponseSuccess();
561 delegate_->TransferComplete(this, success);
562 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700563 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000564 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700565 // If we reach this point is because TransferComplete() was not called in any
566 // of the previous branches. The delegate is allowed to destroy the object
567 // once TransferComplete is called so this would be illegal.
Alex Deymof2858572016-02-25 11:20:13 -0800568 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000569}
570
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800571size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800572 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700573 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800574 const size_t payload_size = size * nmemb;
575
576 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800577 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800578 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
579 << ") or no payload (" << payload_size << "), nothing to do";
580 return 0;
581 }
582
583 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000584 {
585 double transfer_size_double;
586 CHECK_EQ(curl_easy_getinfo(curl_handle_,
587 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800588 &transfer_size_double),
589 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000590 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
591 if (new_transfer_size > 0) {
592 transfer_size_ = resume_offset_ + new_transfer_size;
593 }
594 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800595 bytes_downloaded_ += payload_size;
Tao Bao028ea412018-12-27 14:12:14 -0800596 if (delegate_) {
597 in_write_callback_ = true;
598 auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
599 in_write_callback_ = false;
600 if (should_terminate) {
601 LOG(INFO) << "Requesting libcurl to terminate transfer.";
602 // Returning an amount that differs from the received size signals an
603 // error condition to libcurl, which will cause the transfer to be
604 // aborted.
605 return 0;
606 }
607 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800608 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000609}
610
611void LibcurlHttpFetcher::Pause() {
Alex Deymof2858572016-02-25 11:20:13 -0800612 if (transfer_paused_) {
613 LOG(ERROR) << "Fetcher already paused.";
614 return;
615 }
616 transfer_paused_ = true;
617 if (!transfer_in_progress_) {
618 // If pause before we started a connection, we don't need to notify curl
619 // about that, we will simply not start the connection later.
620 return;
621 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000622 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000623 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000624}
625
626void LibcurlHttpFetcher::Unpause() {
Alex Deymof2858572016-02-25 11:20:13 -0800627 if (!transfer_paused_) {
628 LOG(ERROR) << "Resume attempted when fetcher not paused.";
629 return;
630 }
631 transfer_paused_ = false;
632 if (restart_transfer_on_unpause_) {
633 restart_transfer_on_unpause_ = false;
634 ResumeTransfer(url_);
635 CurlPerformOnce();
636 return;
637 }
638 if (!transfer_in_progress_) {
639 // If resumed before starting the connection, there's no need to notify
640 // anybody. We will simply start the connection once it is time.
641 return;
642 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000643 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000644 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
Alex Deymof2858572016-02-25 11:20:13 -0800645 // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
646 // now to let the connection continue, otherwise it would be called by the
647 // TimeoutCallback but with a delay.
648 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000649}
650
Alex Deymo29b81532015-07-09 11:51:49 -0700651// This method sets up callbacks with the MessageLoop.
652void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000653 fd_set fd_read;
654 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700655 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000656
657 FD_ZERO(&fd_read);
658 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700659 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000660
661 int fd_max = 0;
662
663 // Ask libcurl for the set of file descriptors we should track on its
664 // behalf.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800665 CHECK_EQ(curl_multi_fdset(
666 curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
667 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000668
669 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700670 // the highest one we're tracking, whichever is larger.
Alex Deymo29b81532015-07-09 11:51:49 -0700671 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
672 if (!fd_task_maps_[t].empty())
673 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700674 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000675
Darin Petkov60e14152010-10-27 16:57:04 -0700676 // For each fd, if we're not tracking it, track it. If we are tracking it, but
677 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700678 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700679 // there are read/write fds that we're tracking.
680 for (int fd = 0; fd <= fd_max; ++fd) {
681 // Note that fd_exc is unused in the current version of libcurl so is_exc
682 // should always be false.
683 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
684 bool must_track[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800685 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
686 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
Darin Petkov60e14152010-10-27 16:57:04 -0700687 };
Alex Deymo29b81532015-07-09 11:51:49 -0700688 MessageLoop::WatchMode watch_modes[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800689 MessageLoop::WatchMode::kWatchRead,
690 MessageLoop::WatchMode::kWatchWrite,
Alex Deymo29b81532015-07-09 11:51:49 -0700691 };
Darin Petkov60e14152010-10-27 16:57:04 -0700692
Alex Deymo29b81532015-07-09 11:51:49 -0700693 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
694 auto fd_task_it = fd_task_maps_[t].find(fd);
695 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700696
697 if (!must_track[t]) {
698 // If we have an outstanding io_channel, remove it.
699 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700700 MessageLoop::current()->CancelTask(fd_task_it->second);
701 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700702 }
703 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.
Alex Deymo29b81532015-07-09 11:51:49 -0700711 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
712 FROM_HERE,
713 fd,
714 watch_modes[t],
715 true, // persistent
716 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
717 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700718
Darin Petkov60e14152010-10-27 16:57:04 -0700719 static int io_counter = 0;
720 io_counter++;
721 if (io_counter % 50 == 0) {
722 LOG(INFO) << "io_counter = " << io_counter;
723 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700724 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000725 }
726
Darin Petkovb83371f2010-08-17 09:34:49 -0700727 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700728 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Alex Deymof2858572016-02-25 11:20:13 -0800729 VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700730 timeout_id_ = MessageLoop::current()->PostDelayedTask(
731 FROM_HERE,
732 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
733 base::Unretained(this)),
734 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000735 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000736}
737
Alex Deymo60ca1a72015-06-18 18:19:15 -0700738void LibcurlHttpFetcher::RetryTimeoutCallback() {
Alex Deymob20de692017-02-05 07:47:37 +0000739 retry_task_id_ = MessageLoop::kTaskIdNull;
Alex Deymof2858572016-02-25 11:20:13 -0800740 if (transfer_paused_) {
741 restart_transfer_on_unpause_ = true;
742 return;
743 }
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700744 ResumeTransfer(url_);
745 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700746}
747
Alex Deymo60ca1a72015-06-18 18:19:15 -0700748void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700749 // We always re-schedule the callback, even if we don't want to be called
750 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700751 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700752 timeout_id_ = MessageLoop::current()->PostDelayedTask(
753 FROM_HERE,
754 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
755 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700756
757 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
758 // first, since it could be canceled by this call.
759 if (transfer_in_progress_)
760 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000761}
762
763void LibcurlHttpFetcher::CleanUp() {
Alex Deymob20de692017-02-05 07:47:37 +0000764 MessageLoop::current()->CancelTask(retry_task_id_);
765 retry_task_id_ = MessageLoop::kTaskIdNull;
766
Alex Deymo60ca1a72015-06-18 18:19:15 -0700767 MessageLoop::current()->CancelTask(timeout_id_);
768 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000769
Alex Deymo29b81532015-07-09 11:51:49 -0700770 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
771 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
772 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800773 LOG(WARNING) << "Error canceling the watch task " << fd_taks_pair.second
774 << " for " << (t ? "writing" : "reading") << " the fd "
Alex Deymo29b81532015-07-09 11:51:49 -0700775 << fd_taks_pair.first;
776 }
Darin Petkov60e14152010-10-27 16:57:04 -0700777 }
Alex Deymo29b81532015-07-09 11:51:49 -0700778 fd_task_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.
Alex Deymo56ccb072016-02-05 00:50:48 -0800804 if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
805 // 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
816void LibcurlHttpFetcher::LogCurlHandleInfo() {
817 while (true) {
818 // Repeated calls to |curl_multi_info_read| will return a new struct each
819 // time, until a NULL is returned as a signal that there is no more to get
820 // at this point.
821 int msgs_in_queue;
822 CURLMsg* curl_msg =
823 curl_multi_info_read(curl_multi_handle_, &msgs_in_queue);
824 if (curl_msg == nullptr)
825 break;
826 // When |curl_msg| is |CURLMSG_DONE|, a transfer of an easy handle is done,
827 // and then data contains the return code for this transfer.
828 if (curl_msg->msg == CURLMSG_DONE) {
829 // Make sure |curl_multi_handle_| has one and only one easy handle
830 // |curl_handle_|.
831 CHECK_EQ(curl_handle_, curl_msg->easy_handle);
832 // Transfer return code reference:
833 // https://curl.haxx.se/libcurl/c/libcurl-errors.html
834 LOG(ERROR) << "Return code for the transfer: " << curl_msg->data.result;
835 }
836 }
837
838 // Gets connection error if exists.
839 long connect_error = 0; // NOLINT(runtime/int) - curl needs long.
840 CURLcode res =
841 curl_easy_getinfo(curl_handle_, CURLINFO_OS_ERRNO, &connect_error);
842 if (res == CURLE_OK && connect_error) {
843 LOG(ERROR) << "Connect error code from the OS: " << connect_error;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700844 }
845}
846
rspangler@google.com49fdf182009-10-10 00:57:34 +0000847} // namespace chromeos_update_engine