blob: 7c53a2d964955ef9104c4d691995dc56e4fb6fc1 [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>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070034
Alex Deymo63cfcf42017-02-23 15:29:47 -080035#ifdef __ANDROID__
36#include <cutils/qtaguid.h>
Alex Deymoeb256552017-03-21 22:52:54 -070037#include <private/android_filesystem_config.h>
Alex Deymo63cfcf42017-02-23 15:29:47 -080038#endif // __ANDROID__
39
Alex Deymo14c0da82016-07-20 16:45:45 -070040#include "update_engine/certificate_checker.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/hardware_interface.h"
42#include "update_engine/common/platform_constants.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000043
Alex Deymo60ca1a72015-06-18 18:19:15 -070044using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070045using brillo::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070046using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070047using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000048
49// This is a concrete implementation of HttpFetcher that uses libcurl to do the
50// http work.
51
52namespace chromeos_update_engine {
53
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070054namespace {
Alex Deymo63cfcf42017-02-23 15:29:47 -080055
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080056const int kNoNetworkRetrySeconds = 10;
Alex Deymo63cfcf42017-02-23 15:29:47 -080057
Alex Deymo63cfcf42017-02-23 15:29:47 -080058// libcurl's CURLOPT_SOCKOPTFUNCTION callback function. Called after the socket
59// is created but before it is connected. This callback tags the created socket
60// so the network usage can be tracked in Android.
61int LibcurlSockoptCallback(void* /* clientp */,
62 curl_socket_t curlfd,
63 curlsocktype /* purpose */) {
64#ifdef __ANDROID__
Alex Deymo558fe6a2017-05-19 13:16:20 -070065 // Socket tag used by all network sockets. See qtaguid kernel module for
66 // stats.
67 const int kUpdateEngineSocketTag = 0x55417243; // "CrAU" in little-endian.
Alex Deymoeb256552017-03-21 22:52:54 -070068 qtaguid_tagSocket(curlfd, kUpdateEngineSocketTag, AID_OTA_UPDATE);
Alex Deymo63cfcf42017-02-23 15:29:47 -080069#endif // __ANDROID__
70 return CURL_SOCKOPT_OK;
71}
72
Alex Vakulenkod2779df2014-06-16 13:19:00 -070073} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070074
Alex Deymo13e95182017-03-16 19:06:13 -070075// static
76int LibcurlHttpFetcher::LibcurlCloseSocketCallback(void* clientp,
77 curl_socket_t item) {
78#ifdef __ANDROID__
79 qtaguid_untagSocket(item);
80#endif // __ANDROID__
Tianjie55abd3c2020-06-19 00:22:59 -070081
Alex Deymo13e95182017-03-16 19:06:13 -070082 LibcurlHttpFetcher* fetcher = static_cast<LibcurlHttpFetcher*>(clientp);
83 // Stop watching the socket before closing it.
Tianjie55abd3c2020-06-19 00:22:59 -070084#ifdef __ANDROID__
Alex Deymo13e95182017-03-16 19:06:13 -070085 for (size_t t = 0; t < arraysize(fetcher->fd_task_maps_); ++t) {
86 const auto fd_task_pair = fetcher->fd_task_maps_[t].find(item);
87 if (fd_task_pair != fetcher->fd_task_maps_[t].end()) {
88 if (!MessageLoop::current()->CancelTask(fd_task_pair->second)) {
89 LOG(WARNING) << "Error canceling the watch task "
90 << fd_task_pair->second << " for "
91 << (t ? "writing" : "reading") << " the fd " << item;
92 }
93 fetcher->fd_task_maps_[t].erase(item);
94 }
95 }
Tianjie55abd3c2020-06-19 00:22:59 -070096#else
hscham00b6aa22020-02-20 12:32:06 +090097 for (size_t t = 0; t < base::size(fetcher->fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +090098 fetcher->fd_controller_maps_[t].erase(item);
Alex Deymo13e95182017-03-16 19:06:13 -070099 }
Tianjie55abd3c2020-06-19 00:22:59 -0700100#endif // __ANDROID__
Alex Deymo13e95182017-03-16 19:06:13 -0700101
102 // Documentation for this callback says to return 0 on success or 1 on error.
103 if (!IGNORE_EINTR(close(item)))
104 return 0;
105 return 1;
106}
107
Alex Deymo33e91e72015-12-01 18:26:08 -0300108LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
109 HardwareInterface* hardware)
110 : HttpFetcher(proxy_resolver), hardware_(hardware) {
Alex Deymoc1c17b42015-11-23 03:53:15 -0300111 // Dev users want a longer timeout (180 seconds) because they may
112 // be waiting on the dev server to build an image.
113 if (!hardware_->IsOfficialBuild())
114 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700115 if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
Alex Deymoc1c17b42015-11-23 03:53:15 -0300116 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
117}
118
rspangler@google.com49fdf182009-10-10 00:57:34 +0000119LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800120 LOG_IF(ERROR, transfer_in_progress_)
121 << "Destroying the fetcher while a transfer is in progress.";
Alex Deymo71f67622017-02-03 21:30:24 -0800122 CancelProxyResolution();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000123 CleanUp();
124}
125
Alex Deymof329b932014-10-30 01:37:48 -0700126bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -0700127 curl_proxytype* out_type) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800128 if (base::StartsWith(
129 proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
130 base::StartsWith(
131 proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700132 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
133 return true;
134 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800135 if (base::StartsWith(
136 proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700137 *out_type = CURLPROXY_SOCKS4A;
138 return true;
139 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800140 if (base::StartsWith(
141 proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
142 base::StartsWith(
143 proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700144 *out_type = CURLPROXY_HTTP;
145 return true;
146 }
Alex Deymo56ccb072016-02-05 00:50:48 -0800147 if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -0700148 // known failure case. don't log.
149 return false;
150 }
151 LOG(INFO) << "Unknown proxy type: " << proxy;
152 return false;
153}
154
Alex Deymof329b932014-10-30 01:37:48 -0700155void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700156 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000157 CHECK(!transfer_in_progress_);
158 url_ = url;
159 curl_multi_handle_ = curl_multi_init();
160 CHECK(curl_multi_handle_);
161
162 curl_handle_ = curl_easy_init();
163 CHECK(curl_handle_);
Alex Deymof2858572016-02-25 11:20:13 -0800164 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000165
Alex Deymo13e95182017-03-16 19:06:13 -0700166 // Tag and untag the socket for network usage stats.
Alex Deymo63cfcf42017-02-23 15:29:47 -0800167 curl_easy_setopt(
168 curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
Alex Deymo13e95182017-03-16 19:06:13 -0700169 curl_easy_setopt(
170 curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
171 curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
Alex Deymo63cfcf42017-02-23 15:29:47 -0800172
Andrew de los Reyes45168102010-11-22 11:13:50 -0800173 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700174 bool is_direct = (GetCurrentProxy() == kNoProxy);
175 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
176 if (is_direct) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800177 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800178 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800179 CHECK_EQ(curl_easy_setopt(
180 curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
181 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800182 // Curl seems to require us to set the protocol
183 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700184 if (GetProxyType(GetCurrentProxy(), &type)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800185 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
186 CURLE_OK);
Andrew de los Reyes45168102010-11-22 11:13:50 -0800187 }
188 }
189
rspangler@google.com49fdf182009-10-10 00:57:34 +0000190 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000191 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800192 CHECK_EQ(
193 curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
194 CURLE_OK);
195 CHECK_EQ(curl_easy_setopt(
196 curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000197 CURLE_OK);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800198 }
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800199
Alex Deymofdd6dec2016-03-03 22:35:43 -0800200 // Setup extra HTTP headers.
201 if (curl_http_headers_) {
202 curl_slist_free_all(curl_http_headers_);
203 curl_http_headers_ = nullptr;
204 }
205 for (const auto& header : extra_headers_) {
206 // curl_slist_append() copies the string.
207 curl_http_headers_ =
208 curl_slist_append(curl_http_headers_, header.second.c_str());
209 }
210 if (post_data_set_) {
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800211 // Set the Content-Type HTTP header, if one was specifically set.
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800212 if (post_content_type_ != kHttpContentTypeUnspecified) {
Alex Deymofdd6dec2016-03-03 22:35:43 -0800213 const string content_type_attr = base::StringPrintf(
214 "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
215 curl_http_headers_ =
216 curl_slist_append(curl_http_headers_, content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800217 } else {
218 LOG(WARNING) << "no content type set, using libcurl default";
219 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000220 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800221 CHECK_EQ(
222 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
223 CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000224
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800225 if (bytes_downloaded_ > 0 || download_length_) {
226 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000227 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800228 CHECK_GE(resume_offset_, 0);
229
230 // Compute end offset, if one is specified. As per HTTP specification, this
231 // is an inclusive boundary. Make sure it doesn't overflow.
232 size_t end_offset = 0;
233 if (download_length_) {
234 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800235 CHECK_LE((size_t)resume_offset_, end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800236 }
237
238 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700239 string range_str = base::StringPrintf(
240 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
241 if (end_offset)
242 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800243 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
244 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000245 }
246
247 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800248 CHECK_EQ(
249 curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
250 CURLE_OK);
251 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700252
David Zeuthen34135a92013-08-06 11:16:16 -0700253 // If the connection drops under |low_speed_limit_bps_| (10
254 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
255 // 180 on non-official builds), reconnect.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800256 CHECK_EQ(curl_easy_setopt(
257 curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700258 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800259 CHECK_EQ(curl_easy_setopt(
260 curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700261 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800262 CHECK_EQ(curl_easy_setopt(
263 curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700264 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700265
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700266 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700267 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700268 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800269 CHECK_EQ(
270 curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
271 CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700272
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700273 // Lock down the appropriate curl options for HTTP or HTTPS depending on
274 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300275 if (hardware_->IsOfficialBuild()) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800276 if (base::StartsWith(
277 url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800278 SetCurlOptionsForHttp();
Alex Deymo56ccb072016-02-05 00:50:48 -0800279 } else if (base::StartsWith(
280 url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800281 SetCurlOptionsForHttps();
Amin Hassani565331e2019-06-24 14:11:29 -0700282#ifdef __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800283 } else if (base::StartsWith(
284 url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
285 SetCurlOptionsForFile();
Amin Hassani565331e2019-06-24 14:11:29 -0700286#endif // __ANDROID__
Alex Deymo56ccb072016-02-05 00:50:48 -0800287 } else {
288 LOG(ERROR) << "Received invalid URI: " << url_;
289 // Lock down to no protocol supported for the transfer.
290 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
291 }
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800292 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700293 LOG(INFO) << "Not setting http(s) curl options because we are "
294 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700295 }
296
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000297 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000298 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000299}
300
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800301// Lock down only the protocol in case of HTTP.
302void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
303 LOG(INFO) << "Setting up curl options for HTTP";
304 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
305 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800306 CHECK_EQ(
307 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
308 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800309}
310
311// Security lock-down in official builds: makes sure that peer certificate
312// verification is enabled, restricts the set of trusted certificates,
313// restricts protocols to HTTPS, restricts ciphers to HIGH.
314void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
315 LOG(INFO) << "Setting up curl options for HTTPS";
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800316 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
317 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
Alex Khouderchah84634dc2019-04-04 09:25:39 -0700318 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAINFO, nullptr), CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800319 CHECK_EQ(curl_easy_setopt(
320 curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800321 CURLE_OK);
322 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
323 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800324 CHECK_EQ(
325 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
326 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800327 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
328 CURLE_OK);
Alex Deymo33e91e72015-12-01 18:26:08 -0300329 if (server_to_check_ != ServerToCheck::kNone) {
330 CHECK_EQ(
331 curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
332 CURLE_OK);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800333 CHECK_EQ(curl_easy_setopt(curl_handle_,
334 CURLOPT_SSL_CTX_FUNCTION,
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800335 CertificateChecker::ProcessSSLContext),
336 CURLE_OK);
337 }
338}
339
Alex Deymo56ccb072016-02-05 00:50:48 -0800340// Lock down only the protocol in case of a local file.
341void LibcurlHttpFetcher::SetCurlOptionsForFile() {
342 LOG(INFO) << "Setting up curl options for FILE";
343 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
344 CURLE_OK);
345 CHECK_EQ(
346 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
347 CURLE_OK);
348}
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800349
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000350// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700351void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800352 CHECK(!transfer_in_progress_);
353 url_ = url;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800354 auto closure =
355 base::Bind(&LibcurlHttpFetcher::ProxiesResolved, base::Unretained(this));
Daniel Erate5f6f252017-04-20 12:09:58 -0600356 ResolveProxiesForUrl(url_, closure);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800357}
358
359void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000360 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000361 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700362 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800363 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700364 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800365 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700366 sent_byte_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800367
368 // If we are paused, we delay these two operations until Unpause is called.
369 if (transfer_paused_) {
370 restart_transfer_on_unpause_ = true;
371 return;
372 }
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800373 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700374 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000375}
376
Darin Petkov9ce452b2010-11-17 14:33:28 -0800377void LibcurlHttpFetcher::ForceTransferTermination() {
Alex Deymo71f67622017-02-03 21:30:24 -0800378 CancelProxyResolution();
Darin Petkov9ce452b2010-11-17 14:33:28 -0800379 CleanUp();
380 if (delegate_) {
381 // Note that after the callback returns this object may be destroyed.
382 delegate_->TransferTerminated(this);
383 }
384}
385
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800387 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700388 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800389 } else {
390 ForceTransferTermination();
391 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000392}
393
Alex Deymofdd6dec2016-03-03 22:35:43 -0800394void LibcurlHttpFetcher::SetHeader(const string& header_name,
395 const string& header_value) {
396 string header_line = header_name + ": " + header_value;
397 // Avoid the space if no data on the right side of the semicolon.
398 if (header_value.empty())
399 header_line = header_name + ":";
400 TEST_AND_RETURN(header_line.find('\n') == string::npos);
401 TEST_AND_RETURN(header_name.find(':') == string::npos);
402 extra_headers_[base::ToLowerASCII(header_name)] = header_line;
403}
404
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700405// Inputs: header_name, header_value
406// Example:
407// extra_headers_ = { {"foo":"foo: 123"}, {"bar":"bar:"} }
408// string tmp = "gibberish";
409// Case 1:
410// GetHeader("foo", &tmp) -> tmp = "123", return true.
411// Case 2:
412// GetHeader("bar", &tmp) -> tmp = "", return true.
413// Case 3:
414// GetHeader("moo", &tmp) -> tmp = "", return false.
415bool LibcurlHttpFetcher::GetHeader(const string& header_name,
416 string* header_value) const {
417 // Initially clear |header_value| to handle both success and failures without
418 // leaving |header_value| in a unclear state.
419 header_value->clear();
420 auto header_key = base::ToLowerASCII(header_name);
421 auto header_line_itr = extra_headers_.find(header_key);
422 // If the |header_name| was never set, indicate so by returning false.
423 if (header_line_itr == extra_headers_.end())
424 return false;
425 // From |SetHeader()| the check for |header_name| to not include ":" is
426 // verified, so finding the first index of ":" is a safe operation.
427 auto header_line = header_line_itr->second;
428 *header_value = header_line.substr(header_line.find(':') + 1);
429 // The following is neccessary to remove the leading ' ' before the header
430 // value that was place only if |header_value| passed to |SetHeader()| was
431 // a non-empty string.
432 header_value->erase(0, 1);
433 return true;
434}
435
Andrew de los Reyescb319332010-07-19 10:55:01 -0700436void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000437 CHECK(transfer_in_progress_);
438 int running_handles = 0;
439 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
440
441 // libcurl may request that we immediately call curl_multi_perform after it
442 // returns, so we do. libcurl promises that curl_multi_perform will not block.
443 while (CURLM_CALL_MULTI_PERFORM == retcode) {
444 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700445 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800446 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700447 return;
448 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449 }
Alex Deymof2858572016-02-25 11:20:13 -0800450
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700451 // When retcode is not |CURLM_OK| at this point, libcurl has an internal error
452 // that it is less likely to recover from (libcurl bug, out-of-memory, etc.).
453 // In case of an update check, we send UMA metrics and log the error.
454 if (is_update_check_ &&
455 (retcode == CURLM_OUT_OF_MEMORY || retcode == CURLM_INTERNAL_ERROR)) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700456 auxiliary_error_code_ = ErrorCode::kInternalLibCurlError;
Xiaochu Liua4fa6602019-08-05 17:06:35 +0000457 LOG(ERROR) << "curl_multi_perform is in an unrecoverable error condition: "
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700458 << retcode;
459 } else if (retcode != CURLM_OK) {
460 LOG(ERROR) << "curl_multi_perform returns error: " << retcode;
461 }
462
Alex Deymof2858572016-02-25 11:20:13 -0800463 // If the transfer completes while paused, we should ignore the failure once
464 // the fetcher is unpaused.
465 if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
466 LOG(INFO) << "Connection closed while paused, ignoring failure.";
467 ignore_failure_ = true;
468 }
469
470 if (running_handles != 0 || transfer_paused_) {
471 // There's either more work to do or we are paused, so we just keep the
472 // file descriptors to watch up to date and exit, until we are done with the
473 // work and we are not paused.
474 SetupMessageLoopSources();
475 return;
476 }
477
478 // At this point, the transfer was completed in some way (error, connection
479 // closed or download finished).
480
481 GetHttpResponseCode();
482 if (http_response_code_) {
483 LOG(INFO) << "HTTP response code: " << http_response_code_;
484 no_network_retry_count_ = 0;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700485 unresolved_host_state_machine_.UpdateState(false);
Alex Deymof2858572016-02-25 11:20:13 -0800486 } else {
487 LOG(ERROR) << "Unable to get http response code.";
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700488 CURLcode curl_code = GetCurlCode();
489 LOG(ERROR) << "Return code for the transfer: " << curl_code;
490 if (curl_code == CURLE_COULDNT_RESOLVE_HOST) {
491 LOG(ERROR) << "libcurl can not resolve host.";
492 unresolved_host_state_machine_.UpdateState(true);
Amin Hassanid3d84212019-08-17 00:27:44 -0700493 auxiliary_error_code_ = ErrorCode::kUnresolvedHostError;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700494 }
Alex Deymof2858572016-02-25 11:20:13 -0800495 }
496
497 // we're done!
498 CleanUp();
499
Amin Hassanid3d84212019-08-17 00:27:44 -0700500 if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700501 UnresolvedHostStateMachine::State::kRetry) {
502 // Based on
503 // https://curl.haxx.se/docs/todo.html#updated_DNS_server_while_running,
504 // update_engine process should call res_init() and unconditionally retry.
505 res_init();
506 no_network_max_retries_++;
507 LOG(INFO) << "Will retry after reloading resolv.conf because last attempt "
508 "failed to resolve host.";
Amin Hassanid3d84212019-08-17 00:27:44 -0700509 } else if (unresolved_host_state_machine_.GetState() ==
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700510 UnresolvedHostStateMachine::State::kRetriedSuccess) {
Amin Hassanid3d84212019-08-17 00:27:44 -0700511 auxiliary_error_code_ = ErrorCode::kUnresolvedHostRecovered;
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700512 }
513
Alex Deymof2858572016-02-25 11:20:13 -0800514 // TODO(petkov): This temporary code tries to deal with the case where the
515 // update engine performs an update check while the network is not ready
516 // (e.g., right after resume). Longer term, we should check if the network
517 // is online/offline and return an appropriate error code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800518 if (!sent_byte_ && http_response_code_ == 0 &&
Alex Deymof2858572016-02-25 11:20:13 -0800519 no_network_retry_count_ < no_network_max_retries_) {
520 no_network_retry_count_++;
Alex Deymob20de692017-02-05 07:47:37 +0000521 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymof2858572016-02-25 11:20:13 -0800522 FROM_HERE,
523 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
524 base::Unretained(this)),
525 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
526 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
527 } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
528 IsHttpResponseError()) {
529 // The transfer completed w/ error and we didn't get any bytes.
530 // If we have another proxy to try, try that.
531 //
532 // TODO(garnold) in fact there are two separate cases here: one case is an
533 // other-than-success return code (including no return code) and no
534 // received bytes, which is necessary due to the way callbacks are
535 // currently processing error conditions; the second is an explicit HTTP
536 // error code, where some data may have been received (as in the case of a
537 // semi-successful multi-chunk fetch). This is a confusing behavior and
538 // should be unified into a complete, coherent interface.
539 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
540 << "), " << bytes_downloaded_ << " bytes downloaded";
541
542 PopProxy(); // Delete the proxy we just gave up on.
543
544 if (HasProxy()) {
545 // We have another proxy. Retry immediately.
546 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymob20de692017-02-05 07:47:37 +0000547 retry_task_id_ = MessageLoop::current()->PostTask(
Alex Deymof2858572016-02-25 11:20:13 -0800548 FROM_HERE,
549 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
550 base::Unretained(this)));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700551 } else {
Alex Deymof2858572016-02-25 11:20:13 -0800552 // Out of proxies. Give up.
553 LOG(INFO) << "No further proxies, indicating transfer complete";
554 if (delegate_)
555 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700556 return;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700557 }
Alex Deymof2858572016-02-25 11:20:13 -0800558 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
559 if (!ignore_failure_)
560 retry_count_++;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800561 LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
562 << " of " << transfer_size_ << " bytes. "
Alex Deymof2858572016-02-25 11:20:13 -0800563 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
564 << "after " << retry_count_ << " attempt(s)";
Darin Petkov192ced42010-07-23 16:20:24 -0700565
Alex Deymof2858572016-02-25 11:20:13 -0800566 if (retry_count_ > max_retry_count_) {
567 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
568 if (delegate_)
569 delegate_->TransferComplete(this, false); // signal fail
Alex Deymo021a45e2016-03-15 13:12:05 -0700570 return;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000571 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700572 // Need to restart transfer
573 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymob20de692017-02-05 07:47:37 +0000574 retry_task_id_ = MessageLoop::current()->PostDelayedTask(
Alex Deymo021a45e2016-03-15 13:12:05 -0700575 FROM_HERE,
576 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
577 base::Unretained(this)),
578 TimeDelta::FromSeconds(retry_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000579 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800580 LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
581 << bytes_downloaded_ << " bytes downloaded";
Alex Deymof2858572016-02-25 11:20:13 -0800582 if (delegate_) {
583 bool success = IsHttpResponseSuccess();
584 delegate_->TransferComplete(this, success);
585 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700586 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000587 }
Alex Deymo021a45e2016-03-15 13:12:05 -0700588 // If we reach this point is because TransferComplete() was not called in any
589 // of the previous branches. The delegate is allowed to destroy the object
590 // once TransferComplete is called so this would be illegal.
Alex Deymof2858572016-02-25 11:20:13 -0800591 ignore_failure_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000592}
593
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800594size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800595 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700596 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800597 const size_t payload_size = size * nmemb;
598
599 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800600 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800601 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
602 << ") or no payload (" << payload_size << "), nothing to do";
603 return 0;
604 }
605
606 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000607 {
608 double transfer_size_double;
609 CHECK_EQ(curl_easy_getinfo(curl_handle_,
610 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800611 &transfer_size_double),
612 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000613 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
614 if (new_transfer_size > 0) {
615 transfer_size_ = resume_offset_ + new_transfer_size;
616 }
617 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800618 bytes_downloaded_ += payload_size;
Tao Bao028ea412018-12-27 14:12:14 -0800619 if (delegate_) {
620 in_write_callback_ = true;
621 auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
622 in_write_callback_ = false;
623 if (should_terminate) {
624 LOG(INFO) << "Requesting libcurl to terminate transfer.";
625 // Returning an amount that differs from the received size signals an
626 // error condition to libcurl, which will cause the transfer to be
627 // aborted.
628 return 0;
629 }
630 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800631 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000632}
633
634void LibcurlHttpFetcher::Pause() {
Alex Deymof2858572016-02-25 11:20:13 -0800635 if (transfer_paused_) {
636 LOG(ERROR) << "Fetcher already paused.";
637 return;
638 }
639 transfer_paused_ = true;
640 if (!transfer_in_progress_) {
641 // If pause before we started a connection, we don't need to notify curl
642 // about that, we will simply not start the connection later.
643 return;
644 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000645 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000646 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000647}
648
649void LibcurlHttpFetcher::Unpause() {
Alex Deymof2858572016-02-25 11:20:13 -0800650 if (!transfer_paused_) {
651 LOG(ERROR) << "Resume attempted when fetcher not paused.";
652 return;
653 }
654 transfer_paused_ = false;
655 if (restart_transfer_on_unpause_) {
656 restart_transfer_on_unpause_ = false;
657 ResumeTransfer(url_);
658 CurlPerformOnce();
659 return;
660 }
661 if (!transfer_in_progress_) {
662 // If resumed before starting the connection, there's no need to notify
663 // anybody. We will simply start the connection once it is time.
664 return;
665 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000666 CHECK(curl_handle_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000667 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
Alex Deymof2858572016-02-25 11:20:13 -0800668 // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
669 // now to let the connection continue, otherwise it would be called by the
670 // TimeoutCallback but with a delay.
671 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000672}
673
Alex Deymo29b81532015-07-09 11:51:49 -0700674// This method sets up callbacks with the MessageLoop.
675void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000676 fd_set fd_read;
677 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700678 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000679
680 FD_ZERO(&fd_read);
681 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700682 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000683
684 int fd_max = 0;
685
686 // Ask libcurl for the set of file descriptors we should track on its
687 // behalf.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800688 CHECK_EQ(curl_multi_fdset(
689 curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
690 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000691
692 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700693 // the highest one we're tracking, whichever is larger.
Tianjie55abd3c2020-06-19 00:22:59 -0700694#ifdef __ANDROID__
Alex Deymo29b81532015-07-09 11:51:49 -0700695 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
696 if (!fd_task_maps_[t].empty())
697 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700698 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000699
Darin Petkov60e14152010-10-27 16:57:04 -0700700 // For each fd, if we're not tracking it, track it. If we are tracking it, but
701 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700702 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700703 // there are read/write fds that we're tracking.
704 for (int fd = 0; fd <= fd_max; ++fd) {
705 // Note that fd_exc is unused in the current version of libcurl so is_exc
706 // should always be false.
707 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
708 bool must_track[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800709 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
710 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
Darin Petkov60e14152010-10-27 16:57:04 -0700711 };
Alex Deymo29b81532015-07-09 11:51:49 -0700712 MessageLoop::WatchMode watch_modes[2] = {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800713 MessageLoop::WatchMode::kWatchRead,
714 MessageLoop::WatchMode::kWatchWrite,
Alex Deymo29b81532015-07-09 11:51:49 -0700715 };
Darin Petkov60e14152010-10-27 16:57:04 -0700716
Alex Deymo29b81532015-07-09 11:51:49 -0700717 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
718 auto fd_task_it = fd_task_maps_[t].find(fd);
719 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700720
721 if (!must_track[t]) {
722 // If we have an outstanding io_channel, remove it.
723 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700724 MessageLoop::current()->CancelTask(fd_task_it->second);
725 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700726 }
727 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000728 }
Darin Petkov60e14152010-10-27 16:57:04 -0700729
730 // If we are already tracking this fd, continue -- nothing to do.
731 if (tracked)
732 continue;
733
Darin Petkov60e14152010-10-27 16:57:04 -0700734 // Track a new fd.
Alex Deymo29b81532015-07-09 11:51:49 -0700735 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
736 FROM_HERE,
737 fd,
738 watch_modes[t],
739 true, // persistent
740 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
741 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700742
Darin Petkov60e14152010-10-27 16:57:04 -0700743 static int io_counter = 0;
744 io_counter++;
745 if (io_counter % 50 == 0) {
746 LOG(INFO) << "io_counter = " << io_counter;
747 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700748 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000749 }
Tianjie55abd3c2020-06-19 00:22:59 -0700750#else
hscham00b6aa22020-02-20 12:32:06 +0900751 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900752 if (!fd_controller_maps_[t].empty())
753 fd_max = max(fd_max, fd_controller_maps_[t].rbegin()->first);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000754 }
755
756 // For each fd, if we're not tracking it, track it. If we are tracking it, but
757 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900758 // there should be exactly as many tasks scheduled in
759 // fd_controller_maps_[0|1] as there are read/write fds that we're tracking.
rspangler@google.com49fdf182009-10-10 00:57:34 +0000760 for (int fd = 0; fd <= fd_max; ++fd) {
761 // Note that fd_exc is unused in the current version of libcurl so is_exc
762 // should always be false.
763 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
764 bool must_track[2] = {
765 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
766 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
767 };
rspangler@google.com49fdf182009-10-10 00:57:34 +0000768
hscham00b6aa22020-02-20 12:32:06 +0900769 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900770 bool tracked =
771 fd_controller_maps_[t].find(fd) != fd_controller_maps_[t].end();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000772
773 if (!must_track[t]) {
774 // If we have an outstanding io_channel, remove it.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900775 fd_controller_maps_[t].erase(fd);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000776 continue;
777 }
778
779 // If we are already tracking this fd, continue -- nothing to do.
780 if (tracked)
781 continue;
782
783 // Track a new fd.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900784 switch (t) {
785 case 0: // Read
786 fd_controller_maps_[t][fd] =
787 base::FileDescriptorWatcher::WatchReadable(
788 fd,
789 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
790 base::Unretained(this)));
791 break;
792 case 1: // Write
793 fd_controller_maps_[t][fd] =
794 base::FileDescriptorWatcher::WatchWritable(
795 fd,
796 base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
797 base::Unretained(this)));
798 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000799 static int io_counter = 0;
800 io_counter++;
801 if (io_counter % 50 == 0) {
802 LOG(INFO) << "io_counter = " << io_counter;
803 }
804 }
805 }
Tianjie55abd3c2020-06-19 00:22:59 -0700806#endif // __ANDROID__
rspangler@google.com49fdf182009-10-10 00:57:34 +0000807
Darin Petkovb83371f2010-08-17 09:34:49 -0700808 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700809 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Alex Deymof2858572016-02-25 11:20:13 -0800810 VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700811 timeout_id_ = MessageLoop::current()->PostDelayedTask(
812 FROM_HERE,
813 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
814 base::Unretained(this)),
815 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000816 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000817}
818
Alex Deymo60ca1a72015-06-18 18:19:15 -0700819void LibcurlHttpFetcher::RetryTimeoutCallback() {
Alex Deymob20de692017-02-05 07:47:37 +0000820 retry_task_id_ = MessageLoop::kTaskIdNull;
Alex Deymof2858572016-02-25 11:20:13 -0800821 if (transfer_paused_) {
822 restart_transfer_on_unpause_ = true;
823 return;
824 }
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700825 ResumeTransfer(url_);
826 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700827}
828
Alex Deymo60ca1a72015-06-18 18:19:15 -0700829void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700830 // We always re-schedule the callback, even if we don't want to be called
831 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700832 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700833 timeout_id_ = MessageLoop::current()->PostDelayedTask(
834 FROM_HERE,
835 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
836 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700837
838 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
839 // first, since it could be canceled by this call.
840 if (transfer_in_progress_)
841 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000842}
843
844void LibcurlHttpFetcher::CleanUp() {
Alex Deymob20de692017-02-05 07:47:37 +0000845 MessageLoop::current()->CancelTask(retry_task_id_);
846 retry_task_id_ = MessageLoop::kTaskIdNull;
847
Alex Deymo60ca1a72015-06-18 18:19:15 -0700848 MessageLoop::current()->CancelTask(timeout_id_);
849 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000850
Tianjie55abd3c2020-06-19 00:22:59 -0700851#ifdef __ANDROID__
Alex Deymo29b81532015-07-09 11:51:49 -0700852 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
853 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
854 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800855 LOG(WARNING) << "Error canceling the watch task " << fd_taks_pair.second
856 << " for " << (t ? "writing" : "reading") << " the fd "
Alex Deymo29b81532015-07-09 11:51:49 -0700857 << fd_taks_pair.first;
858 }
Darin Petkov60e14152010-10-27 16:57:04 -0700859 }
Alex Deymo29b81532015-07-09 11:51:49 -0700860 fd_task_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000861 }
Tianjie55abd3c2020-06-19 00:22:59 -0700862#else
hscham00b6aa22020-02-20 12:32:06 +0900863 for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900864 fd_controller_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000865 }
Tianjie55abd3c2020-06-19 00:22:59 -0700866#endif // __ANDROID__
rspangler@google.com49fdf182009-10-10 00:57:34 +0000867
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800868 if (curl_http_headers_) {
869 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700870 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800871 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000872 if (curl_handle_) {
873 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000874 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
875 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000876 }
877 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700878 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000879 }
880 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000881 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700882 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000883 }
884 transfer_in_progress_ = false;
Alex Deymof2858572016-02-25 11:20:13 -0800885 transfer_paused_ = false;
886 restart_transfer_on_unpause_ = false;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000887}
888
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700889void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700890 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Alex Deymo56ccb072016-02-05 00:50:48 -0800891 if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
892 // Fake out a valid response code for file:// URLs.
893 http_response_code_ = 299;
894 } else if (curl_easy_getinfo(curl_handle_,
895 CURLINFO_RESPONSE_CODE,
896 &http_response_code) == CURLE_OK) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700897 http_response_code_ = static_cast<int>(http_response_code);
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700898 } else {
899 LOG(ERROR) << "Unable to get http response code from curl_easy_getinfo";
900 }
901}
902
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700903CURLcode LibcurlHttpFetcher::GetCurlCode() {
904 CURLcode curl_code = CURLE_OK;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700905 while (true) {
906 // Repeated calls to |curl_multi_info_read| will return a new struct each
907 // time, until a NULL is returned as a signal that there is no more to get
908 // at this point.
909 int msgs_in_queue;
910 CURLMsg* curl_msg =
911 curl_multi_info_read(curl_multi_handle_, &msgs_in_queue);
912 if (curl_msg == nullptr)
913 break;
914 // When |curl_msg| is |CURLMSG_DONE|, a transfer of an easy handle is done,
915 // and then data contains the return code for this transfer.
916 if (curl_msg->msg == CURLMSG_DONE) {
917 // Make sure |curl_multi_handle_| has one and only one easy handle
918 // |curl_handle_|.
919 CHECK_EQ(curl_handle_, curl_msg->easy_handle);
920 // Transfer return code reference:
921 // https://curl.haxx.se/libcurl/c/libcurl-errors.html
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700922 curl_code = curl_msg->data.result;
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700923 }
924 }
925
926 // Gets connection error if exists.
927 long connect_error = 0; // NOLINT(runtime/int) - curl needs long.
928 CURLcode res =
929 curl_easy_getinfo(curl_handle_, CURLINFO_OS_ERRNO, &connect_error);
930 if (res == CURLE_OK && connect_error) {
931 LOG(ERROR) << "Connect error code from the OS: " << connect_error;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700932 }
Xiaochu Liub5ba7972019-07-11 09:51:06 -0700933
934 return curl_code;
935}
936
937void UnresolvedHostStateMachine::UpdateState(bool failed_to_resolve_host) {
938 switch (state_) {
939 case State::kInit:
940 if (failed_to_resolve_host) {
941 state_ = State::kRetry;
942 }
943 break;
944 case State::kRetry:
945 if (failed_to_resolve_host) {
946 state_ = State::kNotRetry;
947 } else {
948 state_ = State::kRetriedSuccess;
949 }
950 break;
951 case State::kNotRetry:
952 break;
953 case State::kRetriedSuccess:
954 break;
955 default:
956 NOTREACHED();
957 break;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700958 }
959}
960
rspangler@google.com49fdf182009-10-10 00:57:34 +0000961} // namespace chromeos_update_engine