blob: 7c40cba6d1b0f024b08de85c8c86804d45cfc7d4 [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>
Gilad Arnolde4ad2502011-12-29 17:08:54 -080011#include <base/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070012
Bruno Rocha7f9aea22011-09-12 14:31:24 -070013#include "update_engine/certificate_checker.h"
Andrew de los Reyes45168102010-11-22 11:13:50 -080014#include "update_engine/chrome_proxy_resolver.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070015#include "update_engine/dbus_interface.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070016#include "update_engine/utils.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000017
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080018using google::protobuf::NewCallback;
adlr@google.comc98a7ed2009-12-04 18:54:03 +000019using std::max;
20using std::make_pair;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070021using std::string;
rspangler@google.com49fdf182009-10-10 00:57:34 +000022
23// This is a concrete implementation of HttpFetcher that uses libcurl to do the
24// http work.
25
26namespace chromeos_update_engine {
27
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070028namespace {
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080029const int kNoNetworkRetrySeconds = 10;
Ken Mixterb2bf1222010-11-18 17:29:38 -080030const char kCACertificatesPath[] = "/usr/share/chromeos-ca-certificates";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070031} // namespace {}
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070032
Don Garrettd186e632012-06-13 13:40:21 -070033const int LibcurlHttpFetcher::kMaxRedirects = 10;
34const int LibcurlHttpFetcher::kMaxRetryCountOobeComplete = 20;
35const int LibcurlHttpFetcher::kMaxRetryCountOobeNotComplete = 3;
36
rspangler@google.com49fdf182009-10-10 00:57:34 +000037LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080038 LOG_IF(ERROR, transfer_in_progress_)
39 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000040 CleanUp();
41}
42
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070043// On error, returns false.
Jay Srinivasan43488792012-06-19 00:25:31 -070044bool LibcurlHttpFetcher::IsUpdateAllowedOverCurrentConnection() const {
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070045 NetworkConnectionType type;
46 ConcreteDbusGlib dbus_iface;
Jay Srinivasan43488792012-06-19 00:25:31 -070047 ConnectionManager* connection_manager = system_state_->GetConnectionManager();
48 TEST_AND_RETURN_FALSE(connection_manager->GetConnectionType(&dbus_iface,
49 &type));
50 bool is_allowed = connection_manager->IsUpdateAllowedOver(type);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070051 LOG(INFO) << "We are connected via "
Jay Srinivasan43488792012-06-19 00:25:31 -070052 << connection_manager->StringForConnectionType(type)
53 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
54 return is_allowed;
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070055}
56
Darin Petkovfc7a0ce2010-10-25 10:38:37 -070057bool LibcurlHttpFetcher::IsOfficialBuild() const {
58 return force_build_type_ ? forced_official_build_ : utils::IsOfficialBuild();
59}
60
adlr@google.comc98a7ed2009-12-04 18:54:03 +000061void LibcurlHttpFetcher::ResumeTransfer(const std::string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070062 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000063 CHECK(!transfer_in_progress_);
64 url_ = url;
65 curl_multi_handle_ = curl_multi_init();
66 CHECK(curl_multi_handle_);
67
68 curl_handle_ = curl_easy_init();
69 CHECK(curl_handle_);
70
Andrew de los Reyes45168102010-11-22 11:13:50 -080071 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070072 bool is_direct = (GetCurrentProxy() == kNoProxy);
73 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
74 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080075 CHECK_EQ(curl_easy_setopt(curl_handle_,
76 CURLOPT_PROXY,
77 ""), CURLE_OK);
78 } else {
79 CHECK_EQ(curl_easy_setopt(curl_handle_,
80 CURLOPT_PROXY,
81 GetCurrentProxy().c_str()), CURLE_OK);
82 // Curl seems to require us to set the protocol
83 curl_proxytype type;
84 if (ChromeProxyResolver::GetProxyType(GetCurrentProxy(), &type)) {
85 CHECK_EQ(curl_easy_setopt(curl_handle_,
86 CURLOPT_PROXYTYPE,
87 type), CURLE_OK);
88 }
89 }
90
rspangler@google.com49fdf182009-10-10 00:57:34 +000091 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000092 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
93 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
94 &post_data_[0]),
95 CURLE_OK);
96 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
97 post_data_.size()),
98 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -080099
100 // Set the Content-Type HTTP header, if one was specifically set.
101 CHECK(!curl_http_headers_);
102 if (post_content_type_ != kHttpContentTypeUnspecified) {
103 const string content_type_attr =
104 base::StringPrintf("Content-Type: %s",
105 GetHttpContentTypeString(post_content_type_));
106 curl_http_headers_ = curl_slist_append(NULL, content_type_attr.c_str());
107 CHECK(curl_http_headers_);
108 CHECK_EQ(
109 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
110 curl_http_headers_),
111 CURLE_OK);
112 } else {
113 LOG(WARNING) << "no content type set, using libcurl default";
114 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000115 }
116
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800117 if (bytes_downloaded_ > 0 || download_length_) {
118 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000119 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800120 CHECK_GE(resume_offset_, 0);
121
122 // Compute end offset, if one is specified. As per HTTP specification, this
123 // is an inclusive boundary. Make sure it doesn't overflow.
124 size_t end_offset = 0;
125 if (download_length_) {
126 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
127 CHECK_LE((size_t) resume_offset_, end_offset);
128 }
129
130 // Create a string representation of the desired range.
131 std::string range_str = (end_offset ?
132 StringPrintf("%jd-%zu", resume_offset_,
133 end_offset) :
134 StringPrintf("%jd-", resume_offset_));
135 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
136 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000137 }
138
139 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
140 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
141 StaticLibcurlWrite), CURLE_OK);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700142
143 string url_to_use(url_);
Jay Srinivasan43488792012-06-19 00:25:31 -0700144 if (!IsUpdateAllowedOverCurrentConnection()) {
145 LOG(INFO) << "Not initiating HTTP connection b/c updates are disabled "
146 << "over this connection";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700147 url_to_use = ""; // Sabotage the URL
148 }
149
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700150 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_to_use.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700151 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700152
Darin Petkov192ced42010-07-23 16:20:24 -0700153 // If the connection drops under 10 bytes/sec for 3 minutes, reconnect.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700154 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT, 10),
155 CURLE_OK);
Andrew de los Reyes2a0fd742011-04-06 11:04:53 -0700156 // Use a smaller timeout on official builds, larger for dev. Dev users
157 // want a longer timeout b/c they may be waiting on the dev server to
158 // build an image.
159 const int kTimeout = IsOfficialBuild() ? 90 : 3 * 60;
160 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME, kTimeout),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700161 CURLE_OK);
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700162 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT, 30),
163 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700164
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700165 // By default, libcurl doesn't follow redirections. Allow up to
166 // |kMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700167 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700168 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kMaxRedirects),
169 CURLE_OK);
170
Darin Petkove237d192010-11-16 10:26:08 -0800171 // Security lock-down in official builds: makes sure that peer certificate
172 // verification is enabled, restricts the set of trusted certificates,
173 // restricts protocols to HTTPS, restricts ciphers to HIGH.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700174 if (!is_test_mode_ && IsOfficialBuild()) {
Darin Petkove237d192010-11-16 10:26:08 -0800175 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
176 CURLE_OK);
177 CHECK_EQ(curl_easy_setopt(curl_handle_,
178 CURLOPT_CAPATH,
179 kCACertificatesPath),
180 CURLE_OK);
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700181 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
182 CURLE_OK);
183 CHECK_EQ(curl_easy_setopt(curl_handle_,
184 CURLOPT_REDIR_PROTOCOLS,
185 CURLPROTO_HTTPS),
186 CURLE_OK);
Andrew de los Reyes33676192010-11-29 19:41:39 -0800187 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST,
188 "HIGH:!ADH"),
Darin Petkove237d192010-11-16 10:26:08 -0800189 CURLE_OK);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700190 if (check_certificate_ != CertificateChecker::kNone) {
191 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
192 &check_certificate_),
193 CURLE_OK);
194 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
195 CertificateChecker::ProcessSSLContext),
196 CURLE_OK);
197 }
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700198 }
199
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000200 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000201 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000202}
203
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000204// Begins the transfer, which must not have already been started.
205void LibcurlHttpFetcher::BeginTransfer(const std::string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800206 CHECK(!transfer_in_progress_);
207 url_ = url;
208 if (!ResolveProxiesForUrl(
209 url_,
210 NewCallback(this, &LibcurlHttpFetcher::ProxiesResolved))) {
211 LOG(ERROR) << "Couldn't resolve proxies";
212 if (delegate_)
213 delegate_->TransferComplete(this, false);
214 }
215}
216
217void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000218 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000219 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700220 retry_count_ = 0;
Jay Srinivasan08fce042012-06-07 16:31:01 -0700221 max_retry_count_ = (system_state_->IsOOBEComplete() ?
222 kMaxRetryCountOobeComplete :
223 kMaxRetryCountOobeNotComplete);
Darin Petkova0929552010-11-29 14:19:06 -0800224 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700225 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800226 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700227 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800228 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700229 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000230}
231
Darin Petkov9ce452b2010-11-17 14:33:28 -0800232void LibcurlHttpFetcher::ForceTransferTermination() {
233 CleanUp();
234 if (delegate_) {
235 // Note that after the callback returns this object may be destroyed.
236 delegate_->TransferTerminated(this);
237 }
238}
239
rspangler@google.com49fdf182009-10-10 00:57:34 +0000240void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800241 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700242 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800243 } else {
244 ForceTransferTermination();
245 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000246}
247
Andrew de los Reyescb319332010-07-19 10:55:01 -0700248void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000249 CHECK(transfer_in_progress_);
250 int running_handles = 0;
251 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
252
253 // libcurl may request that we immediately call curl_multi_perform after it
254 // returns, so we do. libcurl promises that curl_multi_perform will not block.
255 while (CURLM_CALL_MULTI_PERFORM == retcode) {
256 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700257 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800258 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700259 return;
260 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000261 }
262 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700263 GetHttpResponseCode();
264 if (http_response_code_) {
265 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800266 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700267 } else {
268 LOG(ERROR) << "Unable to get http response code.";
269 }
Darin Petkov192ced42010-07-23 16:20:24 -0700270
rspangler@google.com49fdf182009-10-10 00:57:34 +0000271 // we're done!
272 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000273
Darin Petkova0929552010-11-29 14:19:06 -0800274 // TODO(petkov): This temporary code tries to deal with the case where the
275 // update engine performs an update check while the network is not ready
276 // (e.g., right after resume). Longer term, we should check if the network
277 // is online/offline and return an appropriate error code.
278 if (!sent_byte_ &&
279 http_response_code_ == 0 &&
280 no_network_retry_count_ < no_network_max_retries_) {
281 no_network_retry_count_++;
282 g_timeout_add_seconds(kNoNetworkRetrySeconds,
283 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
284 this);
285 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
286 return;
287 }
288
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800289 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800290 // The transfer completed w/ error and we didn't get any bytes.
291 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800292 //
293 // TODO(garnold) in fact there are two separate cases here: one case is an
294 // other-than-success return code (including no return code) and no
295 // received bytes, which is necessary due to the way callbacks are
296 // currently processing error conditions; the second is an explicit HTTP
297 // error code, where some data may have been received (as in the case of a
298 // semi-successful multi-chunk fetch). This is a confusing behavior and
299 // should be unified into a complete, coherent interface.
300 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
301 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800302
303 PopProxy(); // Delete the proxy we just gave up on.
304
305 if (HasProxy()) {
306 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700307 LOG(INFO) << "Retrying with next proxy setting";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800308 g_idle_add(&LibcurlHttpFetcher::StaticRetryTimeoutCallback, this);
309 } else {
310 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800311 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800312 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800313 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800314 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800315 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700316 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700317 LOG(INFO) << "Transfer interrupted after downloading "
318 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
319 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
320 << "after " << retry_count_ << " attempt(s)";
321
322 if (retry_count_ > max_retry_count_) {
323 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700324 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800325 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700326 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700327 // Need to restart transfer
328 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Darin Petkovb83371f2010-08-17 09:34:49 -0700329 g_timeout_add_seconds(retry_seconds_,
Darin Petkov9b111652010-08-16 11:46:25 -0700330 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
331 this);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700332 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000333 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800334 LOG(INFO) << "Transfer completed (" << http_response_code_
335 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000336 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800337 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700338 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000339 }
340 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000341 } else {
342 // set up callback
343 SetupMainloopSources();
344 }
345}
346
347size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800348 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700349 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800350 const size_t payload_size = size * nmemb;
351
352 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800353 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800354 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
355 << ") or no payload (" << payload_size << "), nothing to do";
356 return 0;
357 }
358
359 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000360 {
361 double transfer_size_double;
362 CHECK_EQ(curl_easy_getinfo(curl_handle_,
363 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
364 &transfer_size_double), CURLE_OK);
365 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
366 if (new_transfer_size > 0) {
367 transfer_size_ = resume_offset_ + new_transfer_size;
368 }
369 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800370 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700371 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000372 if (delegate_)
Gilad Arnold48085ba2011-11-16 09:36:08 -0800373 delegate_->ReceivedBytes(this, reinterpret_cast<char*>(ptr), payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700374 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800375 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000376}
377
378void LibcurlHttpFetcher::Pause() {
379 CHECK(curl_handle_);
380 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000381 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000382}
383
384void LibcurlHttpFetcher::Unpause() {
385 CHECK(curl_handle_);
386 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000387 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000388}
389
390// This method sets up callbacks with the glib main loop.
391void LibcurlHttpFetcher::SetupMainloopSources() {
392 fd_set fd_read;
393 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700394 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000395
396 FD_ZERO(&fd_read);
397 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700398 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000399
400 int fd_max = 0;
401
402 // Ask libcurl for the set of file descriptors we should track on its
403 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000404 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700405 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000406
407 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700408 // the highest one we're tracking, whichever is larger.
409 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
410 if (!io_channels_[t].empty())
411 fd_max = max(fd_max, io_channels_[t].rbegin()->first);
412 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000413
Darin Petkov60e14152010-10-27 16:57:04 -0700414 // For each fd, if we're not tracking it, track it. If we are tracking it, but
415 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
416 // there should be exactly as many GIOChannel objects in io_channels_[0|1] as
417 // there are read/write fds that we're tracking.
418 for (int fd = 0; fd <= fd_max; ++fd) {
419 // Note that fd_exc is unused in the current version of libcurl so is_exc
420 // should always be false.
421 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
422 bool must_track[2] = {
423 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
424 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
425 };
426
427 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
428 bool tracked = io_channels_[t].find(fd) != io_channels_[t].end();
429
430 if (!must_track[t]) {
431 // If we have an outstanding io_channel, remove it.
432 if (tracked) {
433 g_source_remove(io_channels_[t][fd].second);
434 g_io_channel_unref(io_channels_[t][fd].first);
435 io_channels_[t].erase(io_channels_[t].find(fd));
436 }
437 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000438 }
Darin Petkov60e14152010-10-27 16:57:04 -0700439
440 // If we are already tracking this fd, continue -- nothing to do.
441 if (tracked)
442 continue;
443
444 // Set conditions appropriately -- read for track 0, write for track 1.
445 GIOCondition condition = static_cast<GIOCondition>(
446 ((t == 0) ? (G_IO_IN | G_IO_PRI) : G_IO_OUT) | G_IO_ERR | G_IO_HUP);
447
448 // Track a new fd.
449 GIOChannel* io_channel = g_io_channel_unix_new(fd);
450 guint tag =
451 g_io_add_watch(io_channel, condition, &StaticFDCallback, this);
452
453 io_channels_[t][fd] = make_pair(io_channel, tag);
454 static int io_counter = 0;
455 io_counter++;
456 if (io_counter % 50 == 0) {
457 LOG(INFO) << "io_counter = " << io_counter;
458 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700459 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000460 }
461
Darin Petkovb83371f2010-08-17 09:34:49 -0700462 // Set up a timeout callback for libcurl.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700463 if (!timeout_source_) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700464 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
465 timeout_source_ = g_timeout_source_new_seconds(idle_seconds_);
466 g_source_set_callback(timeout_source_, StaticTimeoutCallback, this, NULL);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700467 g_source_attach(timeout_source_, NULL);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000468 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000469}
470
471bool LibcurlHttpFetcher::FDCallback(GIOChannel *source,
472 GIOCondition condition) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700473 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700474 // We handle removing of this source elsewhere, so we always return true.
475 // The docs say, "the function should return FALSE if the event source
476 // should be removed."
477 // http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html#GIOFunc
478 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000479}
480
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700481gboolean LibcurlHttpFetcher::RetryTimeoutCallback() {
482 ResumeTransfer(url_);
483 CurlPerformOnce();
484 return FALSE; // Don't have glib auto call this callback again
485}
486
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700487gboolean LibcurlHttpFetcher::TimeoutCallback() {
Andrew de los Reyescb319332010-07-19 10:55:01 -0700488 // We always return true, even if we don't want glib to call us back.
489 // We will remove the event source separately if we don't want to
490 // be called back.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700491 if (!transfer_in_progress_)
492 return TRUE;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700493 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700494 return TRUE;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495}
496
497void LibcurlHttpFetcher::CleanUp() {
498 if (timeout_source_) {
499 g_source_destroy(timeout_source_);
500 timeout_source_ = NULL;
501 }
502
Darin Petkov60e14152010-10-27 16:57:04 -0700503 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
504 for (IOChannels::iterator it = io_channels_[t].begin();
505 it != io_channels_[t].end(); ++it) {
506 g_source_remove(it->second.second);
507 g_io_channel_unref(it->second.first);
508 }
509 io_channels_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000510 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000511
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800512 if (curl_http_headers_) {
513 curl_slist_free_all(curl_http_headers_);
514 curl_http_headers_ = NULL;
515 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000516 if (curl_handle_) {
517 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000518 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
519 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000520 }
521 curl_easy_cleanup(curl_handle_);
522 curl_handle_ = NULL;
523 }
524 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000525 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526 curl_multi_handle_ = NULL;
527 }
528 transfer_in_progress_ = false;
529}
530
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700531void LibcurlHttpFetcher::GetHttpResponseCode() {
532 long http_response_code = 0;
533 if (curl_easy_getinfo(curl_handle_,
534 CURLINFO_RESPONSE_CODE,
535 &http_response_code) == CURLE_OK) {
536 http_response_code_ = static_cast<int>(http_response_code);
537 }
538}
539
rspangler@google.com49fdf182009-10-10 00:57:34 +0000540} // namespace chromeos_update_engine