blob: d36e32bd49b35d210cfcad472e8931e7da50ca43 [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
rspangler@google.com49fdf182009-10-10 00:57:34 +000047LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080048 LOG_IF(ERROR, transfer_in_progress_)
49 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000050 CleanUp();
51}
52
Alex Deymof329b932014-10-30 01:37:48 -070053bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -070054 curl_proxytype* out_type) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070055 if (base::StartsWithASCII(proxy, "socks5://", true) ||
56 base::StartsWithASCII(proxy, "socks://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070057 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
58 return true;
59 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070060 if (base::StartsWithASCII(proxy, "socks4://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070061 *out_type = CURLPROXY_SOCKS4A;
62 return true;
63 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070064 if (base::StartsWithASCII(proxy, "http://", true) ||
65 base::StartsWithASCII(proxy, "https://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070066 *out_type = CURLPROXY_HTTP;
67 return true;
68 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070069 if (base::StartsWithASCII(proxy, kNoProxy, true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070070 // known failure case. don't log.
71 return false;
72 }
73 LOG(INFO) << "Unknown proxy type: " << proxy;
74 return false;
75}
76
Alex Deymof329b932014-10-30 01:37:48 -070077void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070078 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000079 CHECK(!transfer_in_progress_);
80 url_ = url;
81 curl_multi_handle_ = curl_multi_init();
82 CHECK(curl_multi_handle_);
83
84 curl_handle_ = curl_easy_init();
85 CHECK(curl_handle_);
86
Andrew de los Reyes45168102010-11-22 11:13:50 -080087 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070088 bool is_direct = (GetCurrentProxy() == kNoProxy);
89 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
90 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080091 CHECK_EQ(curl_easy_setopt(curl_handle_,
92 CURLOPT_PROXY,
93 ""), CURLE_OK);
94 } else {
95 CHECK_EQ(curl_easy_setopt(curl_handle_,
96 CURLOPT_PROXY,
97 GetCurrentProxy().c_str()), CURLE_OK);
98 // Curl seems to require us to set the protocol
99 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700100 if (GetProxyType(GetCurrentProxy(), &type)) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800101 CHECK_EQ(curl_easy_setopt(curl_handle_,
102 CURLOPT_PROXYTYPE,
103 type), CURLE_OK);
104 }
105 }
106
rspangler@google.com49fdf182009-10-10 00:57:34 +0000107 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000108 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
109 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800110 post_data_.data()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000111 CURLE_OK);
112 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
113 post_data_.size()),
114 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800115
116 // Set the Content-Type HTTP header, if one was specifically set.
117 CHECK(!curl_http_headers_);
118 if (post_content_type_ != kHttpContentTypeUnspecified) {
119 const string content_type_attr =
120 base::StringPrintf("Content-Type: %s",
121 GetHttpContentTypeString(post_content_type_));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700122 curl_http_headers_ = curl_slist_append(nullptr,
123 content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800124 CHECK(curl_http_headers_);
125 CHECK_EQ(
126 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
127 curl_http_headers_),
128 CURLE_OK);
129 } else {
130 LOG(WARNING) << "no content type set, using libcurl default";
131 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000132 }
133
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800134 if (bytes_downloaded_ > 0 || download_length_) {
135 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000136 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800137 CHECK_GE(resume_offset_, 0);
138
139 // Compute end offset, if one is specified. As per HTTP specification, this
140 // is an inclusive boundary. Make sure it doesn't overflow.
141 size_t end_offset = 0;
142 if (download_length_) {
143 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
144 CHECK_LE((size_t) resume_offset_, end_offset);
145 }
146
147 // Create a string representation of the desired range.
Alex Deymoc00c98a2015-03-17 17:38:00 -0700148 string range_str = base::StringPrintf(
149 "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
150 if (end_offset)
151 range_str += std::to_string(end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800152 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
153 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000154 }
155
156 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
157 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
158 StaticLibcurlWrite), CURLE_OK);
Chris Sosa77f79e82014-06-02 18:16:24 -0700159 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700160 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700161
David Zeuthen34135a92013-08-06 11:16:16 -0700162 // If the connection drops under |low_speed_limit_bps_| (10
163 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
164 // 180 on non-official builds), reconnect.
165 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
166 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700167 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700168 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
169 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700170 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700171 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
172 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700173 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700174
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700175 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700176 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700177 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700178 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
179 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700180 CURLE_OK);
181
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700182 // Lock down the appropriate curl options for HTTP or HTTPS depending on
183 // the url.
184 if (GetSystemState()->hardware()->IsOfficialBuild()) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700185 if (base::StartsWithASCII(url_, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800186 SetCurlOptionsForHttp();
187 else
188 SetCurlOptionsForHttps();
189 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700190 LOG(INFO) << "Not setting http(s) curl options because we are "
191 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700192 }
193
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000194 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000195 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000196}
197
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800198// Lock down only the protocol in case of HTTP.
199void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
200 LOG(INFO) << "Setting up curl options for HTTP";
201 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
202 CURLE_OK);
203 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
204 CURLPROTO_HTTP),
205 CURLE_OK);
206}
207
208// Security lock-down in official builds: makes sure that peer certificate
209// verification is enabled, restricts the set of trusted certificates,
210// restricts protocols to HTTPS, restricts ciphers to HIGH.
211void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
212 LOG(INFO) << "Setting up curl options for HTTPS";
213 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
214 CURLE_OK);
Alex Deymo35b35842015-10-20 11:21:56 -0700215 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH,
216 constants::kCACertificatesPath),
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800217 CURLE_OK);
218 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
219 CURLE_OK);
220 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
221 CURLPROTO_HTTPS),
222 CURLE_OK);
223 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
224 CURLE_OK);
225 if (check_certificate_ != CertificateChecker::kNone) {
226 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
227 &check_certificate_),
228 CURLE_OK);
229 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
230 CertificateChecker::ProcessSSLContext),
231 CURLE_OK);
232 }
233}
234
235
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000236// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700237void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800238 CHECK(!transfer_in_progress_);
239 url_ = url;
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700240 auto closure = base::Bind(&LibcurlHttpFetcher::ProxiesResolved,
241 base::Unretained(this));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700242 if (!ResolveProxiesForUrl(url_, closure)) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800243 LOG(ERROR) << "Couldn't resolve proxies";
244 if (delegate_)
245 delegate_->TransferComplete(this, false);
246 }
247}
248
249void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000250 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000251 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700252 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800253 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700254 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800255 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700256 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800257 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700258 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000259}
260
Darin Petkov9ce452b2010-11-17 14:33:28 -0800261void LibcurlHttpFetcher::ForceTransferTermination() {
262 CleanUp();
263 if (delegate_) {
264 // Note that after the callback returns this object may be destroyed.
265 delegate_->TransferTerminated(this);
266 }
267}
268
rspangler@google.com49fdf182009-10-10 00:57:34 +0000269void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800270 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700271 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800272 } else {
273 ForceTransferTermination();
274 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000275}
276
Andrew de los Reyescb319332010-07-19 10:55:01 -0700277void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000278 CHECK(transfer_in_progress_);
279 int running_handles = 0;
280 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
281
282 // libcurl may request that we immediately call curl_multi_perform after it
283 // returns, so we do. libcurl promises that curl_multi_perform will not block.
284 while (CURLM_CALL_MULTI_PERFORM == retcode) {
285 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700286 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800287 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700288 return;
289 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000290 }
291 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700292 GetHttpResponseCode();
293 if (http_response_code_) {
294 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800295 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700296 } else {
297 LOG(ERROR) << "Unable to get http response code.";
298 }
Darin Petkov192ced42010-07-23 16:20:24 -0700299
rspangler@google.com49fdf182009-10-10 00:57:34 +0000300 // we're done!
301 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000302
Darin Petkova0929552010-11-29 14:19:06 -0800303 // TODO(petkov): This temporary code tries to deal with the case where the
304 // update engine performs an update check while the network is not ready
305 // (e.g., right after resume). Longer term, we should check if the network
306 // is online/offline and return an appropriate error code.
307 if (!sent_byte_ &&
308 http_response_code_ == 0 &&
309 no_network_retry_count_ < no_network_max_retries_) {
310 no_network_retry_count_++;
Alex Deymo60ca1a72015-06-18 18:19:15 -0700311 MessageLoop::current()->PostDelayedTask(
312 FROM_HERE,
313 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
314 base::Unretained(this)),
315 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
Darin Petkova0929552010-11-29 14:19:06 -0800316 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
317 return;
318 }
319
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800320 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800321 // The transfer completed w/ error and we didn't get any bytes.
322 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800323 //
324 // TODO(garnold) in fact there are two separate cases here: one case is an
325 // other-than-success return code (including no return code) and no
326 // received bytes, which is necessary due to the way callbacks are
327 // currently processing error conditions; the second is an explicit HTTP
328 // error code, where some data may have been received (as in the case of a
329 // semi-successful multi-chunk fetch). This is a confusing behavior and
330 // should be unified into a complete, coherent interface.
331 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
332 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800333
334 PopProxy(); // Delete the proxy we just gave up on.
335
336 if (HasProxy()) {
337 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700338 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700339 MessageLoop::current()->PostTask(
340 FROM_HERE,
341 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
342 base::Unretained(this)));
Andrew de los Reyes45168102010-11-22 11:13:50 -0800343 } else {
344 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800345 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800346 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800347 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800348 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800349 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700350 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700351 LOG(INFO) << "Transfer interrupted after downloading "
352 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
353 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
354 << "after " << retry_count_ << " attempt(s)";
355
356 if (retry_count_ > max_retry_count_) {
357 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700358 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800359 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700360 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700361 // Need to restart transfer
362 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700363 MessageLoop::current()->PostDelayedTask(
364 FROM_HERE,
365 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
366 base::Unretained(this)),
367 TimeDelta::FromSeconds(retry_seconds_));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700368 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000369 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800370 LOG(INFO) << "Transfer completed (" << http_response_code_
371 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000372 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800373 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700374 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000375 }
376 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000377 } else {
378 // set up callback
Alex Deymo29b81532015-07-09 11:51:49 -0700379 SetupMessageLoopSources();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000380 }
381}
382
383size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800384 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700385 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800386 const size_t payload_size = size * nmemb;
387
388 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800389 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800390 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
391 << ") or no payload (" << payload_size << "), nothing to do";
392 return 0;
393 }
394
395 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000396 {
397 double transfer_size_double;
398 CHECK_EQ(curl_easy_getinfo(curl_handle_,
399 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
400 &transfer_size_double), CURLE_OK);
401 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
402 if (new_transfer_size > 0) {
403 transfer_size_ = resume_offset_ + new_transfer_size;
404 }
405 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800406 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700407 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000408 if (delegate_)
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800409 delegate_->ReceivedBytes(this, ptr, payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700410 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800411 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000412}
413
414void LibcurlHttpFetcher::Pause() {
415 CHECK(curl_handle_);
416 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000417 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000418}
419
420void LibcurlHttpFetcher::Unpause() {
421 CHECK(curl_handle_);
422 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000423 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000424}
425
Alex Deymo29b81532015-07-09 11:51:49 -0700426// This method sets up callbacks with the MessageLoop.
427void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000428 fd_set fd_read;
429 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700430 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000431
432 FD_ZERO(&fd_read);
433 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700434 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000435
436 int fd_max = 0;
437
438 // Ask libcurl for the set of file descriptors we should track on its
439 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000440 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700441 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000442
443 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700444 // the highest one we're tracking, whichever is larger.
Alex Deymo29b81532015-07-09 11:51:49 -0700445 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
446 if (!fd_task_maps_[t].empty())
447 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700448 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449
Darin Petkov60e14152010-10-27 16:57:04 -0700450 // For each fd, if we're not tracking it, track it. If we are tracking it, but
451 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700452 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700453 // there are read/write fds that we're tracking.
454 for (int fd = 0; fd <= fd_max; ++fd) {
455 // Note that fd_exc is unused in the current version of libcurl so is_exc
456 // should always be false.
457 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
458 bool must_track[2] = {
459 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
460 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
461 };
Alex Deymo29b81532015-07-09 11:51:49 -0700462 MessageLoop::WatchMode watch_modes[2] = {
463 MessageLoop::WatchMode::kWatchRead,
464 MessageLoop::WatchMode::kWatchWrite,
465 };
Darin Petkov60e14152010-10-27 16:57:04 -0700466
Alex Deymo29b81532015-07-09 11:51:49 -0700467 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
468 auto fd_task_it = fd_task_maps_[t].find(fd);
469 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700470
471 if (!must_track[t]) {
472 // If we have an outstanding io_channel, remove it.
473 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700474 MessageLoop::current()->CancelTask(fd_task_it->second);
475 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700476 }
477 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000478 }
Darin Petkov60e14152010-10-27 16:57:04 -0700479
480 // If we are already tracking this fd, continue -- nothing to do.
481 if (tracked)
482 continue;
483
Darin Petkov60e14152010-10-27 16:57:04 -0700484 // Track a new fd.
Alex Deymo29b81532015-07-09 11:51:49 -0700485 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
486 FROM_HERE,
487 fd,
488 watch_modes[t],
489 true, // persistent
490 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
491 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700492
Darin Petkov60e14152010-10-27 16:57:04 -0700493 static int io_counter = 0;
494 io_counter++;
495 if (io_counter % 50 == 0) {
496 LOG(INFO) << "io_counter = " << io_counter;
497 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700498 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000499 }
500
Darin Petkovb83371f2010-08-17 09:34:49 -0700501 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700502 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700503 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700504 timeout_id_ = MessageLoop::current()->PostDelayedTask(
505 FROM_HERE,
506 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
507 base::Unretained(this)),
508 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000509 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000510}
511
Alex Deymo60ca1a72015-06-18 18:19:15 -0700512void LibcurlHttpFetcher::RetryTimeoutCallback() {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700513 ResumeTransfer(url_);
514 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700515}
516
Alex Deymo60ca1a72015-06-18 18:19:15 -0700517void LibcurlHttpFetcher::TimeoutCallback() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700518 // We always re-schedule the callback, even if we don't want to be called
519 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700520 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700521 timeout_id_ = MessageLoop::current()->PostDelayedTask(
522 FROM_HERE,
523 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
524 TimeDelta::FromSeconds(idle_seconds_));
Alex Deymof123ae22015-09-24 14:59:43 -0700525
526 // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
527 // first, since it could be canceled by this call.
528 if (transfer_in_progress_)
529 CurlPerformOnce();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000530}
531
532void LibcurlHttpFetcher::CleanUp() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700533 MessageLoop::current()->CancelTask(timeout_id_);
534 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000535
Alex Deymo29b81532015-07-09 11:51:49 -0700536 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
537 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
538 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
539 LOG(WARNING) << "Error canceling the watch task "
540 << fd_taks_pair.second << " for "
541 << (t ? "writing" : "reading") << " the fd "
542 << fd_taks_pair.first;
543 }
Darin Petkov60e14152010-10-27 16:57:04 -0700544 }
Alex Deymo29b81532015-07-09 11:51:49 -0700545 fd_task_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000546 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000547
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800548 if (curl_http_headers_) {
549 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700550 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800551 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000552 if (curl_handle_) {
553 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000554 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
555 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000556 }
557 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700558 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000559 }
560 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000561 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700562 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000563 }
564 transfer_in_progress_ = false;
565}
566
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700567void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700568 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700569 if (curl_easy_getinfo(curl_handle_,
570 CURLINFO_RESPONSE_CODE,
571 &http_response_code) == CURLE_OK) {
572 http_response_code_ = static_cast<int>(http_response_code);
573 }
574}
575
rspangler@google.com49fdf182009-10-10 00:57:34 +0000576} // namespace chromeos_update_engine