blob: 59f065e911446c73070d60d944833eafc4285ad8 [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>
Jay Srinivasan738fdf32012-12-07 17:40:54 -080011#include <base/string_util.h>
Gilad Arnolde4ad2502011-12-29 17:08:54 -080012#include <base/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"
Andrew de los Reyes45168102010-11-22 11:13:50 -080015#include "update_engine/chrome_proxy_resolver.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070016#include "update_engine/dbus_interface.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
Don Garrettd186e632012-06-13 13:40:21 -070034const int LibcurlHttpFetcher::kMaxRedirects = 10;
35const int LibcurlHttpFetcher::kMaxRetryCountOobeComplete = 20;
36const int LibcurlHttpFetcher::kMaxRetryCountOobeNotComplete = 3;
37
rspangler@google.com49fdf182009-10-10 00:57:34 +000038LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080039 LOG_IF(ERROR, transfer_in_progress_)
40 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000041 CleanUp();
42}
43
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070044// On error, returns false.
Jay Srinivasan43488792012-06-19 00:25:31 -070045bool LibcurlHttpFetcher::IsUpdateAllowedOverCurrentConnection() const {
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070046 NetworkConnectionType type;
47 ConcreteDbusGlib dbus_iface;
Jay Srinivasan43488792012-06-19 00:25:31 -070048 ConnectionManager* connection_manager = system_state_->GetConnectionManager();
49 TEST_AND_RETURN_FALSE(connection_manager->GetConnectionType(&dbus_iface,
50 &type));
51 bool is_allowed = connection_manager->IsUpdateAllowedOver(type);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070052 LOG(INFO) << "We are connected via "
Jay Srinivasan43488792012-06-19 00:25:31 -070053 << connection_manager->StringForConnectionType(type)
54 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
55 return is_allowed;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070056}
57
Darin Petkovfc7a0ce2010-10-25 10:38:37 -070058bool LibcurlHttpFetcher::IsOfficialBuild() const {
59 return force_build_type_ ? forced_official_build_ : utils::IsOfficialBuild();
60}
61
adlr@google.comc98a7ed2009-12-04 18:54:03 +000062void LibcurlHttpFetcher::ResumeTransfer(const std::string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070063 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000064 CHECK(!transfer_in_progress_);
65 url_ = url;
66 curl_multi_handle_ = curl_multi_init();
67 CHECK(curl_multi_handle_);
68
69 curl_handle_ = curl_easy_init();
70 CHECK(curl_handle_);
71
Andrew de los Reyes45168102010-11-22 11:13:50 -080072 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070073 bool is_direct = (GetCurrentProxy() == kNoProxy);
74 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
75 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080076 CHECK_EQ(curl_easy_setopt(curl_handle_,
77 CURLOPT_PROXY,
78 ""), CURLE_OK);
79 } else {
80 CHECK_EQ(curl_easy_setopt(curl_handle_,
81 CURLOPT_PROXY,
82 GetCurrentProxy().c_str()), CURLE_OK);
83 // Curl seems to require us to set the protocol
84 curl_proxytype type;
85 if (ChromeProxyResolver::GetProxyType(GetCurrentProxy(), &type)) {
86 CHECK_EQ(curl_easy_setopt(curl_handle_,
87 CURLOPT_PROXYTYPE,
88 type), CURLE_OK);
89 }
90 }
91
rspangler@google.com49fdf182009-10-10 00:57:34 +000092 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000093 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
94 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
95 &post_data_[0]),
96 CURLE_OK);
97 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
98 post_data_.size()),
99 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800100
101 // Set the Content-Type HTTP header, if one was specifically set.
102 CHECK(!curl_http_headers_);
103 if (post_content_type_ != kHttpContentTypeUnspecified) {
104 const string content_type_attr =
105 base::StringPrintf("Content-Type: %s",
106 GetHttpContentTypeString(post_content_type_));
107 curl_http_headers_ = curl_slist_append(NULL, content_type_attr.c_str());
108 CHECK(curl_http_headers_);
109 CHECK_EQ(
110 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
111 curl_http_headers_),
112 CURLE_OK);
113 } else {
114 LOG(WARNING) << "no content type set, using libcurl default";
115 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000116 }
117
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800118 if (bytes_downloaded_ > 0 || download_length_) {
119 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000120 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800121 CHECK_GE(resume_offset_, 0);
122
123 // Compute end offset, if one is specified. As per HTTP specification, this
124 // is an inclusive boundary. Make sure it doesn't overflow.
125 size_t end_offset = 0;
126 if (download_length_) {
127 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
128 CHECK_LE((size_t) resume_offset_, end_offset);
129 }
130
131 // Create a string representation of the desired range.
132 std::string range_str = (end_offset ?
133 StringPrintf("%jd-%zu", resume_offset_,
134 end_offset) :
135 StringPrintf("%jd-", resume_offset_));
136 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
137 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000138 }
139
140 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
141 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
142 StaticLibcurlWrite), CURLE_OK);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700143
144 string url_to_use(url_);
Jay Srinivasan43488792012-06-19 00:25:31 -0700145 if (!IsUpdateAllowedOverCurrentConnection()) {
146 LOG(INFO) << "Not initiating HTTP connection b/c updates are disabled "
147 << "over this connection";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700148 url_to_use = ""; // Sabotage the URL
149 }
150
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700151 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_to_use.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700152 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700153
Darin Petkov192ced42010-07-23 16:20:24 -0700154 // If the connection drops under 10 bytes/sec for 3 minutes, reconnect.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700155 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT, 10),
156 CURLE_OK);
Andrew de los Reyes2a0fd742011-04-06 11:04:53 -0700157 // Use a smaller timeout on official builds, larger for dev. Dev users
158 // want a longer timeout b/c they may be waiting on the dev server to
159 // build an image.
160 const int kTimeout = IsOfficialBuild() ? 90 : 3 * 60;
161 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME, kTimeout),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700162 CURLE_OK);
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700163 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT, 30),
164 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700165
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700166 // By default, libcurl doesn't follow redirections. Allow up to
167 // |kMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700168 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700169 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kMaxRedirects),
170 CURLE_OK);
171
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800172 // If we are running in test mode or using a dev/test build, then lock down
173 // the appropriate curl options for HTTP or HTTPS depending on the url.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700174 if (!is_test_mode_ && IsOfficialBuild()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800175 if (StartsWithASCII(url_to_use, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800176 SetCurlOptionsForHttp();
177 else
178 SetCurlOptionsForHttps();
179 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800180 LOG(INFO) << "Not setting http(s) curl options because we are in "
181 << "test mode or running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700182 }
183
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000184 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000185 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000186}
187
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800188// Lock down only the protocol in case of HTTP.
189void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
190 LOG(INFO) << "Setting up curl options for HTTP";
191 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
192 CURLE_OK);
193 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
194 CURLPROTO_HTTP),
195 CURLE_OK);
196}
197
198// Security lock-down in official builds: makes sure that peer certificate
199// verification is enabled, restricts the set of trusted certificates,
200// restricts protocols to HTTPS, restricts ciphers to HIGH.
201void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
202 LOG(INFO) << "Setting up curl options for HTTPS";
203 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
204 CURLE_OK);
205 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH, kCACertificatesPath),
206 CURLE_OK);
207 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
208 CURLE_OK);
209 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
210 CURLPROTO_HTTPS),
211 CURLE_OK);
212 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
213 CURLE_OK);
214 if (check_certificate_ != CertificateChecker::kNone) {
215 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
216 &check_certificate_),
217 CURLE_OK);
218 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
219 CertificateChecker::ProcessSSLContext),
220 CURLE_OK);
221 }
222}
223
224
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000225// Begins the transfer, which must not have already been started.
226void LibcurlHttpFetcher::BeginTransfer(const std::string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800227 CHECK(!transfer_in_progress_);
228 url_ = url;
229 if (!ResolveProxiesForUrl(
230 url_,
231 NewCallback(this, &LibcurlHttpFetcher::ProxiesResolved))) {
232 LOG(ERROR) << "Couldn't resolve proxies";
233 if (delegate_)
234 delegate_->TransferComplete(this, false);
235 }
236}
237
238void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000239 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000240 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700241 retry_count_ = 0;
Jay Srinivasan08fce042012-06-07 16:31:01 -0700242 max_retry_count_ = (system_state_->IsOOBEComplete() ?
243 kMaxRetryCountOobeComplete :
244 kMaxRetryCountOobeNotComplete);
Darin Petkova0929552010-11-29 14:19:06 -0800245 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700246 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800247 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700248 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800249 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700250 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000251}
252
Darin Petkov9ce452b2010-11-17 14:33:28 -0800253void LibcurlHttpFetcher::ForceTransferTermination() {
254 CleanUp();
255 if (delegate_) {
256 // Note that after the callback returns this object may be destroyed.
257 delegate_->TransferTerminated(this);
258 }
259}
260
rspangler@google.com49fdf182009-10-10 00:57:34 +0000261void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800262 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700263 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800264 } else {
265 ForceTransferTermination();
266 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000267}
268
Andrew de los Reyescb319332010-07-19 10:55:01 -0700269void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000270 CHECK(transfer_in_progress_);
271 int running_handles = 0;
272 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
273
274 // libcurl may request that we immediately call curl_multi_perform after it
275 // returns, so we do. libcurl promises that curl_multi_perform will not block.
276 while (CURLM_CALL_MULTI_PERFORM == retcode) {
277 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700278 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800279 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700280 return;
281 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000282 }
283 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700284 GetHttpResponseCode();
285 if (http_response_code_) {
286 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800287 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700288 } else {
289 LOG(ERROR) << "Unable to get http response code.";
290 }
Darin Petkov192ced42010-07-23 16:20:24 -0700291
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292 // we're done!
293 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000294
Darin Petkova0929552010-11-29 14:19:06 -0800295 // TODO(petkov): This temporary code tries to deal with the case where the
296 // update engine performs an update check while the network is not ready
297 // (e.g., right after resume). Longer term, we should check if the network
298 // is online/offline and return an appropriate error code.
299 if (!sent_byte_ &&
300 http_response_code_ == 0 &&
301 no_network_retry_count_ < no_network_max_retries_) {
302 no_network_retry_count_++;
303 g_timeout_add_seconds(kNoNetworkRetrySeconds,
304 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
305 this);
306 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
307 return;
308 }
309
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800310 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800311 // The transfer completed w/ error and we didn't get any bytes.
312 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800313 //
314 // TODO(garnold) in fact there are two separate cases here: one case is an
315 // other-than-success return code (including no return code) and no
316 // received bytes, which is necessary due to the way callbacks are
317 // currently processing error conditions; the second is an explicit HTTP
318 // error code, where some data may have been received (as in the case of a
319 // semi-successful multi-chunk fetch). This is a confusing behavior and
320 // should be unified into a complete, coherent interface.
321 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
322 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800323
324 PopProxy(); // Delete the proxy we just gave up on.
325
326 if (HasProxy()) {
327 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700328 LOG(INFO) << "Retrying with next proxy setting";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800329 g_idle_add(&LibcurlHttpFetcher::StaticRetryTimeoutCallback, this);
330 } else {
331 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800332 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800333 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800334 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800335 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800336 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700337 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700338 LOG(INFO) << "Transfer interrupted after downloading "
339 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
340 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
341 << "after " << retry_count_ << " attempt(s)";
342
343 if (retry_count_ > max_retry_count_) {
344 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700345 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800346 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700347 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700348 // Need to restart transfer
349 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Darin Petkovb83371f2010-08-17 09:34:49 -0700350 g_timeout_add_seconds(retry_seconds_,
Darin Petkov9b111652010-08-16 11:46:25 -0700351 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
352 this);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700353 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000354 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800355 LOG(INFO) << "Transfer completed (" << http_response_code_
356 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000357 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800358 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700359 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000360 }
361 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000362 } else {
363 // set up callback
364 SetupMainloopSources();
365 }
366}
367
368size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800369 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700370 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800371 const size_t payload_size = size * nmemb;
372
373 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800374 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800375 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
376 << ") or no payload (" << payload_size << "), nothing to do";
377 return 0;
378 }
379
380 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000381 {
382 double transfer_size_double;
383 CHECK_EQ(curl_easy_getinfo(curl_handle_,
384 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
385 &transfer_size_double), CURLE_OK);
386 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
387 if (new_transfer_size > 0) {
388 transfer_size_ = resume_offset_ + new_transfer_size;
389 }
390 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800391 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700392 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000393 if (delegate_)
Gilad Arnold48085ba2011-11-16 09:36:08 -0800394 delegate_->ReceivedBytes(this, reinterpret_cast<char*>(ptr), payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700395 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800396 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000397}
398
399void LibcurlHttpFetcher::Pause() {
400 CHECK(curl_handle_);
401 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000402 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000403}
404
405void LibcurlHttpFetcher::Unpause() {
406 CHECK(curl_handle_);
407 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000408 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409}
410
411// This method sets up callbacks with the glib main loop.
412void LibcurlHttpFetcher::SetupMainloopSources() {
413 fd_set fd_read;
414 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700415 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000416
417 FD_ZERO(&fd_read);
418 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700419 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000420
421 int fd_max = 0;
422
423 // Ask libcurl for the set of file descriptors we should track on its
424 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000425 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700426 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000427
428 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700429 // the highest one we're tracking, whichever is larger.
430 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
431 if (!io_channels_[t].empty())
432 fd_max = max(fd_max, io_channels_[t].rbegin()->first);
433 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000434
Darin Petkov60e14152010-10-27 16:57:04 -0700435 // For each fd, if we're not tracking it, track it. If we are tracking it, but
436 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
437 // there should be exactly as many GIOChannel objects in io_channels_[0|1] as
438 // there are read/write fds that we're tracking.
439 for (int fd = 0; fd <= fd_max; ++fd) {
440 // Note that fd_exc is unused in the current version of libcurl so is_exc
441 // should always be false.
442 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
443 bool must_track[2] = {
444 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
445 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
446 };
447
448 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
449 bool tracked = io_channels_[t].find(fd) != io_channels_[t].end();
450
451 if (!must_track[t]) {
452 // If we have an outstanding io_channel, remove it.
453 if (tracked) {
454 g_source_remove(io_channels_[t][fd].second);
455 g_io_channel_unref(io_channels_[t][fd].first);
456 io_channels_[t].erase(io_channels_[t].find(fd));
457 }
458 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000459 }
Darin Petkov60e14152010-10-27 16:57:04 -0700460
461 // If we are already tracking this fd, continue -- nothing to do.
462 if (tracked)
463 continue;
464
465 // Set conditions appropriately -- read for track 0, write for track 1.
466 GIOCondition condition = static_cast<GIOCondition>(
467 ((t == 0) ? (G_IO_IN | G_IO_PRI) : G_IO_OUT) | G_IO_ERR | G_IO_HUP);
468
469 // Track a new fd.
470 GIOChannel* io_channel = g_io_channel_unix_new(fd);
471 guint tag =
472 g_io_add_watch(io_channel, condition, &StaticFDCallback, this);
473
474 io_channels_[t][fd] = make_pair(io_channel, tag);
475 static int io_counter = 0;
476 io_counter++;
477 if (io_counter % 50 == 0) {
478 LOG(INFO) << "io_counter = " << io_counter;
479 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700480 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000481 }
482
Darin Petkovb83371f2010-08-17 09:34:49 -0700483 // Set up a timeout callback for libcurl.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700484 if (!timeout_source_) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700485 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
486 timeout_source_ = g_timeout_source_new_seconds(idle_seconds_);
487 g_source_set_callback(timeout_source_, StaticTimeoutCallback, this, NULL);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700488 g_source_attach(timeout_source_, NULL);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000489 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000490}
491
492bool LibcurlHttpFetcher::FDCallback(GIOChannel *source,
493 GIOCondition condition) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700494 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700495 // We handle removing of this source elsewhere, so we always return true.
496 // The docs say, "the function should return FALSE if the event source
497 // should be removed."
498 // http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html#GIOFunc
499 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000500}
501
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700502gboolean LibcurlHttpFetcher::RetryTimeoutCallback() {
503 ResumeTransfer(url_);
504 CurlPerformOnce();
505 return FALSE; // Don't have glib auto call this callback again
506}
507
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700508gboolean LibcurlHttpFetcher::TimeoutCallback() {
Andrew de los Reyescb319332010-07-19 10:55:01 -0700509 // We always return true, even if we don't want glib to call us back.
510 // We will remove the event source separately if we don't want to
511 // be called back.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700512 if (!transfer_in_progress_)
513 return TRUE;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700514 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700515 return TRUE;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000516}
517
518void LibcurlHttpFetcher::CleanUp() {
519 if (timeout_source_) {
520 g_source_destroy(timeout_source_);
521 timeout_source_ = NULL;
522 }
523
Darin Petkov60e14152010-10-27 16:57:04 -0700524 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
525 for (IOChannels::iterator it = io_channels_[t].begin();
526 it != io_channels_[t].end(); ++it) {
527 g_source_remove(it->second.second);
528 g_io_channel_unref(it->second.first);
529 }
530 io_channels_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000531 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000532
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800533 if (curl_http_headers_) {
534 curl_slist_free_all(curl_http_headers_);
535 curl_http_headers_ = NULL;
536 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000537 if (curl_handle_) {
538 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000539 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
540 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000541 }
542 curl_easy_cleanup(curl_handle_);
543 curl_handle_ = NULL;
544 }
545 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000546 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000547 curl_multi_handle_ = NULL;
548 }
549 transfer_in_progress_ = false;
550}
551
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700552void LibcurlHttpFetcher::GetHttpResponseCode() {
553 long http_response_code = 0;
554 if (curl_easy_getinfo(curl_handle_,
555 CURLINFO_RESPONSE_CODE,
556 &http_response_code) == CURLE_OK) {
557 http_response_code_ = static_cast<int>(http_response_code);
558 }
559}
560
rspangler@google.com49fdf182009-10-10 00:57:34 +0000561} // namespace chromeos_update_engine