blob: 57f0595113d7eab712bebabdf48af020754f124d [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
10#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070011#include <base/strings/string_util.h>
12#include <base/strings/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070013
Bruno Rocha7f9aea22011-09-12 14:31:24 -070014#include "update_engine/certificate_checker.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070015#include "update_engine/hardware_interface.h"
Gilad Arnold1b9d6ae2014-03-03 13:46:07 -080016#include "update_engine/real_dbus_wrapper.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070017#include "update_engine/utils.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000018
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080019using google::protobuf::NewCallback;
adlr@google.comc98a7ed2009-12-04 18:54:03 +000020using std::max;
21using std::make_pair;
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";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -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
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070040// On error, returns false.
Jay Srinivasan43488792012-06-19 00:25:31 -070041bool LibcurlHttpFetcher::IsUpdateAllowedOverCurrentConnection() const {
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070042 NetworkConnectionType type;
Alex Deymo6ae91202014-03-10 19:21:25 -070043 NetworkTethering tethering;
Gilad Arnold1b9d6ae2014-03-03 13:46:07 -080044 RealDBusWrapper dbus_iface;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080045 ConnectionManager* connection_manager = system_state_->connection_manager();
Alex Deymo6ae91202014-03-10 19:21:25 -070046 if (!connection_manager->GetConnectionProperties(&dbus_iface,
47 &type, &tethering)) {
Chris Sosa133f8922013-11-06 16:39:16 -080048 LOG(INFO) << "We could not determine our connection type. "
49 << "Defaulting to allow updates.";
50 return true;
51 }
Alex Deymo6ae91202014-03-10 19:21:25 -070052 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070053 LOG(INFO) << "We are connected via "
Jay Srinivasan43488792012-06-19 00:25:31 -070054 << connection_manager->StringForConnectionType(type)
55 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
56 return is_allowed;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070057}
58
Darin Petkovfc7a0ce2010-10-25 10:38:37 -070059bool LibcurlHttpFetcher::IsOfficialBuild() const {
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070060 return force_build_type_ ? forced_official_build_
61 : system_state_->hardware()->IsOfficialBuild();
Darin Petkovfc7a0ce2010-10-25 10:38:37 -070062}
63
Gilad Arnold59d9e012013-07-23 16:41:43 -070064bool LibcurlHttpFetcher::GetProxyType(const std::string& proxy,
65 curl_proxytype* out_type) {
66 if (utils::StringHasPrefix(proxy, "socks5://") ||
67 utils::StringHasPrefix(proxy, "socks://")) {
68 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
69 return true;
70 }
71 if (utils::StringHasPrefix(proxy, "socks4://")) {
72 *out_type = CURLPROXY_SOCKS4A;
73 return true;
74 }
75 if (utils::StringHasPrefix(proxy, "http://") ||
76 utils::StringHasPrefix(proxy, "https://")) {
77 *out_type = CURLPROXY_HTTP;
78 return true;
79 }
80 if (utils::StringHasPrefix(proxy, kNoProxy)) {
81 // known failure case. don't log.
82 return false;
83 }
84 LOG(INFO) << "Unknown proxy type: " << proxy;
85 return false;
86}
87
adlr@google.comc98a7ed2009-12-04 18:54:03 +000088void LibcurlHttpFetcher::ResumeTransfer(const std::string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070089 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000090 CHECK(!transfer_in_progress_);
91 url_ = url;
92 curl_multi_handle_ = curl_multi_init();
93 CHECK(curl_multi_handle_);
94
95 curl_handle_ = curl_easy_init();
96 CHECK(curl_handle_);
97
Andrew de los Reyes45168102010-11-22 11:13:50 -080098 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070099 bool is_direct = (GetCurrentProxy() == kNoProxy);
100 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
101 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800102 CHECK_EQ(curl_easy_setopt(curl_handle_,
103 CURLOPT_PROXY,
104 ""), CURLE_OK);
105 } else {
106 CHECK_EQ(curl_easy_setopt(curl_handle_,
107 CURLOPT_PROXY,
108 GetCurrentProxy().c_str()), CURLE_OK);
109 // Curl seems to require us to set the protocol
110 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -0700111 if (GetProxyType(GetCurrentProxy(), &type)) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800112 CHECK_EQ(curl_easy_setopt(curl_handle_,
113 CURLOPT_PROXYTYPE,
114 type), CURLE_OK);
115 }
116 }
117
rspangler@google.com49fdf182009-10-10 00:57:34 +0000118 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000119 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
120 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
121 &post_data_[0]),
122 CURLE_OK);
123 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
124 post_data_.size()),
125 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800126
127 // Set the Content-Type HTTP header, if one was specifically set.
128 CHECK(!curl_http_headers_);
129 if (post_content_type_ != kHttpContentTypeUnspecified) {
130 const string content_type_attr =
131 base::StringPrintf("Content-Type: %s",
132 GetHttpContentTypeString(post_content_type_));
133 curl_http_headers_ = curl_slist_append(NULL, content_type_attr.c_str());
134 CHECK(curl_http_headers_);
135 CHECK_EQ(
136 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
137 curl_http_headers_),
138 CURLE_OK);
139 } else {
140 LOG(WARNING) << "no content type set, using libcurl default";
141 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000142 }
143
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800144 if (bytes_downloaded_ > 0 || download_length_) {
145 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000146 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800147 CHECK_GE(resume_offset_, 0);
148
149 // Compute end offset, if one is specified. As per HTTP specification, this
150 // is an inclusive boundary. Make sure it doesn't overflow.
151 size_t end_offset = 0;
152 if (download_length_) {
153 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
154 CHECK_LE((size_t) resume_offset_, end_offset);
155 }
156
157 // Create a string representation of the desired range.
158 std::string range_str = (end_offset ?
Alex Vakulenko75039d72014-03-25 12:36:28 -0700159 base::StringPrintf("%jd-%zu", resume_offset_,
160 end_offset) :
161 base::StringPrintf("%jd-", resume_offset_));
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800162 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
163 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000164 }
165
166 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
167 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
168 StaticLibcurlWrite), CURLE_OK);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700169
170 string url_to_use(url_);
Jay Srinivasan43488792012-06-19 00:25:31 -0700171 if (!IsUpdateAllowedOverCurrentConnection()) {
172 LOG(INFO) << "Not initiating HTTP connection b/c updates are disabled "
173 << "over this connection";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700174 url_to_use = ""; // Sabotage the URL
175 }
176
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700177 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_to_use.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700178 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700179
David Zeuthen34135a92013-08-06 11:16:16 -0700180 // If the connection drops under |low_speed_limit_bps_| (10
181 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
182 // 180 on non-official builds), reconnect.
183 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
184 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700185 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700186 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
187 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700188 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700189 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
190 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700191 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700192
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700193 // By default, libcurl doesn't follow redirections. Allow up to
David Zeuthen34135a92013-08-06 11:16:16 -0700194 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700195 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700196 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
197 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700198 CURLE_OK);
199
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800200 // If we are running in test mode or using a dev/test build, then lock down
201 // the appropriate curl options for HTTP or HTTPS depending on the url.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700202 if (!is_test_mode_ && IsOfficialBuild()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800203 if (StartsWithASCII(url_to_use, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800204 SetCurlOptionsForHttp();
205 else
206 SetCurlOptionsForHttps();
207 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800208 LOG(INFO) << "Not setting http(s) curl options because we are in "
209 << "test mode or running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700210 }
211
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000212 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000213 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000214}
215
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800216// Lock down only the protocol in case of HTTP.
217void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
218 LOG(INFO) << "Setting up curl options for HTTP";
219 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
220 CURLE_OK);
221 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
222 CURLPROTO_HTTP),
223 CURLE_OK);
224}
225
226// Security lock-down in official builds: makes sure that peer certificate
227// verification is enabled, restricts the set of trusted certificates,
228// restricts protocols to HTTPS, restricts ciphers to HIGH.
229void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
230 LOG(INFO) << "Setting up curl options for HTTPS";
231 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
232 CURLE_OK);
233 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH, kCACertificatesPath),
234 CURLE_OK);
235 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
236 CURLE_OK);
237 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
238 CURLPROTO_HTTPS),
239 CURLE_OK);
240 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
241 CURLE_OK);
242 if (check_certificate_ != CertificateChecker::kNone) {
243 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
244 &check_certificate_),
245 CURLE_OK);
246 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
247 CertificateChecker::ProcessSSLContext),
248 CURLE_OK);
249 }
250}
251
252
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000253// Begins the transfer, which must not have already been started.
254void LibcurlHttpFetcher::BeginTransfer(const std::string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800255 CHECK(!transfer_in_progress_);
256 url_ = url;
257 if (!ResolveProxiesForUrl(
258 url_,
259 NewCallback(this, &LibcurlHttpFetcher::ProxiesResolved))) {
260 LOG(ERROR) << "Couldn't resolve proxies";
261 if (delegate_)
262 delegate_->TransferComplete(this, false);
263 }
264}
265
266void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000267 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000268 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700269 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800270 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700271 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800272 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700273 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800274 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700275 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000276}
277
Darin Petkov9ce452b2010-11-17 14:33:28 -0800278void LibcurlHttpFetcher::ForceTransferTermination() {
279 CleanUp();
280 if (delegate_) {
281 // Note that after the callback returns this object may be destroyed.
282 delegate_->TransferTerminated(this);
283 }
284}
285
rspangler@google.com49fdf182009-10-10 00:57:34 +0000286void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800287 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700288 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800289 } else {
290 ForceTransferTermination();
291 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292}
293
Andrew de los Reyescb319332010-07-19 10:55:01 -0700294void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000295 CHECK(transfer_in_progress_);
296 int running_handles = 0;
297 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
298
299 // libcurl may request that we immediately call curl_multi_perform after it
300 // returns, so we do. libcurl promises that curl_multi_perform will not block.
301 while (CURLM_CALL_MULTI_PERFORM == retcode) {
302 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700303 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800304 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700305 return;
306 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000307 }
308 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700309 GetHttpResponseCode();
310 if (http_response_code_) {
311 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800312 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700313 } else {
314 LOG(ERROR) << "Unable to get http response code.";
315 }
Darin Petkov192ced42010-07-23 16:20:24 -0700316
rspangler@google.com49fdf182009-10-10 00:57:34 +0000317 // we're done!
318 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000319
Darin Petkova0929552010-11-29 14:19:06 -0800320 // TODO(petkov): This temporary code tries to deal with the case where the
321 // update engine performs an update check while the network is not ready
322 // (e.g., right after resume). Longer term, we should check if the network
323 // is online/offline and return an appropriate error code.
324 if (!sent_byte_ &&
325 http_response_code_ == 0 &&
326 no_network_retry_count_ < no_network_max_retries_) {
327 no_network_retry_count_++;
328 g_timeout_add_seconds(kNoNetworkRetrySeconds,
329 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
330 this);
331 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
332 return;
333 }
334
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800335 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800336 // The transfer completed w/ error and we didn't get any bytes.
337 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800338 //
339 // TODO(garnold) in fact there are two separate cases here: one case is an
340 // other-than-success return code (including no return code) and no
341 // received bytes, which is necessary due to the way callbacks are
342 // currently processing error conditions; the second is an explicit HTTP
343 // error code, where some data may have been received (as in the case of a
344 // semi-successful multi-chunk fetch). This is a confusing behavior and
345 // should be unified into a complete, coherent interface.
346 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
347 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800348
349 PopProxy(); // Delete the proxy we just gave up on.
350
351 if (HasProxy()) {
352 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700353 LOG(INFO) << "Retrying with next proxy setting";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800354 g_idle_add(&LibcurlHttpFetcher::StaticRetryTimeoutCallback, this);
355 } else {
356 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800357 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800358 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800359 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800360 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800361 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700362 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700363 LOG(INFO) << "Transfer interrupted after downloading "
364 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
365 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
366 << "after " << retry_count_ << " attempt(s)";
367
368 if (retry_count_ > max_retry_count_) {
369 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700370 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800371 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700372 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700373 // Need to restart transfer
374 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Darin Petkovb83371f2010-08-17 09:34:49 -0700375 g_timeout_add_seconds(retry_seconds_,
Darin Petkov9b111652010-08-16 11:46:25 -0700376 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
377 this);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700378 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000379 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800380 LOG(INFO) << "Transfer completed (" << http_response_code_
381 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000382 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800383 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700384 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000385 }
386 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000387 } else {
388 // set up callback
389 SetupMainloopSources();
390 }
391}
392
393size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800394 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700395 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800396 const size_t payload_size = size * nmemb;
397
398 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800399 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800400 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
401 << ") or no payload (" << payload_size << "), nothing to do";
402 return 0;
403 }
404
405 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000406 {
407 double transfer_size_double;
408 CHECK_EQ(curl_easy_getinfo(curl_handle_,
409 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
410 &transfer_size_double), CURLE_OK);
411 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
412 if (new_transfer_size > 0) {
413 transfer_size_ = resume_offset_ + new_transfer_size;
414 }
415 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800416 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700417 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000418 if (delegate_)
Gilad Arnold48085ba2011-11-16 09:36:08 -0800419 delegate_->ReceivedBytes(this, reinterpret_cast<char*>(ptr), payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700420 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800421 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000422}
423
424void LibcurlHttpFetcher::Pause() {
425 CHECK(curl_handle_);
426 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000427 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000428}
429
430void LibcurlHttpFetcher::Unpause() {
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_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000434}
435
436// This method sets up callbacks with the glib main loop.
437void LibcurlHttpFetcher::SetupMainloopSources() {
438 fd_set fd_read;
439 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700440 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000441
442 FD_ZERO(&fd_read);
443 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700444 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000445
446 int fd_max = 0;
447
448 // Ask libcurl for the set of file descriptors we should track on its
449 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000450 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700451 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000452
453 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700454 // the highest one we're tracking, whichever is larger.
455 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
456 if (!io_channels_[t].empty())
457 fd_max = max(fd_max, io_channels_[t].rbegin()->first);
458 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000459
Darin Petkov60e14152010-10-27 16:57:04 -0700460 // For each fd, if we're not tracking it, track it. If we are tracking it, but
461 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
462 // there should be exactly as many GIOChannel objects in io_channels_[0|1] as
463 // there are read/write fds that we're tracking.
464 for (int fd = 0; fd <= fd_max; ++fd) {
465 // Note that fd_exc is unused in the current version of libcurl so is_exc
466 // should always be false.
467 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
468 bool must_track[2] = {
469 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
470 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
471 };
472
473 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
474 bool tracked = io_channels_[t].find(fd) != io_channels_[t].end();
475
476 if (!must_track[t]) {
477 // If we have an outstanding io_channel, remove it.
478 if (tracked) {
479 g_source_remove(io_channels_[t][fd].second);
480 g_io_channel_unref(io_channels_[t][fd].first);
481 io_channels_[t].erase(io_channels_[t].find(fd));
482 }
483 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484 }
Darin Petkov60e14152010-10-27 16:57:04 -0700485
486 // If we are already tracking this fd, continue -- nothing to do.
487 if (tracked)
488 continue;
489
490 // Set conditions appropriately -- read for track 0, write for track 1.
491 GIOCondition condition = static_cast<GIOCondition>(
492 ((t == 0) ? (G_IO_IN | G_IO_PRI) : G_IO_OUT) | G_IO_ERR | G_IO_HUP);
493
494 // Track a new fd.
495 GIOChannel* io_channel = g_io_channel_unix_new(fd);
496 guint tag =
497 g_io_add_watch(io_channel, condition, &StaticFDCallback, this);
498
499 io_channels_[t][fd] = make_pair(io_channel, tag);
500 static int io_counter = 0;
501 io_counter++;
502 if (io_counter % 50 == 0) {
503 LOG(INFO) << "io_counter = " << io_counter;
504 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700505 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000506 }
507
Darin Petkovb83371f2010-08-17 09:34:49 -0700508 // Set up a timeout callback for libcurl.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700509 if (!timeout_source_) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700510 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
511 timeout_source_ = g_timeout_source_new_seconds(idle_seconds_);
512 g_source_set_callback(timeout_source_, StaticTimeoutCallback, this, NULL);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700513 g_source_attach(timeout_source_, NULL);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000514 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000515}
516
517bool LibcurlHttpFetcher::FDCallback(GIOChannel *source,
518 GIOCondition condition) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700519 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700520 // We handle removing of this source elsewhere, so we always return true.
521 // The docs say, "the function should return FALSE if the event source
522 // should be removed."
523 // http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html#GIOFunc
524 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000525}
526
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700527gboolean LibcurlHttpFetcher::RetryTimeoutCallback() {
528 ResumeTransfer(url_);
529 CurlPerformOnce();
530 return FALSE; // Don't have glib auto call this callback again
531}
532
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700533gboolean LibcurlHttpFetcher::TimeoutCallback() {
Andrew de los Reyescb319332010-07-19 10:55:01 -0700534 // We always return true, even if we don't want glib to call us back.
535 // We will remove the event source separately if we don't want to
536 // be called back.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700537 if (!transfer_in_progress_)
538 return TRUE;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700539 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700540 return TRUE;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000541}
542
543void LibcurlHttpFetcher::CleanUp() {
544 if (timeout_source_) {
545 g_source_destroy(timeout_source_);
546 timeout_source_ = NULL;
547 }
548
Darin Petkov60e14152010-10-27 16:57:04 -0700549 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
550 for (IOChannels::iterator it = io_channels_[t].begin();
551 it != io_channels_[t].end(); ++it) {
552 g_source_remove(it->second.second);
553 g_io_channel_unref(it->second.first);
554 }
555 io_channels_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000556 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000557
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800558 if (curl_http_headers_) {
559 curl_slist_free_all(curl_http_headers_);
560 curl_http_headers_ = NULL;
561 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000562 if (curl_handle_) {
563 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000564 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
565 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000566 }
567 curl_easy_cleanup(curl_handle_);
568 curl_handle_ = NULL;
569 }
570 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000571 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000572 curl_multi_handle_ = NULL;
573 }
574 transfer_in_progress_ = false;
575}
576
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700577void LibcurlHttpFetcher::GetHttpResponseCode() {
578 long http_response_code = 0;
579 if (curl_easy_getinfo(curl_handle_,
580 CURLINFO_RESPONSE_CODE,
581 &http_response_code) == CURLE_OK) {
582 http_response_code_ = static_cast<int>(http_response_code);
583 }
584}
585
rspangler@google.com49fdf182009-10-10 00:57:34 +0000586} // namespace chromeos_update_engine