blob: 725bdd46024d42af74ead77ee7bddf4a71d5c7a6 [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 Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/libcurl_http_fetcher.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070018
adlr@google.comc98a7ed2009-12-04 18:54:03 +000019#include <algorithm>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070020#include <string>
21
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070022#include <base/bind.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070023#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070024#include <base/location.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070025#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070026#include <base/strings/string_util.h>
27#include <base/strings/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070028
Alex Deymo39910dc2015-11-09 17:04:30 -080029#include "update_engine/common/certificate_checker.h"
30#include "update_engine/common/hardware_interface.h"
31#include "update_engine/common/platform_constants.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000032
Alex Deymo60ca1a72015-06-18 18:19:15 -070033using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070034using brillo::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070035using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070036using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000037
38// This is a concrete implementation of HttpFetcher that uses libcurl to do the
39// http work.
40
41namespace chromeos_update_engine {
42
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070043namespace {
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080044const int kNoNetworkRetrySeconds = 10;
Alex Vakulenkod2779df2014-06-16 13:19:00 -070045} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070046
Alex Deymo33e91e72015-12-01 18:26:08 -030047LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
48 HardwareInterface* hardware)
49 : HttpFetcher(proxy_resolver), hardware_(hardware) {
Alex Deymoc1c17b42015-11-23 03:53:15 -030050 // Dev users want a longer timeout (180 seconds) because they may
51 // be waiting on the dev server to build an image.
52 if (!hardware_->IsOfficialBuild())
53 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
54 if (!hardware_->IsOOBEComplete(nullptr))
55 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
56}
57
rspangler@google.com49fdf182009-10-10 00:57:34 +000058LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080059 LOG_IF(ERROR, transfer_in_progress_)
60 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000061 CleanUp();
62}
63
Alex Deymof329b932014-10-30 01:37:48 -070064bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -070065 curl_proxytype* out_type) {
Alex Deymo56ccb072016-02-05 00:50:48 -080066 if (base::StartsWith(
67 proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
68 base::StartsWith(
69 proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070070 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
71 return true;
72 }
Alex Deymo56ccb072016-02-05 00:50:48 -080073 if (base::StartsWith(
74 proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070075 *out_type = CURLPROXY_SOCKS4A;
76 return true;
77 }
Alex Deymo56ccb072016-02-05 00:50:48 -080078 if (base::StartsWith(
79 proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
80 base::StartsWith(
81 proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070082 *out_type = CURLPROXY_HTTP;
83 return true;
84 }
Alex Deymo56ccb072016-02-05 00:50:48 -080085 if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070086 // known failure case. don't log.
87 return false;
88 }
89 LOG(INFO) << "Unknown proxy type: " << proxy;
90 return false;
91}
92
Alex Deymof329b932014-10-30 01:37:48 -070093void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070094 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000095 CHECK(!transfer_in_progress_);
96 url_ = url;
97 curl_multi_handle_ = curl_multi_init();
98 CHECK(curl_multi_handle_);
99
100 curl_handle_ = curl_easy_init();
101 CHECK(curl_handle_);
102
Andrew de los Reyes45168102010-11-22 11:13:50 -0800103 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700104 bool is_direct = (GetCurrentProxy() == kNoProxy);
105 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
106 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800107 CHECK_EQ(curl_easy_setopt(curl_handle_,
108 CURLOPT_PROXY,
109 ""), CURLE_OK);
110 } else {
111 CHECK_EQ(curl_easy_setopt(curl_handle_,
112 CURLOPT_PROXY,
113 GetCurrentProxy().c_str()), CURLE_OK);
114 // Curl seems to require us to set the protocol
115 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700116 if (GetProxyType(GetCurrentProxy(), &type)) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800117 CHECK_EQ(curl_easy_setopt(curl_handle_,
118 CURLOPT_PROXYTYPE,
119 type), CURLE_OK);
120 }
121 }
122
rspangler@google.com49fdf182009-10-10 00:57:34 +0000123 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000124 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
125 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800126 post_data_.data()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000127 CURLE_OK);
128 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
129 post_data_.size()),
130 CURLE_OK);
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800131 }
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800132
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800133 // Setup extra HTTP headers.
134 if (curl_http_headers_) {
135 curl_slist_free_all(curl_http_headers_);
136 curl_http_headers_ = nullptr;
137 }
138 for (const auto& header : extra_headers_) {
139 // curl_slist_append() copies the string.
140 curl_http_headers_ =
141 curl_slist_append(curl_http_headers_, header.second.c_str());
142 }
143 if (post_data_set_) {
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800144 // Set the Content-Type HTTP header, if one was specifically set.
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800145 if (post_content_type_ != kHttpContentTypeUnspecified) {
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800146 const string content_type_attr = base::StringPrintf(
147 "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
148 curl_http_headers_ =
149 curl_slist_append(curl_http_headers_, content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800150 } else {
151 LOG(WARNING) << "no content type set, using libcurl default";
152 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000153 }
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800154 CHECK_EQ(
155 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
156 CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000157
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800158 if (bytes_downloaded_ > 0 || download_length_) {
159 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000160 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800161 CHECK_GE(resume_offset_, 0);
162
163 // Compute end offset, if one is specified. As per HTTP specification, this
164 // is an inclusive boundary. Make sure it doesn't overflow.
165 size_t end_offset = 0;
166 if (download_length_) {
167 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
168 CHECK_LE((size_t) resume_offset_, end_offset);
169 }
170
171 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700172 string range_str = base::StringPrintf(
173 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
174 if (end_offset)
175 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800176 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
177 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000178 }
179
180 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
181 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
182 StaticLibcurlWrite), CURLE_OK);
Chris Sosa77f79e82014-06-02 18:16:24 -0700183 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700184 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700185
David Zeuthen34135a92013-08-06 11:16:16 -0700186 // If the connection drops under |low_speed_limit_bps_| (10
187 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
188 // 180 on non-official builds), reconnect.
189 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
190 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700191 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700192 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
193 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700194 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700195 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
196 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700197 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700198
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700199 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700200 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700201 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700202 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
203 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700204 CURLE_OK);
205
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700206 // Lock down the appropriate curl options for HTTP or HTTPS depending on
207 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300208 if (hardware_->IsOfficialBuild()) {
Alex Deymo56ccb072016-02-05 00:50:48 -0800209 if (base::StartsWith(
210 url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800211 SetCurlOptionsForHttp();
Alex Deymo56ccb072016-02-05 00:50:48 -0800212 } else if (base::StartsWith(
213 url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800214 SetCurlOptionsForHttps();
Alex Deymo56ccb072016-02-05 00:50:48 -0800215#if !defined(__CHROMEOS__) && !defined(__BRILLO__)
216 } else if (base::StartsWith(
217 url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
218 SetCurlOptionsForFile();
219#endif
220 } else {
221 LOG(ERROR) << "Received invalid URI: " << url_;
222 // Lock down to no protocol supported for the transfer.
223 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
224 }
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800225 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700226 LOG(INFO) << "Not setting http(s) curl options because we are "
227 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700228 }
229
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000230 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000231 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000232}
233
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800234// Lock down only the protocol in case of HTTP.
235void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
236 LOG(INFO) << "Setting up curl options for HTTP";
237 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
238 CURLE_OK);
239 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
240 CURLPROTO_HTTP),
241 CURLE_OK);
242}
243
244// Security lock-down in official builds: makes sure that peer certificate
245// verification is enabled, restricts the set of trusted certificates,
246// restricts protocols to HTTPS, restricts ciphers to HIGH.
247void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
248 LOG(INFO) << "Setting up curl options for HTTPS";
249 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
250 CURLE_OK);
Alex Deymo35b35842015-10-20 11:21:56 -0700251 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH,
252 constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800253 CURLE_OK);
254 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
255 CURLE_OK);
256 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
257 CURLPROTO_HTTPS),
258 CURLE_OK);
259 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
260 CURLE_OK);
Alex Deymo33e91e72015-12-01 18:26:08 -0300261 if (server_to_check_ != ServerToCheck::kNone) {
262 CHECK_EQ(
263 curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
264 CURLE_OK);
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800265 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
266 CertificateChecker::ProcessSSLContext),
267 CURLE_OK);
268 }
269}
270
Alex Deymo56ccb072016-02-05 00:50:48 -0800271// Lock down only the protocol in case of a local file.
272void LibcurlHttpFetcher::SetCurlOptionsForFile() {
273 LOG(INFO) << "Setting up curl options for FILE";
274 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
275 CURLE_OK);
276 CHECK_EQ(
277 curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
278 CURLE_OK);
279}
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800280
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000281// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700282void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800283 CHECK(!transfer_in_progress_);
284 url_ = url;
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700285 auto closure = base::Bind(&LibcurlHttpFetcher::ProxiesResolved,
286 base::Unretained(this));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700287 if (!ResolveProxiesForUrl(url_, closure)) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800288 LOG(ERROR) << "Couldn't resolve proxies";
289 if (delegate_)
290 delegate_->TransferComplete(this, false);
291 }
292}
293
294void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000295 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000296 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700297 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800298 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700299 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800300 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700301 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800302 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700303 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000304}
305
Darin Petkov9ce452b2010-11-17 14:33:28 -0800306void LibcurlHttpFetcher::ForceTransferTermination() {
307 CleanUp();
308 if (delegate_) {
309 // Note that after the callback returns this object may be destroyed.
310 delegate_->TransferTerminated(this);
311 }
312}
313
rspangler@google.com49fdf182009-10-10 00:57:34 +0000314void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800315 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700316 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800317 } else {
318 ForceTransferTermination();
319 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000320}
321
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800322void LibcurlHttpFetcher::SetHeader(const string& header_name,
323 const string& header_value) {
324 string header_line = header_name + ": " + header_value;
325 // Avoid the space if no data on the right side of the semicolon.
326 if (header_value.empty())
327 header_line = header_name + ":";
328 TEST_AND_RETURN(header_line.find('\n') == string::npos);
329 TEST_AND_RETURN(header_name.find(':') == string::npos);
330 extra_headers_[base::ToLowerASCII(header_name)] = header_line;
331}
332
Andrew de los Reyescb319332010-07-19 10:55:01 -0700333void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334 CHECK(transfer_in_progress_);
335 int running_handles = 0;
336 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
337
338 // libcurl may request that we immediately call curl_multi_perform after it
339 // returns, so we do. libcurl promises that curl_multi_perform will not block.
340 while (CURLM_CALL_MULTI_PERFORM == retcode) {
341 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700342 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800343 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700344 return;
345 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000346 }
347 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700348 GetHttpResponseCode();
349 if (http_response_code_) {
350 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800351 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700352 } else {
353 LOG(ERROR) << "Unable to get http response code.";
354 }
Darin Petkov192ced42010-07-23 16:20:24 -0700355
rspangler@google.com49fdf182009-10-10 00:57:34 +0000356 // we're done!
357 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000358
Darin Petkova0929552010-11-29 14:19:06 -0800359 // TODO(petkov): This temporary code tries to deal with the case where the
360 // update engine performs an update check while the network is not ready
361 // (e.g., right after resume). Longer term, we should check if the network
362 // is online/offline and return an appropriate error code.
363 if (!sent_byte_ &&
364 http_response_code_ == 0 &&
365 no_network_retry_count_ < no_network_max_retries_) {
366 no_network_retry_count_++;
Alex Deymo60ca1a72015-06-18 18:19:15 -0700367 MessageLoop::current()->PostDelayedTask(
368 FROM_HERE,
369 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
370 base::Unretained(this)),
371 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
Darin Petkova0929552010-11-29 14:19:06 -0800372 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
373 return;
374 }
375
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800376 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800377 // The transfer completed w/ error and we didn't get any bytes.
378 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800379 //
380 // TODO(garnold) in fact there are two separate cases here: one case is an
381 // other-than-success return code (including no return code) and no
382 // received bytes, which is necessary due to the way callbacks are
383 // currently processing error conditions; the second is an explicit HTTP
384 // error code, where some data may have been received (as in the case of a
385 // semi-successful multi-chunk fetch). This is a confusing behavior and
386 // should be unified into a complete, coherent interface.
387 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
388 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800389
390 PopProxy(); // Delete the proxy we just gave up on.
391
392 if (HasProxy()) {
393 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700394 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700395 MessageLoop::current()->PostTask(
396 FROM_HERE,
397 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
398 base::Unretained(this)));
Andrew de los Reyes45168102010-11-22 11:13:50 -0800399 } else {
400 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800401 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800402 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800403 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800404 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800405 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700406 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700407 LOG(INFO) << "Transfer interrupted after downloading "
408 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
409 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
410 << "after " << retry_count_ << " attempt(s)";
411
412 if (retry_count_ > max_retry_count_) {
413 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700414 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800415 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700416 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700417 // Need to restart transfer
418 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700419 MessageLoop::current()->PostDelayedTask(
420 FROM_HERE,
421 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
422 base::Unretained(this)),
423 TimeDelta::FromSeconds(retry_seconds_));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700424 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000425 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800426 LOG(INFO) << "Transfer completed (" << http_response_code_
427 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000428 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800429 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700430 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000431 }
432 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000433 } else {
434 // set up callback
Alex Deymo29b81532015-07-09 11:51:49 -0700435 SetupMessageLoopSources();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000436 }
437}
438
439size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800440 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700441 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800442 const size_t payload_size = size * nmemb;
443
444 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800445 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800446 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
447 << ") or no payload (" << payload_size << "), nothing to do";
448 return 0;
449 }
450
451 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000452 {
453 double transfer_size_double;
454 CHECK_EQ(curl_easy_getinfo(curl_handle_,
455 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
456 &transfer_size_double), CURLE_OK);
457 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
458 if (new_transfer_size > 0) {
459 transfer_size_ = resume_offset_ + new_transfer_size;
460 }
461 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800462 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700463 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 if (delegate_)
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800465 delegate_->ReceivedBytes(this, ptr, payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700466 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800467 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000468}
469
470void LibcurlHttpFetcher::Pause() {
471 CHECK(curl_handle_);
472 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000473 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000474}
475
476void LibcurlHttpFetcher::Unpause() {
477 CHECK(curl_handle_);
478 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000479 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000480}
481
Alex Deymo29b81532015-07-09 11:51:49 -0700482// This method sets up callbacks with the MessageLoop.
483void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484 fd_set fd_read;
485 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700486 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000487
488 FD_ZERO(&fd_read);
489 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700490 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000491
492 int fd_max = 0;
493
494 // Ask libcurl for the set of file descriptors we should track on its
495 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000496 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700497 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000498
499 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700500 // the highest one we're tracking, whichever is larger.
Alex Deymo29b81532015-07-09 11:51:49 -0700501 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
502 if (!fd_task_maps_[t].empty())
503 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700504 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000505
Darin Petkov60e14152010-10-27 16:57:04 -0700506 // For each fd, if we're not tracking it, track it. If we are tracking it, but
507 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700508 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700509 // there are read/write fds that we're tracking.
510 for (int fd = 0; fd <= fd_max; ++fd) {
511 // Note that fd_exc is unused in the current version of libcurl so is_exc
512 // should always be false.
513 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
514 bool must_track[2] = {
515 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
516 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
517 };
Alex Deymo29b81532015-07-09 11:51:49 -0700518 MessageLoop::WatchMode watch_modes[2] = {
519 MessageLoop::WatchMode::kWatchRead,
520 MessageLoop::WatchMode::kWatchWrite,
521 };
Darin Petkov60e14152010-10-27 16:57:04 -0700522
Alex Deymo29b81532015-07-09 11:51:49 -0700523 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
524 auto fd_task_it = fd_task_maps_[t].find(fd);
525 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700526
527 if (!must_track[t]) {
528 // If we have an outstanding io_channel, remove it.
529 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700530 MessageLoop::current()->CancelTask(fd_task_it->second);
531 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700532 }
533 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000534 }
Darin Petkov60e14152010-10-27 16:57:04 -0700535
536 // If we are already tracking this fd, continue -- nothing to do.
537 if (tracked)
538 continue;
539
Darin Petkov60e14152010-10-27 16:57:04 -0700540 // Track a new fd.
Alex Deymo29b81532015-07-09 11:51:49 -0700541 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
542 FROM_HERE,
543 fd,
544 watch_modes[t],
545 true, // persistent
546 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
547 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700548
Darin Petkov60e14152010-10-27 16:57:04 -0700549 static int io_counter = 0;
550 io_counter++;
551 if (io_counter % 50 == 0) {
552 LOG(INFO) << "io_counter = " << io_counter;
553 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700554 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000555 }
556
Darin Petkovb83371f2010-08-17 09:34:49 -0700557 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700558 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700559 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700560 timeout_id_ = MessageLoop::current()->PostDelayedTask(
561 FROM_HERE,
562 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
563 base::Unretained(this)),
564 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000565 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000566}
567
Alex Deymo60ca1a72015-06-18 18:19:15 -0700568void LibcurlHttpFetcher::RetryTimeoutCallback() {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700569 ResumeTransfer(url_);
570 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700571}
572
Alex Deymo60ca1a72015-06-18 18:19:15 -0700573void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700574 // We always re-schedule the callback, even if we don't want to be called
575 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700576 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700577 timeout_id_ = MessageLoop::current()->PostDelayedTask(
578 FROM_HERE,
579 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
580 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700581
582 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
583 // first, since it could be canceled by this call.
584 if (transfer_in_progress_)
585 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000586}
587
588void LibcurlHttpFetcher::CleanUp() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700589 MessageLoop::current()->CancelTask(timeout_id_);
590 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000591
Alex Deymo29b81532015-07-09 11:51:49 -0700592 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
593 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
594 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
595 LOG(WARNING) << "Error canceling the watch task "
596 << fd_taks_pair.second << " for "
597 << (t ? "writing" : "reading") << " the fd "
598 << fd_taks_pair.first;
599 }
Darin Petkov60e14152010-10-27 16:57:04 -0700600 }
Alex Deymo29b81532015-07-09 11:51:49 -0700601 fd_task_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000602 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000603
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800604 if (curl_http_headers_) {
605 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700606 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800607 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000608 if (curl_handle_) {
609 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000610 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
611 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000612 }
613 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700614 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000615 }
616 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000617 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700618 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000619 }
620 transfer_in_progress_ = false;
621}
622
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700623void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700624 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Alex Deymo56ccb072016-02-05 00:50:48 -0800625 if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
626 // Fake out a valid response code for file:// URLs.
627 http_response_code_ = 299;
628 } else if (curl_easy_getinfo(curl_handle_,
629 CURLINFO_RESPONSE_CODE,
630 &http_response_code) == CURLE_OK) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700631 http_response_code_ = static_cast<int>(http_response_code);
632 }
633}
634
rspangler@google.com49fdf182009-10-10 00:57:34 +0000635} // namespace chromeos_update_engine