blob: 5a248e659ecca7bfac50387ecd99671d3d566d08 [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"
Alex Deymoc1c17b42015-11-23 03:53:15 -030032#include "update_engine/system_state.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000033
Alex Deymo60ca1a72015-06-18 18:19:15 -070034using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070035using brillo::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070036using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070037using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000038
39// This is a concrete implementation of HttpFetcher that uses libcurl to do the
40// http work.
41
42namespace chromeos_update_engine {
43
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070044namespace {
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080045const int kNoNetworkRetrySeconds = 10;
Alex Vakulenkod2779df2014-06-16 13:19:00 -070046} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070047
Alex Deymoc1c17b42015-11-23 03:53:15 -030048LibcurlHttpFetcher::LibcurlHttpFetcher(
49 ProxyResolver* proxy_resolver,
50 SystemState* system_state,
51 std::unique_ptr<CertificateChecker> certificate_checker)
52 : HttpFetcher(proxy_resolver),
53 hardware_(system_state->hardware()),
54 certificate_checker_(std::move(certificate_checker)) {
55 // Dev users want a longer timeout (180 seconds) because they may
56 // be waiting on the dev server to build an image.
57 if (!hardware_->IsOfficialBuild())
58 low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
59 if (!hardware_->IsOOBEComplete(nullptr))
60 max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
61}
62
rspangler@google.com49fdf182009-10-10 00:57:34 +000063LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080064 LOG_IF(ERROR, transfer_in_progress_)
65 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000066 CleanUp();
67}
68
Alex Deymof329b932014-10-30 01:37:48 -070069bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -070070 curl_proxytype* out_type) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070071 if (base::StartsWithASCII(proxy, "socks5://", true) ||
72 base::StartsWithASCII(proxy, "socks://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070073 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
74 return true;
75 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070076 if (base::StartsWithASCII(proxy, "socks4://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070077 *out_type = CURLPROXY_SOCKS4A;
78 return true;
79 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070080 if (base::StartsWithASCII(proxy, "http://", true) ||
81 base::StartsWithASCII(proxy, "https://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070082 *out_type = CURLPROXY_HTTP;
83 return true;
84 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070085 if (base::StartsWithASCII(proxy, kNoProxy, true)) {
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);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800131
132 // Set the Content-Type HTTP header, if one was specifically set.
133 CHECK(!curl_http_headers_);
134 if (post_content_type_ != kHttpContentTypeUnspecified) {
135 const string content_type_attr =
136 base::StringPrintf("Content-Type: %s",
137 GetHttpContentTypeString(post_content_type_));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700138 curl_http_headers_ = curl_slist_append(nullptr,
139 content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800140 CHECK(curl_http_headers_);
141 CHECK_EQ(
142 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
143 curl_http_headers_),
144 CURLE_OK);
145 } else {
146 LOG(WARNING) << "no content type set, using libcurl default";
147 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000148 }
149
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800150 if (bytes_downloaded_ > 0 || download_length_) {
151 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000152 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800153 CHECK_GE(resume_offset_, 0);
154
155 // Compute end offset, if one is specified. As per HTTP specification, this
156 // is an inclusive boundary. Make sure it doesn't overflow.
157 size_t end_offset = 0;
158 if (download_length_) {
159 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
160 CHECK_LE((size_t) resume_offset_, end_offset);
161 }
162
163 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700164 string range_str = base::StringPrintf(
165 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
166 if (end_offset)
167 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800168 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
169 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000170 }
171
172 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
173 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
174 StaticLibcurlWrite), CURLE_OK);
Chris Sosa77f79e82014-06-02 18:16:24 -0700175 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700176 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700177
David Zeuthen34135a92013-08-06 11:16:16 -0700178 // If the connection drops under |low_speed_limit_bps_| (10
179 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
180 // 180 on non-official builds), reconnect.
181 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
182 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700183 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700184 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
185 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700186 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700187 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
188 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700189 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700190
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700191 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700192 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700193 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700194 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
195 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700196 CURLE_OK);
197
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700198 // Lock down the appropriate curl options for HTTP or HTTPS depending on
199 // the url.
Alex Deymoc1c17b42015-11-23 03:53:15 -0300200 if (hardware_->IsOfficialBuild()) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700201 if (base::StartsWithASCII(url_, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800202 SetCurlOptionsForHttp();
203 else
204 SetCurlOptionsForHttps();
205 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700206 LOG(INFO) << "Not setting http(s) curl options because we are "
207 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700208 }
209
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000210 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000211 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000212}
213
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800214// Lock down only the protocol in case of HTTP.
215void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
216 LOG(INFO) << "Setting up curl options for HTTP";
217 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
218 CURLE_OK);
219 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
220 CURLPROTO_HTTP),
221 CURLE_OK);
222}
223
224// Security lock-down in official builds: makes sure that peer certificate
225// verification is enabled, restricts the set of trusted certificates,
226// restricts protocols to HTTPS, restricts ciphers to HIGH.
227void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
228 LOG(INFO) << "Setting up curl options for HTTPS";
229 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
230 CURLE_OK);
Alex Deymo35b35842015-10-20 11:21:56 -0700231 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH,
232 constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800233 CURLE_OK);
234 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
235 CURLE_OK);
236 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
237 CURLPROTO_HTTPS),
238 CURLE_OK);
239 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
240 CURLE_OK);
Alex Deymoc1c17b42015-11-23 03:53:15 -0300241 if (certificate_checker_ != nullptr) {
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800242 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
Alex Deymoc1c17b42015-11-23 03:53:15 -0300243 certificate_checker_.get()),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800244 CURLE_OK);
245 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
246 CertificateChecker::ProcessSSLContext),
247 CURLE_OK);
248 }
249}
250
251
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000252// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700253void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800254 CHECK(!transfer_in_progress_);
255 url_ = url;
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700256 auto closure = base::Bind(&LibcurlHttpFetcher::ProxiesResolved,
257 base::Unretained(this));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700258 if (!ResolveProxiesForUrl(url_, closure)) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800259 LOG(ERROR) << "Couldn't resolve proxies";
260 if (delegate_)
261 delegate_->TransferComplete(this, false);
262 }
263}
264
265void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000266 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000267 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700268 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800269 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700270 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800271 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700272 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800273 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700274 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000275}
276
Darin Petkov9ce452b2010-11-17 14:33:28 -0800277void LibcurlHttpFetcher::ForceTransferTermination() {
278 CleanUp();
279 if (delegate_) {
280 // Note that after the callback returns this object may be destroyed.
281 delegate_->TransferTerminated(this);
282 }
283}
284
rspangler@google.com49fdf182009-10-10 00:57:34 +0000285void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800286 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700287 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800288 } else {
289 ForceTransferTermination();
290 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291}
292
Andrew de los Reyescb319332010-07-19 10:55:01 -0700293void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294 CHECK(transfer_in_progress_);
295 int running_handles = 0;
296 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
297
298 // libcurl may request that we immediately call curl_multi_perform after it
299 // returns, so we do. libcurl promises that curl_multi_perform will not block.
300 while (CURLM_CALL_MULTI_PERFORM == retcode) {
301 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700302 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800303 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700304 return;
305 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000306 }
307 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700308 GetHttpResponseCode();
309 if (http_response_code_) {
310 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800311 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700312 } else {
313 LOG(ERROR) << "Unable to get http response code.";
314 }
Darin Petkov192ced42010-07-23 16:20:24 -0700315
rspangler@google.com49fdf182009-10-10 00:57:34 +0000316 // we're done!
317 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000318
Darin Petkova0929552010-11-29 14:19:06 -0800319 // TODO(petkov): This temporary code tries to deal with the case where the
320 // update engine performs an update check while the network is not ready
321 // (e.g., right after resume). Longer term, we should check if the network
322 // is online/offline and return an appropriate error code.
323 if (!sent_byte_ &&
324 http_response_code_ == 0 &&
325 no_network_retry_count_ < no_network_max_retries_) {
326 no_network_retry_count_++;
Alex Deymo60ca1a72015-06-18 18:19:15 -0700327 MessageLoop::current()->PostDelayedTask(
328 FROM_HERE,
329 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
330 base::Unretained(this)),
331 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
Darin Petkova0929552010-11-29 14:19:06 -0800332 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
333 return;
334 }
335
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800336 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800337 // The transfer completed w/ error and we didn't get any bytes.
338 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800339 //
340 // TODO(garnold) in fact there are two separate cases here: one case is an
341 // other-than-success return code (including no return code) and no
342 // received bytes, which is necessary due to the way callbacks are
343 // currently processing error conditions; the second is an explicit HTTP
344 // error code, where some data may have been received (as in the case of a
345 // semi-successful multi-chunk fetch). This is a confusing behavior and
346 // should be unified into a complete, coherent interface.
347 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
348 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800349
350 PopProxy(); // Delete the proxy we just gave up on.
351
352 if (HasProxy()) {
353 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700354 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700355 MessageLoop::current()->PostTask(
356 FROM_HERE,
357 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
358 base::Unretained(this)));
Andrew de los Reyes45168102010-11-22 11:13:50 -0800359 } else {
360 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800361 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800362 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800363 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800364 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800365 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700366 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700367 LOG(INFO) << "Transfer interrupted after downloading "
368 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
369 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
370 << "after " << retry_count_ << " attempt(s)";
371
372 if (retry_count_ > max_retry_count_) {
373 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700374 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800375 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700376 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700377 // Need to restart transfer
378 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700379 MessageLoop::current()->PostDelayedTask(
380 FROM_HERE,
381 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
382 base::Unretained(this)),
383 TimeDelta::FromSeconds(retry_seconds_));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700384 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000385 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800386 LOG(INFO) << "Transfer completed (" << http_response_code_
387 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000388 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800389 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700390 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000391 }
392 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000393 } else {
394 // set up callback
Alex Deymo29b81532015-07-09 11:51:49 -0700395 SetupMessageLoopSources();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000396 }
397}
398
399size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800400 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700401 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800402 const size_t payload_size = size * nmemb;
403
404 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800405 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800406 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
407 << ") or no payload (" << payload_size << "), nothing to do";
408 return 0;
409 }
410
411 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000412 {
413 double transfer_size_double;
414 CHECK_EQ(curl_easy_getinfo(curl_handle_,
415 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
416 &transfer_size_double), CURLE_OK);
417 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
418 if (new_transfer_size > 0) {
419 transfer_size_ = resume_offset_ + new_transfer_size;
420 }
421 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800422 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700423 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000424 if (delegate_)
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800425 delegate_->ReceivedBytes(this, ptr, payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700426 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800427 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000428}
429
430void LibcurlHttpFetcher::Pause() {
431 CHECK(curl_handle_);
432 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000433 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000434}
435
436void LibcurlHttpFetcher::Unpause() {
437 CHECK(curl_handle_);
438 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000439 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000440}
441
Alex Deymo29b81532015-07-09 11:51:49 -0700442// This method sets up callbacks with the MessageLoop.
443void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000444 fd_set fd_read;
445 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700446 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000447
448 FD_ZERO(&fd_read);
449 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700450 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000451
452 int fd_max = 0;
453
454 // Ask libcurl for the set of file descriptors we should track on its
455 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000456 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700457 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000458
459 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700460 // the highest one we're tracking, whichever is larger.
Alex Deymo29b81532015-07-09 11:51:49 -0700461 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
462 if (!fd_task_maps_[t].empty())
463 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700464 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000465
Darin Petkov60e14152010-10-27 16:57:04 -0700466 // For each fd, if we're not tracking it, track it. If we are tracking it, but
467 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700468 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700469 // there are read/write fds that we're tracking.
470 for (int fd = 0; fd <= fd_max; ++fd) {
471 // Note that fd_exc is unused in the current version of libcurl so is_exc
472 // should always be false.
473 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
474 bool must_track[2] = {
475 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
476 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
477 };
Alex Deymo29b81532015-07-09 11:51:49 -0700478 MessageLoop::WatchMode watch_modes[2] = {
479 MessageLoop::WatchMode::kWatchRead,
480 MessageLoop::WatchMode::kWatchWrite,
481 };
Darin Petkov60e14152010-10-27 16:57:04 -0700482
Alex Deymo29b81532015-07-09 11:51:49 -0700483 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
484 auto fd_task_it = fd_task_maps_[t].find(fd);
485 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700486
487 if (!must_track[t]) {
488 // If we have an outstanding io_channel, remove it.
489 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700490 MessageLoop::current()->CancelTask(fd_task_it->second);
491 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700492 }
493 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494 }
Darin Petkov60e14152010-10-27 16:57:04 -0700495
496 // If we are already tracking this fd, continue -- nothing to do.
497 if (tracked)
498 continue;
499
Darin Petkov60e14152010-10-27 16:57:04 -0700500 // Track a new fd.
Alex Deymo29b81532015-07-09 11:51:49 -0700501 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
502 FROM_HERE,
503 fd,
504 watch_modes[t],
505 true, // persistent
506 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
507 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700508
Darin Petkov60e14152010-10-27 16:57:04 -0700509 static int io_counter = 0;
510 io_counter++;
511 if (io_counter % 50 == 0) {
512 LOG(INFO) << "io_counter = " << io_counter;
513 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700514 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000515 }
516
Darin Petkovb83371f2010-08-17 09:34:49 -0700517 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700518 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700519 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700520 timeout_id_ = MessageLoop::current()->PostDelayedTask(
521 FROM_HERE,
522 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
523 base::Unretained(this)),
524 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000525 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526}
527
Alex Deymo60ca1a72015-06-18 18:19:15 -0700528void LibcurlHttpFetcher::RetryTimeoutCallback() {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700529 ResumeTransfer(url_);
530 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700531}
532
Alex Deymo60ca1a72015-06-18 18:19:15 -0700533void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700534 // We always re-schedule the callback, even if we don't want to be called
535 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700536 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700537 timeout_id_ = MessageLoop::current()->PostDelayedTask(
538 FROM_HERE,
539 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
540 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700541
542 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
543 // first, since it could be canceled by this call.
544 if (transfer_in_progress_)
545 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000546}
547
548void LibcurlHttpFetcher::CleanUp() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700549 MessageLoop::current()->CancelTask(timeout_id_);
550 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000551
Alex Deymo29b81532015-07-09 11:51:49 -0700552 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
553 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
554 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
555 LOG(WARNING) << "Error canceling the watch task "
556 << fd_taks_pair.second << " for "
557 << (t ? "writing" : "reading") << " the fd "
558 << fd_taks_pair.first;
559 }
Darin Petkov60e14152010-10-27 16:57:04 -0700560 }
Alex Deymo29b81532015-07-09 11:51:49 -0700561 fd_task_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000562 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000563
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800564 if (curl_http_headers_) {
565 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700566 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800567 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000568 if (curl_handle_) {
569 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000570 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
571 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000572 }
573 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700574 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000575 }
576 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000577 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700578 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000579 }
580 transfer_in_progress_ = false;
581}
582
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700583void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700584 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700585 if (curl_easy_getinfo(curl_handle_,
586 CURLINFO_RESPONSE_CODE,
587 &http_response_code) == CURLE_OK) {
588 http_response_code_ = static_cast<int>(http_response_code);
589 }
590}
591
rspangler@google.com49fdf182009-10-10 00:57:34 +0000592} // namespace chromeos_update_engine