blob: 42e9e42ac296cd66c7587e6c044e068aef7f10cb [file] [log] [blame]
rspangler@google.com49fdf182009-10-10 00:57:34 +00001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
rspangler@google.com49fdf182009-10-10 00:57:34 +00005#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyesd57d1472010-10-21 13:34:08 -07006
adlr@google.comc98a7ed2009-12-04 18:54:03 +00007#include <algorithm>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -07008#include <string>
9
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070010#include <base/bind.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070011#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070012#include <base/strings/string_util.h>
13#include <base/strings/stringprintf.h>
Andrew de los Reyesd57d1472010-10-21 13:34:08 -070014
Bruno Rocha7f9aea22011-09-12 14:31:24 -070015#include "update_engine/certificate_checker.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070016#include "update_engine/hardware_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
adlr@google.comc98a7ed2009-12-04 18:54:03 +000019using std::make_pair;
Alex Deymoc4acdf42014-05-28 21:07:10 -070020using std::max;
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";
Alex Vakulenkod2779df2014-06-16 13:19:00 -070031} // namespace
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -070032
rspangler@google.com49fdf182009-10-10 00:57:34 +000033LibcurlHttpFetcher::~LibcurlHttpFetcher() {
Darin Petkov9ce452b2010-11-17 14:33:28 -080034 LOG_IF(ERROR, transfer_in_progress_)
35 << "Destroying the fetcher while a transfer is in progress.";
rspangler@google.com49fdf182009-10-10 00:57:34 +000036 CleanUp();
37}
38
Alex Deymof329b932014-10-30 01:37:48 -070039bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
Gilad Arnold59d9e012013-07-23 16:41:43 -070040 curl_proxytype* out_type) {
41 if (utils::StringHasPrefix(proxy, "socks5://") ||
42 utils::StringHasPrefix(proxy, "socks://")) {
43 *out_type = CURLPROXY_SOCKS5_HOSTNAME;
44 return true;
45 }
46 if (utils::StringHasPrefix(proxy, "socks4://")) {
47 *out_type = CURLPROXY_SOCKS4A;
48 return true;
49 }
50 if (utils::StringHasPrefix(proxy, "http://") ||
51 utils::StringHasPrefix(proxy, "https://")) {
52 *out_type = CURLPROXY_HTTP;
53 return true;
54 }
55 if (utils::StringHasPrefix(proxy, kNoProxy)) {
56 // known failure case. don't log.
57 return false;
58 }
59 LOG(INFO) << "Unknown proxy type: " << proxy;
60 return false;
61}
62
Alex Deymof329b932014-10-30 01:37:48 -070063void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
Andrew de los Reyes3270f742010-07-15 22:28:14 -070064 LOG(INFO) << "Starting/Resuming transfer";
rspangler@google.com49fdf182009-10-10 00:57:34 +000065 CHECK(!transfer_in_progress_);
66 url_ = url;
67 curl_multi_handle_ = curl_multi_init();
68 CHECK(curl_multi_handle_);
69
70 curl_handle_ = curl_easy_init();
71 CHECK(curl_handle_);
72
Andrew de los Reyes45168102010-11-22 11:13:50 -080073 CHECK(HasProxy());
Gilad Arnoldfbaee242012-04-04 15:59:43 -070074 bool is_direct = (GetCurrentProxy() == kNoProxy);
75 LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
76 if (is_direct) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080077 CHECK_EQ(curl_easy_setopt(curl_handle_,
78 CURLOPT_PROXY,
79 ""), CURLE_OK);
80 } else {
81 CHECK_EQ(curl_easy_setopt(curl_handle_,
82 CURLOPT_PROXY,
83 GetCurrentProxy().c_str()), CURLE_OK);
84 // Curl seems to require us to set the protocol
85 curl_proxytype type;
Gilad Arnold59d9e012013-07-23 16:41:43 -070086 if (GetProxyType(GetCurrentProxy(), &type)) {
Andrew de los Reyes45168102010-11-22 11:13:50 -080087 CHECK_EQ(curl_easy_setopt(curl_handle_,
88 CURLOPT_PROXYTYPE,
89 type), CURLE_OK);
90 }
91 }
92
rspangler@google.com49fdf182009-10-10 00:57:34 +000093 if (post_data_set_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000094 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
95 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS,
96 &post_data_[0]),
97 CURLE_OK);
98 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDSIZE,
99 post_data_.size()),
100 CURLE_OK);
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800101
102 // Set the Content-Type HTTP header, if one was specifically set.
103 CHECK(!curl_http_headers_);
104 if (post_content_type_ != kHttpContentTypeUnspecified) {
105 const string content_type_attr =
106 base::StringPrintf("Content-Type: %s",
107 GetHttpContentTypeString(post_content_type_));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700108 curl_http_headers_ = curl_slist_append(nullptr,
109 content_type_attr.c_str());
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800110 CHECK(curl_http_headers_);
111 CHECK_EQ(
112 curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER,
113 curl_http_headers_),
114 CURLE_OK);
115 } else {
116 LOG(WARNING) << "no content type set, using libcurl default";
117 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000118 }
119
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800120 if (bytes_downloaded_ > 0 || download_length_) {
121 // Resume from where we left off.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000122 resume_offset_ = bytes_downloaded_;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800123 CHECK_GE(resume_offset_, 0);
124
125 // Compute end offset, if one is specified. As per HTTP specification, this
126 // is an inclusive boundary. Make sure it doesn't overflow.
127 size_t end_offset = 0;
128 if (download_length_) {
129 end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
130 CHECK_LE((size_t) resume_offset_, end_offset);
131 }
132
133 // Create a string representation of the desired range.
Alex Deymof329b932014-10-30 01:37:48 -0700134 string range_str = (end_offset ?
135 base::StringPrintf("%jd-%zu", resume_offset_,
136 end_offset) :
137 base::StringPrintf("%jd-", resume_offset_));
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800138 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
139 CURLE_OK);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000140 }
141
142 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
143 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION,
144 StaticLibcurlWrite), CURLE_OK);
Chris Sosa77f79e82014-06-02 18:16:24 -0700145 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()),
Andrew de los Reyesd57d1472010-10-21 13:34:08 -0700146 CURLE_OK);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700147
David Zeuthen34135a92013-08-06 11:16:16 -0700148 // If the connection drops under |low_speed_limit_bps_| (10
149 // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
150 // 180 on non-official builds), reconnect.
151 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_LIMIT,
152 low_speed_limit_bps_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700153 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700154 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_LOW_SPEED_TIME,
155 low_speed_time_seconds_),
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700156 CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700157 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT,
158 connect_timeout_seconds_),
Andrew de los Reyese72f9c02011-04-20 10:47:40 -0700159 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
David Zeuthen34135a92013-08-06 11:16:16 -0700162 // |kDownloadMaxRedirects| redirections.
Darin Petkov3a4016a2010-09-28 13:54:17 -0700163 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
David Zeuthen34135a92013-08-06 11:16:16 -0700164 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS,
165 kDownloadMaxRedirects),
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700166 CURLE_OK);
167
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700168 // Lock down the appropriate curl options for HTTP or HTTPS depending on
169 // the url.
170 if (GetSystemState()->hardware()->IsOfficialBuild()) {
Chris Sosa77f79e82014-06-02 18:16:24 -0700171 if (StartsWithASCII(url_, "http://", false))
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800172 SetCurlOptionsForHttp();
173 else
174 SetCurlOptionsForHttps();
175 } else {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700176 LOG(INFO) << "Not setting http(s) curl options because we are "
177 << "running a dev/test image";
Darin Petkovfc7a0ce2010-10-25 10:38:37 -0700178 }
179
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000180 CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000181 transfer_in_progress_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000182}
183
Jay Srinivasanb3f55402012-12-03 18:12:04 -0800184// Lock down only the protocol in case of HTTP.
185void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
186 LOG(INFO) << "Setting up curl options for HTTP";
187 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
188 CURLE_OK);
189 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
190 CURLPROTO_HTTP),
191 CURLE_OK);
192}
193
194// Security lock-down in official builds: makes sure that peer certificate
195// verification is enabled, restricts the set of trusted certificates,
196// restricts protocols to HTTPS, restricts ciphers to HIGH.
197void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
198 LOG(INFO) << "Setting up curl options for HTTPS";
199 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1),
200 CURLE_OK);
201 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAPATH, kCACertificatesPath),
202 CURLE_OK);
203 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
204 CURLE_OK);
205 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS,
206 CURLPROTO_HTTPS),
207 CURLE_OK);
208 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
209 CURLE_OK);
210 if (check_certificate_ != CertificateChecker::kNone) {
211 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA,
212 &check_certificate_),
213 CURLE_OK);
214 CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_FUNCTION,
215 CertificateChecker::ProcessSSLContext),
216 CURLE_OK);
217 }
218}
219
220
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000221// Begins the transfer, which must not have already been started.
Alex Deymof329b932014-10-30 01:37:48 -0700222void LibcurlHttpFetcher::BeginTransfer(const string& url) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800223 CHECK(!transfer_in_progress_);
224 url_ = url;
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700225 auto closure = base::Bind(&LibcurlHttpFetcher::ProxiesResolved,
226 base::Unretained(this));
227 if (!ResolveProxiesForUrl(url_, new base::Closure(closure))) {
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800228 LOG(ERROR) << "Couldn't resolve proxies";
229 if (delegate_)
230 delegate_->TransferComplete(this, false);
231 }
232}
233
234void LibcurlHttpFetcher::ProxiesResolved() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000235 transfer_size_ = -1;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000236 resume_offset_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700237 retry_count_ = 0;
Darin Petkova0929552010-11-29 14:19:06 -0800238 no_network_retry_count_ = 0;
Darin Petkovcb466212010-08-26 09:40:11 -0700239 http_response_code_ = 0;
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800240 terminate_requested_ = false;
Gilad Arnolda2dee1d2012-04-12 11:50:37 -0700241 sent_byte_ = false;
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800242 ResumeTransfer(url_);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700243 CurlPerformOnce();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000244}
245
Darin Petkov9ce452b2010-11-17 14:33:28 -0800246void LibcurlHttpFetcher::ForceTransferTermination() {
247 CleanUp();
248 if (delegate_) {
249 // Note that after the callback returns this object may be destroyed.
250 delegate_->TransferTerminated(this);
251 }
252}
253
rspangler@google.com49fdf182009-10-10 00:57:34 +0000254void LibcurlHttpFetcher::TerminateTransfer() {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800255 if (in_write_callback_) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700256 terminate_requested_ = true;
Darin Petkov9ce452b2010-11-17 14:33:28 -0800257 } else {
258 ForceTransferTermination();
259 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000260}
261
Andrew de los Reyescb319332010-07-19 10:55:01 -0700262void LibcurlHttpFetcher::CurlPerformOnce() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000263 CHECK(transfer_in_progress_);
264 int running_handles = 0;
265 CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
266
267 // libcurl may request that we immediately call curl_multi_perform after it
268 // returns, so we do. libcurl promises that curl_multi_perform will not block.
269 while (CURLM_CALL_MULTI_PERFORM == retcode) {
270 retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700271 if (terminate_requested_) {
Darin Petkov9ce452b2010-11-17 14:33:28 -0800272 ForceTransferTermination();
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700273 return;
274 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000275 }
276 if (0 == running_handles) {
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700277 GetHttpResponseCode();
278 if (http_response_code_) {
279 LOG(INFO) << "HTTP response code: " << http_response_code_;
Darin Petkova0929552010-11-29 14:19:06 -0800280 no_network_retry_count_ = 0;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700281 } else {
282 LOG(ERROR) << "Unable to get http response code.";
283 }
Darin Petkov192ced42010-07-23 16:20:24 -0700284
rspangler@google.com49fdf182009-10-10 00:57:34 +0000285 // we're done!
286 CleanUp();
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000287
Darin Petkova0929552010-11-29 14:19:06 -0800288 // TODO(petkov): This temporary code tries to deal with the case where the
289 // update engine performs an update check while the network is not ready
290 // (e.g., right after resume). Longer term, we should check if the network
291 // is online/offline and return an appropriate error code.
292 if (!sent_byte_ &&
293 http_response_code_ == 0 &&
294 no_network_retry_count_ < no_network_max_retries_) {
295 no_network_retry_count_++;
296 g_timeout_add_seconds(kNoNetworkRetrySeconds,
297 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
298 this);
299 LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
300 return;
301 }
302
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800303 if ((!sent_byte_ && !IsHttpResponseSuccess()) || IsHttpResponseError()) {
Andrew de los Reyes45168102010-11-22 11:13:50 -0800304 // The transfer completed w/ error and we didn't get any bytes.
305 // If we have another proxy to try, try that.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800306 //
307 // TODO(garnold) in fact there are two separate cases here: one case is an
308 // other-than-success return code (including no return code) and no
309 // received bytes, which is necessary due to the way callbacks are
310 // currently processing error conditions; the second is an explicit HTTP
311 // error code, where some data may have been received (as in the case of a
312 // semi-successful multi-chunk fetch). This is a confusing behavior and
313 // should be unified into a complete, coherent interface.
314 LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
315 << "), " << bytes_downloaded_ << " bytes downloaded";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800316
317 PopProxy(); // Delete the proxy we just gave up on.
318
319 if (HasProxy()) {
320 // We have another proxy. Retry immediately.
Gilad Arnoldfbaee242012-04-04 15:59:43 -0700321 LOG(INFO) << "Retrying with next proxy setting";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800322 g_idle_add(&LibcurlHttpFetcher::StaticRetryTimeoutCallback, this);
323 } else {
324 // Out of proxies. Give up.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800325 LOG(INFO) << "No further proxies, indicating transfer complete";
Andrew de los Reyes45168102010-11-22 11:13:50 -0800326 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800327 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes45168102010-11-22 11:13:50 -0800328 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800329 } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700330 retry_count_++;
Jay Srinivasan32f23572012-06-05 13:45:07 -0700331 LOG(INFO) << "Transfer interrupted after downloading "
332 << bytes_downloaded_ << " of " << transfer_size_ << " bytes. "
333 << transfer_size_ - bytes_downloaded_ << " bytes remaining "
334 << "after " << retry_count_ << " attempt(s)";
335
336 if (retry_count_ > max_retry_count_) {
337 LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700338 if (delegate_)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800339 delegate_->TransferComplete(this, false); // signal fail
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700340 } else {
Jay Srinivasan32f23572012-06-05 13:45:07 -0700341 // Need to restart transfer
342 LOG(INFO) << "Restarting transfer to download the remaining bytes";
Darin Petkovb83371f2010-08-17 09:34:49 -0700343 g_timeout_add_seconds(retry_seconds_,
Darin Petkov9b111652010-08-16 11:46:25 -0700344 &LibcurlHttpFetcher::StaticRetryTimeoutCallback,
345 this);
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700346 }
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000347 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800348 LOG(INFO) << "Transfer completed (" << http_response_code_
349 << "), " << bytes_downloaded_ << " bytes downloaded";
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000350 if (delegate_) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800351 bool success = IsHttpResponseSuccess();
Andrew de los Reyesfb4ad7d2010-07-19 10:43:46 -0700352 delegate_->TransferComplete(this, success);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000353 }
354 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000355 } else {
356 // set up callback
357 SetupMainloopSources();
358 }
359}
360
361size_t LibcurlHttpFetcher::LibcurlWrite(void *ptr, size_t size, size_t nmemb) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800362 // Update HTTP response first.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700363 GetHttpResponseCode();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800364 const size_t payload_size = size * nmemb;
365
366 // Do nothing if no payload or HTTP response is an error.
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800367 if (payload_size == 0 || !IsHttpResponseSuccess()) {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800368 LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
369 << ") or no payload (" << payload_size << "), nothing to do";
370 return 0;
371 }
372
373 sent_byte_ = true;
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000374 {
375 double transfer_size_double;
376 CHECK_EQ(curl_easy_getinfo(curl_handle_,
377 CURLINFO_CONTENT_LENGTH_DOWNLOAD,
378 &transfer_size_double), CURLE_OK);
379 off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
380 if (new_transfer_size > 0) {
381 transfer_size_ = resume_offset_ + new_transfer_size;
382 }
383 }
Gilad Arnold48085ba2011-11-16 09:36:08 -0800384 bytes_downloaded_ += payload_size;
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700385 in_write_callback_ = true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386 if (delegate_)
Gilad Arnold48085ba2011-11-16 09:36:08 -0800387 delegate_->ReceivedBytes(this, reinterpret_cast<char*>(ptr), payload_size);
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700388 in_write_callback_ = false;
Gilad Arnold48085ba2011-11-16 09:36:08 -0800389 return payload_size;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000390}
391
392void LibcurlHttpFetcher::Pause() {
393 CHECK(curl_handle_);
394 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000395 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000396}
397
398void LibcurlHttpFetcher::Unpause() {
399 CHECK(curl_handle_);
400 CHECK(transfer_in_progress_);
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000401 CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000402}
403
404// This method sets up callbacks with the glib main loop.
405void LibcurlHttpFetcher::SetupMainloopSources() {
406 fd_set fd_read;
407 fd_set fd_write;
Darin Petkov60e14152010-10-27 16:57:04 -0700408 fd_set fd_exc;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409
410 FD_ZERO(&fd_read);
411 FD_ZERO(&fd_write);
Darin Petkov60e14152010-10-27 16:57:04 -0700412 FD_ZERO(&fd_exc);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000413
414 int fd_max = 0;
415
416 // Ask libcurl for the set of file descriptors we should track on its
417 // behalf.
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000418 CHECK_EQ(curl_multi_fdset(curl_multi_handle_, &fd_read, &fd_write,
Darin Petkov60e14152010-10-27 16:57:04 -0700419 &fd_exc, &fd_max), CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000420
421 // We should iterate through all file descriptors up to libcurl's fd_max or
Darin Petkov60e14152010-10-27 16:57:04 -0700422 // the highest one we're tracking, whichever is larger.
423 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
424 if (!io_channels_[t].empty())
425 fd_max = max(fd_max, io_channels_[t].rbegin()->first);
426 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000427
Darin Petkov60e14152010-10-27 16:57:04 -0700428 // For each fd, if we're not tracking it, track it. If we are tracking it, but
429 // libcurl doesn't care about it anymore, stop tracking it. After this loop,
430 // there should be exactly as many GIOChannel objects in io_channels_[0|1] as
431 // there are read/write fds that we're tracking.
432 for (int fd = 0; fd <= fd_max; ++fd) {
433 // Note that fd_exc is unused in the current version of libcurl so is_exc
434 // should always be false.
435 bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
436 bool must_track[2] = {
437 is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
438 is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
439 };
440
441 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
442 bool tracked = io_channels_[t].find(fd) != io_channels_[t].end();
443
444 if (!must_track[t]) {
445 // If we have an outstanding io_channel, remove it.
446 if (tracked) {
447 g_source_remove(io_channels_[t][fd].second);
448 g_io_channel_unref(io_channels_[t][fd].first);
449 io_channels_[t].erase(io_channels_[t].find(fd));
450 }
451 continue;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000452 }
Darin Petkov60e14152010-10-27 16:57:04 -0700453
454 // If we are already tracking this fd, continue -- nothing to do.
455 if (tracked)
456 continue;
457
458 // Set conditions appropriately -- read for track 0, write for track 1.
459 GIOCondition condition = static_cast<GIOCondition>(
460 ((t == 0) ? (G_IO_IN | G_IO_PRI) : G_IO_OUT) | G_IO_ERR | G_IO_HUP);
461
462 // Track a new fd.
463 GIOChannel* io_channel = g_io_channel_unix_new(fd);
464 guint tag =
465 g_io_add_watch(io_channel, condition, &StaticFDCallback, this);
466
467 io_channels_[t][fd] = make_pair(io_channel, tag);
468 static int io_counter = 0;
469 io_counter++;
470 if (io_counter % 50 == 0) {
471 LOG(INFO) << "io_counter = " << io_counter;
472 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700473 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000474 }
475
Darin Petkovb83371f2010-08-17 09:34:49 -0700476 // Set up a timeout callback for libcurl.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700477 if (!timeout_source_) {
Darin Petkovb83371f2010-08-17 09:34:49 -0700478 LOG(INFO) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
479 timeout_source_ = g_timeout_source_new_seconds(idle_seconds_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700480 g_source_set_callback(timeout_source_, StaticTimeoutCallback, this,
481 nullptr);
482 g_source_attach(timeout_source_, nullptr);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484}
485
486bool LibcurlHttpFetcher::FDCallback(GIOChannel *source,
487 GIOCondition condition) {
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700488 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700489 // We handle removing of this source elsewhere, so we always return true.
490 // The docs say, "the function should return FALSE if the event source
491 // should be removed."
492 // http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html#GIOFunc
493 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494}
495
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700496gboolean LibcurlHttpFetcher::RetryTimeoutCallback() {
497 ResumeTransfer(url_);
498 CurlPerformOnce();
499 return FALSE; // Don't have glib auto call this callback again
500}
501
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700502gboolean LibcurlHttpFetcher::TimeoutCallback() {
Andrew de los Reyescb319332010-07-19 10:55:01 -0700503 // We always return true, even if we don't want glib to call us back.
504 // We will remove the event source separately if we don't want to
505 // be called back.
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700506 if (!transfer_in_progress_)
507 return TRUE;
Andrew de los Reyes9bbd1872010-07-16 14:52:29 -0700508 CurlPerformOnce();
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700509 return TRUE;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000510}
511
512void LibcurlHttpFetcher::CleanUp() {
513 if (timeout_source_) {
514 g_source_destroy(timeout_source_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700515 timeout_source_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000516 }
517
Darin Petkov60e14152010-10-27 16:57:04 -0700518 for (size_t t = 0; t < arraysize(io_channels_); ++t) {
519 for (IOChannels::iterator it = io_channels_[t].begin();
520 it != io_channels_[t].end(); ++it) {
521 g_source_remove(it->second.second);
522 g_io_channel_unref(it->second.first);
523 }
524 io_channels_[t].clear();
rspangler@google.com49fdf182009-10-10 00:57:34 +0000525 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800527 if (curl_http_headers_) {
528 curl_slist_free_all(curl_http_headers_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700529 curl_http_headers_ = nullptr;
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800530 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000531 if (curl_handle_) {
532 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000533 CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
534 CURLM_OK);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000535 }
536 curl_easy_cleanup(curl_handle_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700537 curl_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000538 }
539 if (curl_multi_handle_) {
adlr@google.comc98a7ed2009-12-04 18:54:03 +0000540 CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700541 curl_multi_handle_ = nullptr;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000542 }
543 transfer_in_progress_ = false;
544}
545
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700546void LibcurlHttpFetcher::GetHttpResponseCode() {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700547 long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700548 if (curl_easy_getinfo(curl_handle_,
549 CURLINFO_RESPONSE_CODE,
550 &http_response_code) == CURLE_OK) {
551 http_response_code_ = static_cast<int>(http_response_code);
552 }
553}
554
rspangler@google.com49fdf182009-10-10 00:57:34 +0000555} // namespace chromeos_update_engine