blob: 9d3229359aba7cc89334a9628e73635474b0fff4 [file] [log] [blame]
rspangler@google.com49fdf182009-10-10 00:57:34 +00001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
rspangler@google.com49fdf182009-10-10 00:57:34 +00005#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -07006
adlr@google.comc98a7ed2009-12-04 18:54:03 +00007#include <algorithm>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -07008#include <string>
9
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070010#include <base/bind.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070011#include <base/location.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070012#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070013#include <base/strings/string_util.h>
14#include <base/strings/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070015
Bruno Rocha7f9aea22011-09-12 14:31:24 -070016#include "update_engine/certificate_checker.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070017#include "update_engine/hardware_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000018
Alex Deymo60ca1a72015-06-18 18:19:15 -070019using base::TimeDelta;
20using chromeos::MessageLoop;
Alex Deymoc4acdf42014-05-28 21:07:10 -070021using std::max;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070022using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000023
24// This is a concrete implementation of HttpFetcher that uses libcurl to do the
25// http work.
26
27namespace chromeos_update_engine {
28
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070029namespace {
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080030const int kNoNetworkRetrySeconds = 10;
Ken Mixterb2bf1222010-11-18 17:29:38 -080031const char kCACertificatesPath[] = "/usr/share/chromeos-ca-certificates";
Alex Vakulenkod2779df2014-06-16 13:19:00 -070032} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070033
rspangler@google.com49fdf182009-10-10 00:57:34 +000034LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080035 LOG_IF(ERROR, transfer_in_progress_)
36 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000037 CleanUp();
38}
39
Alex Deymof329b932014-10-30 01:37:48 -070040bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -070041 curl_proxytype* out_type) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070042 if (base::StartsWithASCII(proxy, "socks5://", true) ||
43 base::StartsWithASCII(proxy, "socks://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070044 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
45 return true;
46 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070047 if (base::StartsWithASCII(proxy, "socks4://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070048 *out_type = CURLPROXY_SOCKS4A;
49 return true;
50 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070051 if (base::StartsWithASCII(proxy, "http://", true) ||
52 base::StartsWithASCII(proxy, "https://", true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070053 *out_type = CURLPROXY_HTTP;
54 return true;
55 }
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070056 if (base::StartsWithASCII(proxy, kNoProxy, true)) {
Gilad Arnold59d9e012013-07-23 16:41:43 -070057 // known failure case. don't log.
58 return false;
59 }
60 LOG(INFO) << "Unknown proxy type: " << proxy;
61 return false;
62}
63
Alex Deymof329b932014-10-30 01:37:48 -070064void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070065 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000066 CHECK(!transfer_in_progress_);
67 url_ = url;
68 curl_multi_handle_ = curl_multi_init();
69 CHECK(curl_multi_handle_);
70
71 curl_handle_ = curl_easy_init();
72 CHECK(curl_handle_);
73
Andrew de los Reyes45168102010-11-22 11:13:50 -080074 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070075 bool is_direct = (GetCurrentProxy() == kNoProxy);
76 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
77 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080078 CHECK_EQ(curl_easy_setopt(curl_handle_,
79 CURLOPT_PROXY,
80 ""), CURLE_OK);
81 } else {
82 CHECK_EQ(curl_easy_setopt(curl_handle_,
83 CURLOPT_PROXY,
84 GetCurrentProxy().c_str()), CURLE_OK);
85 // Curl seems to require us to set the protocol
86 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -070087 if (GetProxyType(GetCurrentProxy(), &type)) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080088 CHECK_EQ(curl_easy_setopt(curl_handle_,
89 CURLOPT_PROXYTYPE,
90 type), CURLE_OK);
91 }
92 }
93
rspangler@google.com49fdf182009-10-10 00:57:34 +000094 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000095 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
96 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080097 post_data_.data()),
adlr@google.comc98a7ed2009-12-04 18:54:03 +000098 CURLE_OK);
99 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
100 post_data_.size()),
101 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800102
103 // Set the Content-Type HTTP header, if one was specifically set.
104 CHECK(!curl_http_headers_);
105 if (post_content_type_ != kHttpContentTypeUnspecified) {
106 const string content_type_attr =
107 base::StringPrintf("Content-Type: %s",
108 GetHttpContentTypeString(post_content_type_));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700109 curl_http_headers_ = curl_slist_append(nullptr,
110 content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800111 CHECK(curl_http_headers_);
112 CHECK_EQ(
113 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
114 curl_http_headers_),
115 CURLE_OK);
116 } else {
117 LOG(WARNING) << "no content type set, using libcurl default";
118 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000119 }
120
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800121 if (bytes_downloaded_ > 0 || download_length_) {
122 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000123 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800124 CHECK_GE(resume_offset_, 0);
125
126 // Compute end offset, if one is specified. As per HTTP specification, this
127 // is an inclusive boundary. Make sure it doesn't overflow.
128 size_t end_offset = 0;
129 if (download_length_) {
130 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
131 CHECK_LE((size_t) resume_offset_, end_offset);
132 }
133
134 // Create a string representation of the desired range.
Alex Deymof329b932014-10-30 01:37:48 -0700135 string range_str = (end_offset ?
136 base::StringPrintf("%jd-%zu", resume_offset_,
137 end_offset) :
138 base::StringPrintf("%jd-", resume_offset_));
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800139 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
140 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000141 }
142
143 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
144 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
145 StaticLibcurlWrite), CURLE_OK);
Chris Sosa77f79e82014-06-02 18:16:24 -0700146 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700147 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700148
David Zeuthen34135a92013-08-06 11:16:16 -0700149 // If the connection drops under |low_speed_limit_bps_| (10
150 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
151 // 180 on non-official builds), reconnect.
152 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
153 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700154 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700155 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
156 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700157 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700158 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
159 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700160 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700161
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700162 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700163 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700164 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700165 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
166 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700167 CURLE_OK);
168
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700169 // Lock down the appropriate curl options for HTTP or HTTPS depending on
170 // the url.
171 if (GetSystemState()->hardware()->IsOfficialBuild()) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700172 if (base::StartsWithASCII(url_, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800173 SetCurlOptionsForHttp();
174 else
175 SetCurlOptionsForHttps();
176 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700177 LOG(INFO) << "Not setting http(s) curl options because we are "
178 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700179 }
180
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000181 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000182 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000183}
184
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800185// Lock down only the protocol in case of HTTP.
186void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
187 LOG(INFO) << "Setting up curl options for HTTP";
188 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
189 CURLE_OK);
190 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
191 CURLPROTO_HTTP),
192 CURLE_OK);
193}
194
195// Security lock-down in official builds: makes sure that peer certificate
196// verification is enabled, restricts the set of trusted certificates,
197// restricts protocols to HTTPS, restricts ciphers to HIGH.
198void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
199 LOG(INFO) << "Setting up curl options for HTTPS";
200 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
201 CURLE_OK);
202 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH, kCACertificatesPath),
203 CURLE_OK);
204 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
205 CURLE_OK);
206 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
207 CURLPROTO_HTTPS),
208 CURLE_OK);
209 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
210 CURLE_OK);
211 if (check_certificate_ != CertificateChecker::kNone) {
212 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
213 &check_certificate_),
214 CURLE_OK);
215 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
216 CertificateChecker::ProcessSSLContext),
217 CURLE_OK);
218 }
219}
220
221
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000222// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700223void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800224 CHECK(!transfer_in_progress_);
225 url_ = url;
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700226 auto closure = base::Bind(&LibcurlHttpFetcher::ProxiesResolved,
227 base::Unretained(this));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700228 if (!ResolveProxiesForUrl(url_, closure)) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800229 LOG(ERROR) << "Couldn't resolve proxies";
230 if (delegate_)
231 delegate_->TransferComplete(this, false);
232 }
233}
234
235void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000236 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000237 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700238 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800239 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700240 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800241 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700242 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800243 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700244 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000245}
246
Darin Petkov9ce452b2010-11-17 14:33:28 -0800247void LibcurlHttpFetcher::ForceTransferTermination() {
248 CleanUp();
249 if (delegate_) {
250 // Note that after the callback returns this object may be destroyed.
251 delegate_->TransferTerminated(this);
252 }
253}
254
rspangler@google.com49fdf182009-10-10 00:57:34 +0000255void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800256 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700257 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800258 } else {
259 ForceTransferTermination();
260 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000261}
262
Andrew de los Reyescb319332010-07-19 10:55:01 -0700263void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000264 CHECK(transfer_in_progress_);
265 int running_handles = 0;
266 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
267
268 // libcurl may request that we immediately call curl_multi_perform after it
269 // returns, so we do. libcurl promises that curl_multi_perform will not block.
270 while (CURLM_CALL_MULTI_PERFORM == retcode) {
271 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700272 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800273 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700274 return;
275 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000276 }
277 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700278 GetHttpResponseCode();
279 if (http_response_code_) {
280 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800281 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700282 } else {
283 LOG(ERROR) << "Unable to get http response code.";
284 }
Darin Petkov192ced42010-07-23 16:20:24 -0700285
rspangler@google.com49fdf182009-10-10 00:57:34 +0000286 // we're done!
287 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000288
Darin Petkova0929552010-11-29 14:19:06 -0800289 // TODO(petkov): This temporary code tries to deal with the case where the
290 // update engine performs an update check while the network is not ready
291 // (e.g., right after resume). Longer term, we should check if the network
292 // is online/offline and return an appropriate error code.
293 if (!sent_byte_ &&
294 http_response_code_ == 0 &&
295 no_network_retry_count_ < no_network_max_retries_) {
296 no_network_retry_count_++;
Alex Deymo60ca1a72015-06-18 18:19:15 -0700297 MessageLoop::current()->PostDelayedTask(
298 FROM_HERE,
299 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
300 base::Unretained(this)),
301 TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
Darin Petkova0929552010-11-29 14:19:06 -0800302 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
303 return;
304 }
305
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800306 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800307 // The transfer completed w/ error and we didn't get any bytes.
308 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800309 //
310 // TODO(garnold) in fact there are two separate cases here: one case is an
311 // other-than-success return code (including no return code) and no
312 // received bytes, which is necessary due to the way callbacks are
313 // currently processing error conditions; the second is an explicit HTTP
314 // error code, where some data may have been received (as in the case of a
315 // semi-successful multi-chunk fetch). This is a confusing behavior and
316 // should be unified into a complete, coherent interface.
317 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
318 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800319
320 PopProxy(); // Delete the proxy we just gave up on.
321
322 if (HasProxy()) {
323 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700324 LOG(INFO) << "Retrying with next proxy setting";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700325 MessageLoop::current()->PostTask(
326 FROM_HERE,
327 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
328 base::Unretained(this)));
Andrew de los Reyes45168102010-11-22 11:13:50 -0800329 } else {
330 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800331 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800332 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800333 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800334 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800335 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700336 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700337 LOG(INFO) << "Transfer interrupted after downloading "
338 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
339 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
340 << "after " << retry_count_ << " attempt(s)";
341
342 if (retry_count_ > max_retry_count_) {
343 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700344 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800345 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700346 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700347 // Need to restart transfer
348 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700349 MessageLoop::current()->PostDelayedTask(
350 FROM_HERE,
351 base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
352 base::Unretained(this)),
353 TimeDelta::FromSeconds(retry_seconds_));
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700354 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000355 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800356 LOG(INFO) << "Transfer completed (" << http_response_code_
357 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000358 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800359 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700360 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000361 }
362 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000363 } else {
364 // set up callback
Alex Deymo29b81532015-07-09 11:51:49 -0700365 SetupMessageLoopSources();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000366 }
367}
368
369size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800370 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700371 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800372 const size_t payload_size = size * nmemb;
373
374 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800375 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800376 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
377 << ") or no payload (" << payload_size << "), nothing to do";
378 return 0;
379 }
380
381 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000382 {
383 double transfer_size_double;
384 CHECK_EQ(curl_easy_getinfo(curl_handle_,
385 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
386 &transfer_size_double), CURLE_OK);
387 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
388 if (new_transfer_size > 0) {
389 transfer_size_ = resume_offset_ + new_transfer_size;
390 }
391 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800392 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700393 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000394 if (delegate_)
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800395 delegate_->ReceivedBytes(this, ptr, payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700396 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800397 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000398}
399
400void LibcurlHttpFetcher::Pause() {
401 CHECK(curl_handle_);
402 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000403 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000404}
405
406void LibcurlHttpFetcher::Unpause() {
407 CHECK(curl_handle_);
408 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000409 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410}
411
Alex Deymo29b81532015-07-09 11:51:49 -0700412// This method sets up callbacks with the MessageLoop.
413void LibcurlHttpFetcher::SetupMessageLoopSources() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000414 fd_set fd_read;
415 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700416 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000417
418 FD_ZERO(&fd_read);
419 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700420 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000421
422 int fd_max = 0;
423
424 // Ask libcurl for the set of file descriptors we should track on its
425 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000426 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700427 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000428
429 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700430 // the highest one we're tracking, whichever is larger.
Alex Deymo29b81532015-07-09 11:51:49 -0700431 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
432 if (!fd_task_maps_[t].empty())
433 fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
Darin Petkov60e14152010-10-27 16:57:04 -0700434 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000435
Darin Petkov60e14152010-10-27 16:57:04 -0700436 // For each fd, if we're not tracking it, track it. If we are tracking it, but
437 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
Alex Deymo29b81532015-07-09 11:51:49 -0700438 // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
Darin Petkov60e14152010-10-27 16:57:04 -0700439 // there are read/write fds that we're tracking.
440 for (int fd = 0; fd <= fd_max; ++fd) {
441 // Note that fd_exc is unused in the current version of libcurl so is_exc
442 // should always be false.
443 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
444 bool must_track[2] = {
445 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
446 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
447 };
Alex Deymo29b81532015-07-09 11:51:49 -0700448 MessageLoop::WatchMode watch_modes[2] = {
449 MessageLoop::WatchMode::kWatchRead,
450 MessageLoop::WatchMode::kWatchWrite,
451 };
Darin Petkov60e14152010-10-27 16:57:04 -0700452
Alex Deymo29b81532015-07-09 11:51:49 -0700453 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
454 auto fd_task_it = fd_task_maps_[t].find(fd);
455 bool tracked = fd_task_it != fd_task_maps_[t].end();
Darin Petkov60e14152010-10-27 16:57:04 -0700456
457 if (!must_track[t]) {
458 // If we have an outstanding io_channel, remove it.
459 if (tracked) {
Alex Deymo29b81532015-07-09 11:51:49 -0700460 MessageLoop::current()->CancelTask(fd_task_it->second);
461 fd_task_maps_[t].erase(fd_task_it);
Darin Petkov60e14152010-10-27 16:57:04 -0700462 }
463 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 }
Darin Petkov60e14152010-10-27 16:57:04 -0700465
466 // If we are already tracking this fd, continue -- nothing to do.
467 if (tracked)
468 continue;
469
Darin Petkov60e14152010-10-27 16:57:04 -0700470 // Track a new fd.
Alex Deymo29b81532015-07-09 11:51:49 -0700471 fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
472 FROM_HERE,
473 fd,
474 watch_modes[t],
475 true, // persistent
476 base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
477 base::Unretained(this)));
Darin Petkov60e14152010-10-27 16:57:04 -0700478
Darin Petkov60e14152010-10-27 16:57:04 -0700479 static int io_counter = 0;
480 io_counter++;
481 if (io_counter % 50 == 0) {
482 LOG(INFO) << "io_counter = " << io_counter;
483 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700484 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000485 }
486
Darin Petkovb83371f2010-08-17 09:34:49 -0700487 // Set up a timeout callback for libcurl.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700488 if (timeout_id_ == MessageLoop::kTaskIdNull) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700489 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
Alex Deymo60ca1a72015-06-18 18:19:15 -0700490 timeout_id_ = MessageLoop::current()->PostDelayedTask(
491 FROM_HERE,
492 base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
493 base::Unretained(this)),
494 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000496}
497
Alex Deymo60ca1a72015-06-18 18:19:15 -0700498void LibcurlHttpFetcher::RetryTimeoutCallback() {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700499 ResumeTransfer(url_);
500 CurlPerformOnce();
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700501}
502
Alex Deymo60ca1a72015-06-18 18:19:15 -0700503void LibcurlHttpFetcher::TimeoutCallback() {
504 if (transfer_in_progress_)
505 CurlPerformOnce();
506
507 // We always re-schedule the callback, even if we don't want to be called
508 // anymore. We will remove the event source separately if we don't want to
Andrew de los Reyescb319332010-07-19 10:55:01 -0700509 // be called back.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700510 timeout_id_ = MessageLoop::current()->PostDelayedTask(
511 FROM_HERE,
512 base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
513 TimeDelta::FromSeconds(idle_seconds_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000514}
515
516void LibcurlHttpFetcher::CleanUp() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700517 MessageLoop::current()->CancelTask(timeout_id_);
518 timeout_id_ = MessageLoop::kTaskIdNull;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000519
Alex Deymo29b81532015-07-09 11:51:49 -0700520 for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
521 for (const auto& fd_taks_pair : fd_task_maps_[t]) {
522 if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
523 LOG(WARNING) << "Error canceling the watch task "
524 << fd_taks_pair.second << " for "
525 << (t ? "writing" : "reading") << " the fd "
526 << fd_taks_pair.first;
527 }
Darin Petkov60e14152010-10-27 16:57:04 -0700528 }
Alex Deymo29b81532015-07-09 11:51:49 -0700529 fd_task_maps_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000530 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000531
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800532 if (curl_http_headers_) {
533 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700534 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800535 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000536 if (curl_handle_) {
537 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000538 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
539 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000540 }
541 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700542 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000543 }
544 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000545 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700546 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000547 }
548 transfer_in_progress_ = false;
549}
550
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700551void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700552 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700553 if (curl_easy_getinfo(curl_handle_,
554 CURLINFO_RESPONSE_CODE,
555 &http_response_code) == CURLE_OK) {
556 http_response_code_ = static_cast<int>(http_response_code);
557 }
558}
559
rspangler@google.com49fdf182009-10-10 00:57:34 +0000560} // namespace chromeos_update_engine