blob: abc43891d49165f40dd6db6c148feefa78f8c40f [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"
16#include "update_engine/flimflam_proxy.h"
17#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 {
Gilad Arnold34bf1ee2012-02-09 16:16:02 -080030const int kMaxRetriesCount = 3;
Andrew de los Reyes5d0783d2010-11-29 18:14:16 -080031const int kNoNetworkRetrySeconds = 10;
Ken Mixterb2bf1222010-11-18 17:29:38 -080032const char kCACertificatesPath[] = "/usr/share/chromeos-ca-certificates";
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070033} // namespace {}
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070034
rspangler@google.com49fdf182009-10-10 00:57:34 +000035LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080036 LOG_IF(ERROR, transfer_in_progress_)
37 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000038 CleanUp();
39}
40
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070041// On error, returns false.
42bool LibcurlHttpFetcher::ConnectionIsExpensive() const {
43 if (force_connection_type_)
44 return forced_expensive_connection_;
45 NetworkConnectionType type;
46 ConcreteDbusGlib dbus_iface;
47 TEST_AND_RETURN_FALSE(FlimFlamProxy::GetConnectionType(&dbus_iface, &type));
48 LOG(INFO) << "We are connected via "
49 << FlimFlamProxy::StringForConnectionType(type);
50 return FlimFlamProxy::IsExpensiveConnectionType(type);
51}
52
Darin Petkovfc7a0ce2010-10-25 10:38:37 -070053bool LibcurlHttpFetcher::IsOfficialBuild() const {
54 return force_build_type_ ? forced_official_build_ : utils::IsOfficialBuild();
55}
56
adlr@google.comc98a7ed2009-12-04 18:54:03 +000057void LibcurlHttpFetcher::ResumeTransfer(const std::string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070058 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000059 CHECK(!transfer_in_progress_);
60 url_ = url;
61 curl_multi_handle_ = curl_multi_init();
62 CHECK(curl_multi_handle_);
63
64 curl_handle_ = curl_easy_init();
65 CHECK(curl_handle_);
66
Andrew de los Reyes45168102010-11-22 11:13:50 -080067 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070068 bool is_direct = (GetCurrentProxy() == kNoProxy);
69 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
70 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080071 CHECK_EQ(curl_easy_setopt(curl_handle_,
72 CURLOPT_PROXY,
73 ""), CURLE_OK);
74 } else {
75 CHECK_EQ(curl_easy_setopt(curl_handle_,
76 CURLOPT_PROXY,
77 GetCurrentProxy().c_str()), CURLE_OK);
78 // Curl seems to require us to set the protocol
79 curl_proxytype type;
80 if (ChromeProxyResolver::GetProxyType(GetCurrentProxy(), &type)) {
81 CHECK_EQ(curl_easy_setopt(curl_handle_,
82 CURLOPT_PROXYTYPE,
83 type), CURLE_OK);
84 }
85 }
86
rspangler@google.com49fdf182009-10-10 00:57:34 +000087 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000088 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
89 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
90 &post_data_[0]),
91 CURLE_OK);
92 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
93 post_data_.size()),
94 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -080095
96 // Set the Content-Type HTTP header, if one was specifically set.
97 CHECK(!curl_http_headers_);
98 if (post_content_type_ != kHttpContentTypeUnspecified) {
99 const string content_type_attr =
100 base::StringPrintf("Content-Type: %s",
101 GetHttpContentTypeString(post_content_type_));
102 curl_http_headers_ = curl_slist_append(NULL, content_type_attr.c_str());
103 CHECK(curl_http_headers_);
104 CHECK_EQ(
105 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
106 curl_http_headers_),
107 CURLE_OK);
108 } else {
109 LOG(WARNING) << "no content type set, using libcurl default";
110 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000111 }
112
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800113 if (bytes_downloaded_ > 0 || download_length_) {
114 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000115 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800116 CHECK_GE(resume_offset_, 0);
117
118 // Compute end offset, if one is specified. As per HTTP specification, this
119 // is an inclusive boundary. Make sure it doesn't overflow.
120 size_t end_offset = 0;
121 if (download_length_) {
122 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
123 CHECK_LE((size_t) resume_offset_, end_offset);
124 }
125
126 // Create a string representation of the desired range.
127 std::string range_str = (end_offset ?
128 StringPrintf("%jd-%zu", resume_offset_,
129 end_offset) :
130 StringPrintf("%jd-", resume_offset_));
131 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
132 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000133 }
134
135 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
136 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
137 StaticLibcurlWrite), CURLE_OK);
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700138
139 string url_to_use(url_);
140 if (ConnectionIsExpensive()) {
141 LOG(INFO) << "Not initiating HTTP connection b/c we are on an expensive"
142 << " connection";
143 url_to_use = ""; // Sabotage the URL
144 }
145
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700146 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_to_use.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700147 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700148
Darin Petkov192ced42010-07-23 16:20:24 -0700149 // If the connection drops under 10 bytes/sec for 3 minutes, reconnect.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700150 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT, 10),
151 CURLE_OK);
Andrew de los Reyes2a0fd742011-04-06 11:04:53 -0700152 // Use a smaller timeout on official builds, larger for dev. Dev users
153 // want a longer timeout b/c they may be waiting on the dev server to
154 // build an image.
155 const int kTimeout = IsOfficialBuild() ? 90 : 3 * 60;
156 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME, kTimeout),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700157 CURLE_OK);
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700158 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT, 30),
159 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700160
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700161 // By default, libcurl doesn't follow redirections. Allow up to
162 // |kMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700163 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700164 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kMaxRedirects),
165 CURLE_OK);
166
Darin Petkove237d192010-11-16 10:26:08 -0800167 // Security lock-down in official builds: makes sure that peer certificate
168 // verification is enabled, restricts the set of trusted certificates,
169 // restricts protocols to HTTPS, restricts ciphers to HIGH.
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700170 if (IsOfficialBuild()) {
Darin Petkove237d192010-11-16 10:26:08 -0800171 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
172 CURLE_OK);
173 CHECK_EQ(curl_easy_setopt(curl_handle_,
174 CURLOPT_CAPATH,
175 kCACertificatesPath),
176 CURLE_OK);
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700177 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
178 CURLE_OK);
179 CHECK_EQ(curl_easy_setopt(curl_handle_,
180 CURLOPT_REDIR_PROTOCOLS,
181 CURLPROTO_HTTPS),
182 CURLE_OK);
Andrew de los Reyes33676192010-11-29 19:41:39 -0800183 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST,
184 "HIGH:!ADH"),
Darin Petkove237d192010-11-16 10:26:08 -0800185 CURLE_OK);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700186 if (check_certificate_ != CertificateChecker::kNone) {
187 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
188 &check_certificate_),
189 CURLE_OK);
190 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
191 CertificateChecker::ProcessSSLContext),
192 CURLE_OK);
193 }
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700194 }
195
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000196 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000197 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000198}
199
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000200// Begins the transfer, which must not have already been started.
201void LibcurlHttpFetcher::BeginTransfer(const std::string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800202 CHECK(!transfer_in_progress_);
203 url_ = url;
204 if (!ResolveProxiesForUrl(
205 url_,
206 NewCallback(this, &LibcurlHttpFetcher::ProxiesResolved))) {
207 LOG(ERROR) << "Couldn't resolve proxies";
208 if (delegate_)
209 delegate_->TransferComplete(this, false);
210 }
211}
212
213void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000214 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000215 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700216 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800217 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700218 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800219 terminate_requested_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800220 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700221 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000222}
223
Darin Petkov9ce452b2010-11-17 14:33:28 -0800224void LibcurlHttpFetcher::ForceTransferTermination() {
225 CleanUp();
226 if (delegate_) {
227 // Note that after the callback returns this object may be destroyed.
228 delegate_->TransferTerminated(this);
229 }
230}
231
rspangler@google.com49fdf182009-10-10 00:57:34 +0000232void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800233 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700234 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800235 } else {
236 ForceTransferTermination();
237 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000238}
239
Andrew de los Reyescb319332010-07-19 10:55:01 -0700240void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000241 CHECK(transfer_in_progress_);
242 int running_handles = 0;
243 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
244
245 // libcurl may request that we immediately call curl_multi_perform after it
246 // returns, so we do. libcurl promises that curl_multi_perform will not block.
247 while (CURLM_CALL_MULTI_PERFORM == retcode) {
248 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700249 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800250 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700251 return;
252 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000253 }
254 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700255 GetHttpResponseCode();
256 if (http_response_code_) {
257 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800258 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700259 } else {
260 LOG(ERROR) << "Unable to get http response code.";
261 }
Darin Petkov192ced42010-07-23 16:20:24 -0700262
rspangler@google.com49fdf182009-10-10 00:57:34 +0000263 // we're done!
264 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000265
Darin Petkova0929552010-11-29 14:19:06 -0800266 // TODO(petkov): This temporary code tries to deal with the case where the
267 // update engine performs an update check while the network is not ready
268 // (e.g., right after resume). Longer term, we should check if the network
269 // is online/offline and return an appropriate error code.
270 if (!sent_byte_ &&
271 http_response_code_ == 0 &&
272 no_network_retry_count_ < no_network_max_retries_) {
273 no_network_retry_count_++;
274 g_timeout_add_seconds(kNoNetworkRetrySeconds,
275 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
276 this);
277 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
278 return;
279 }
280
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800281 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800282 // The transfer completed w/ error and we didn't get any bytes.
283 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800284 //
285 // TODO(garnold) in fact there are two separate cases here: one case is an
286 // other-than-success return code (including no return code) and no
287 // received bytes, which is necessary due to the way callbacks are
288 // currently processing error conditions; the second is an explicit HTTP
289 // error code, where some data may have been received (as in the case of a
290 // semi-successful multi-chunk fetch). This is a confusing behavior and
291 // should be unified into a complete, coherent interface.
292 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
293 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800294
295 PopProxy(); // Delete the proxy we just gave up on.
296
297 if (HasProxy()) {
298 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700299 LOG(INFO) << "Retrying with next proxy setting";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800300 g_idle_add(&LibcurlHttpFetcher::StaticRetryTimeoutCallback, this);
301 } else {
302 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800303 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800304 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800305 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800306 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800307 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700308 // Need to restart transfer
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700309 retry_count_++;
310 LOG(INFO) << "Restarting transfer b/c we finished, had downloaded "
311 << bytes_downloaded_ << " bytes, but transfer_size_ is "
312 << transfer_size_ << ". retry_count: " << retry_count_;
313 if (retry_count_ > kMaxRetriesCount) {
314 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800315 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700316 } else {
Darin Petkovb83371f2010-08-17 09:34:49 -0700317 g_timeout_add_seconds(retry_seconds_,
Darin Petkov9b111652010-08-16 11:46:25 -0700318 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
319 this);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700320 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000321 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800322 LOG(INFO) << "Transfer completed (" << http_response_code_
323 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000324 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800325 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700326 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000327 }
328 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000329 } else {
330 // set up callback
331 SetupMainloopSources();
332 }
333}
334
335size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800336 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700337 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800338 const size_t payload_size = size * nmemb;
339
340 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800341 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800342 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
343 << ") or no payload (" << payload_size << "), nothing to do";
344 return 0;
345 }
346
347 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000348 {
349 double transfer_size_double;
350 CHECK_EQ(curl_easy_getinfo(curl_handle_,
351 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
352 &transfer_size_double), CURLE_OK);
353 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
354 if (new_transfer_size > 0) {
355 transfer_size_ = resume_offset_ + new_transfer_size;
356 }
357 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800358 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700359 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000360 if (delegate_)
Gilad Arnold48085ba2011-11-16 09:36:08 -0800361 delegate_->ReceivedBytes(this, reinterpret_cast<char*>(ptr), payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700362 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800363 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364}
365
366void LibcurlHttpFetcher::Pause() {
367 CHECK(curl_handle_);
368 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000369 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000370}
371
372void LibcurlHttpFetcher::Unpause() {
373 CHECK(curl_handle_);
374 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000375 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000376}
377
378// This method sets up callbacks with the glib main loop.
379void LibcurlHttpFetcher::SetupMainloopSources() {
380 fd_set fd_read;
381 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700382 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000383
384 FD_ZERO(&fd_read);
385 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700386 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000387
388 int fd_max = 0;
389
390 // Ask libcurl for the set of file descriptors we should track on its
391 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000392 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700393 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000394
395 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700396 // the highest one we're tracking, whichever is larger.
397 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
398 if (!io_channels_[t].empty())
399 fd_max = max(fd_max, io_channels_[t].rbegin()->first);
400 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000401
Darin Petkov60e14152010-10-27 16:57:04 -0700402 // For each fd, if we're not tracking it, track it. If we are tracking it, but
403 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
404 // there should be exactly as many GIOChannel objects in io_channels_[0|1] as
405 // there are read/write fds that we're tracking.
406 for (int fd = 0; fd <= fd_max; ++fd) {
407 // Note that fd_exc is unused in the current version of libcurl so is_exc
408 // should always be false.
409 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
410 bool must_track[2] = {
411 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
412 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
413 };
414
415 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
416 bool tracked = io_channels_[t].find(fd) != io_channels_[t].end();
417
418 if (!must_track[t]) {
419 // If we have an outstanding io_channel, remove it.
420 if (tracked) {
421 g_source_remove(io_channels_[t][fd].second);
422 g_io_channel_unref(io_channels_[t][fd].first);
423 io_channels_[t].erase(io_channels_[t].find(fd));
424 }
425 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000426 }
Darin Petkov60e14152010-10-27 16:57:04 -0700427
428 // If we are already tracking this fd, continue -- nothing to do.
429 if (tracked)
430 continue;
431
432 // Set conditions appropriately -- read for track 0, write for track 1.
433 GIOCondition condition = static_cast<GIOCondition>(
434 ((t == 0) ? (G_IO_IN | G_IO_PRI) : G_IO_OUT) | G_IO_ERR | G_IO_HUP);
435
436 // Track a new fd.
437 GIOChannel* io_channel = g_io_channel_unix_new(fd);
438 guint tag =
439 g_io_add_watch(io_channel, condition, &StaticFDCallback, this);
440
441 io_channels_[t][fd] = make_pair(io_channel, tag);
442 static int io_counter = 0;
443 io_counter++;
444 if (io_counter % 50 == 0) {
445 LOG(INFO) << "io_counter = " << io_counter;
446 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700447 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448 }
449
Darin Petkovb83371f2010-08-17 09:34:49 -0700450 // Set up a timeout callback for libcurl.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700451 if (!timeout_source_) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700452 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
453 timeout_source_ = g_timeout_source_new_seconds(idle_seconds_);
454 g_source_set_callback(timeout_source_, StaticTimeoutCallback, this, NULL);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700455 g_source_attach(timeout_source_, NULL);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000456 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000457}
458
459bool LibcurlHttpFetcher::FDCallback(GIOChannel *source,
460 GIOCondition condition) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700461 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700462 // We handle removing of this source elsewhere, so we always return true.
463 // The docs say, "the function should return FALSE if the event source
464 // should be removed."
465 // http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html#GIOFunc
466 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000467}
468
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700469gboolean LibcurlHttpFetcher::RetryTimeoutCallback() {
470 ResumeTransfer(url_);
471 CurlPerformOnce();
472 return FALSE; // Don't have glib auto call this callback again
473}
474
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700475gboolean LibcurlHttpFetcher::TimeoutCallback() {
Andrew de los Reyescb319332010-07-19 10:55:01 -0700476 // We always return true, even if we don't want glib to call us back.
477 // We will remove the event source separately if we don't want to
478 // be called back.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700479 if (!transfer_in_progress_)
480 return TRUE;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700481 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700482 return TRUE;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483}
484
485void LibcurlHttpFetcher::CleanUp() {
486 if (timeout_source_) {
487 g_source_destroy(timeout_source_);
488 timeout_source_ = NULL;
489 }
490
Darin Petkov60e14152010-10-27 16:57:04 -0700491 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
492 for (IOChannels::iterator it = io_channels_[t].begin();
493 it != io_channels_[t].end(); ++it) {
494 g_source_remove(it->second.second);
495 g_io_channel_unref(it->second.first);
496 }
497 io_channels_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000498 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000499
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800500 if (curl_http_headers_) {
501 curl_slist_free_all(curl_http_headers_);
502 curl_http_headers_ = NULL;
503 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000504 if (curl_handle_) {
505 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000506 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
507 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000508 }
509 curl_easy_cleanup(curl_handle_);
510 curl_handle_ = NULL;
511 }
512 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000513 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000514 curl_multi_handle_ = NULL;
515 }
516 transfer_in_progress_ = false;
517}
518
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700519void LibcurlHttpFetcher::GetHttpResponseCode() {
520 long http_response_code = 0;
521 if (curl_easy_getinfo(curl_handle_,
522 CURLINFO_RESPONSE_CODE,
523 &http_response_code) == CURLE_OK) {
524 http_response_code_ = static_cast<int>(http_response_code);
525 }
526}
527
rspangler@google.com49fdf182009-10-10 00:57:34 +0000528} // namespace chromeos_update_engine