1 //
2 // Copyright (C) 2009 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "update_engine/libcurl_http_fetcher.h"
18 
19 #include <netinet/in.h>
20 #include <resolv.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 #include <algorithm>
25 #include <string>
26 
27 #include <base/bind.h>
28 #include <base/format_macros.h>
29 #include <base/location.h>
30 #include <base/logging.h>
31 #include <base/strings/string_split.h>
32 #include <base/strings/string_util.h>
33 #include <base/strings/stringprintf.h>
34 #include <base/threading/thread_task_runner_handle.h>
35 
36 
37 #ifdef __ANDROID__
38 #include <cutils/qtaguid.h>
39 #include <private/android_filesystem_config.h>
40 #endif  // __ANDROID__
41 
42 #include "update_engine/certificate_checker.h"
43 #include "update_engine/common/hardware_interface.h"
44 #include "update_engine/common/platform_constants.h"
45 
46 using base::TimeDelta;
47 using brillo::MessageLoop;
48 using std::max;
49 using std::string;
50 
51 // This is a concrete implementation of HttpFetcher that uses libcurl to do the
52 // http work.
53 
54 namespace chromeos_update_engine {
55 
56 namespace {
57 
58 const int kNoNetworkRetrySeconds = 10;
59 
60 // libcurl's CURLOPT_SOCKOPTFUNCTION callback function. Called after the socket
61 // is created but before it is connected. This callback tags the created socket
62 // so the network usage can be tracked in Android.
LibcurlSockoptCallback(void *,curl_socket_t curlfd,curlsocktype)63 int LibcurlSockoptCallback(void* /* clientp */,
64                            curl_socket_t curlfd,
65                            curlsocktype /* purpose */) {
66 #ifdef __ANDROID__
67   // Socket tag used by all network sockets. See qtaguid kernel module for
68   // stats.
69   const int kUpdateEngineSocketTag = 0x55417243;  // "CrAU" in little-endian.
70   qtaguid_tagSocket(curlfd, kUpdateEngineSocketTag, AID_OTA_UPDATE);
71 #endif  // __ANDROID__
72   return CURL_SOCKOPT_OK;
73 }
74 
75 }  // namespace
76 
77 // static
LibcurlCloseSocketCallback(void * clientp,curl_socket_t item)78 int LibcurlHttpFetcher::LibcurlCloseSocketCallback(void* clientp,
79                                                    curl_socket_t item) {
80 #ifdef __ANDROID__
81   qtaguid_untagSocket(item);
82 #endif  // __ANDROID__
83 
84   LibcurlHttpFetcher* fetcher = static_cast<LibcurlHttpFetcher*>(clientp);
85   // Stop watching the socket before closing it.
86   for (size_t t = 0; t < base::size(fetcher->fd_controller_maps_); ++t) {
87     fetcher->fd_controller_maps_[t].erase(item);
88   }
89 
90   // Documentation for this callback says to return 0 on success or 1 on error.
91   if (!IGNORE_EINTR(close(item)))
92     return 0;
93   return 1;
94 }
95 
LibcurlHttpFetcher(ProxyResolver * proxy_resolver,HardwareInterface * hardware)96 LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
97                                        HardwareInterface* hardware)
98     : HttpFetcher(proxy_resolver), hardware_(hardware) {
99   // Dev users want a longer timeout (180 seconds) because they may
100   // be waiting on the dev server to build an image.
101   if (!hardware_->IsOfficialBuild())
102     low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
103   if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
104     max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
105 }
106 
~LibcurlHttpFetcher()107 LibcurlHttpFetcher::~LibcurlHttpFetcher() {
108   LOG_IF(ERROR, transfer_in_progress_)
109       << "Destroying the fetcher while a transfer is in progress.";
110   CancelProxyResolution();
111   CleanUp();
112 }
113 
GetProxyType(const string & proxy,curl_proxytype * out_type)114 bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
115                                       curl_proxytype* out_type) {
116   if (base::StartsWith(
117           proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
118       base::StartsWith(
119           proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
120     *out_type = CURLPROXY_SOCKS5_HOSTNAME;
121     return true;
122   }
123   if (base::StartsWith(
124           proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
125     *out_type = CURLPROXY_SOCKS4A;
126     return true;
127   }
128   if (base::StartsWith(
129           proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
130       base::StartsWith(
131           proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
132     *out_type = CURLPROXY_HTTP;
133     return true;
134   }
135   if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
136     // known failure case. don't log.
137     return false;
138   }
139   LOG(INFO) << "Unknown proxy type: " << proxy;
140   return false;
141 }
142 
ResumeTransfer(const string & url)143 void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
144   LOG(INFO) << "Starting/Resuming transfer";
145   CHECK(!transfer_in_progress_);
146   url_ = url;
147   curl_multi_handle_ = curl_multi_init();
148   CHECK(curl_multi_handle_);
149 
150   curl_handle_ = curl_easy_init();
151   CHECK(curl_handle_);
152   ignore_failure_ = false;
153 
154   // Tag and untag the socket for network usage stats.
155   curl_easy_setopt(
156       curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
157   curl_easy_setopt(
158       curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
159   curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
160 
161   CHECK(HasProxy());
162   bool is_direct = (GetCurrentProxy() == kNoProxy);
163   LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
164   if (is_direct) {
165     CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
166   } else {
167     CHECK_EQ(curl_easy_setopt(
168                  curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
169              CURLE_OK);
170     // Curl seems to require us to set the protocol
171     curl_proxytype type;
172     if (GetProxyType(GetCurrentProxy(), &type)) {
173       CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
174                CURLE_OK);
175     }
176   }
177 
178   if (post_data_set_) {
179     CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
180     CHECK_EQ(
181         curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
182         CURLE_OK);
183     CHECK_EQ(curl_easy_setopt(
184                  curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
185              CURLE_OK);
186   }
187 
188   // Setup extra HTTP headers.
189   if (curl_http_headers_) {
190     curl_slist_free_all(curl_http_headers_);
191     curl_http_headers_ = nullptr;
192   }
193   for (const auto& header : extra_headers_) {
194     // curl_slist_append() copies the string.
195     curl_http_headers_ =
196         curl_slist_append(curl_http_headers_, header.second.c_str());
197   }
198   if (post_data_set_) {
199     // Set the Content-Type HTTP header, if one was specifically set.
200     if (post_content_type_ != kHttpContentTypeUnspecified) {
201       const string content_type_attr = base::StringPrintf(
202           "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
203       curl_http_headers_ =
204           curl_slist_append(curl_http_headers_, content_type_attr.c_str());
205     } else {
206       LOG(WARNING) << "no content type set, using libcurl default";
207     }
208   }
209   CHECK_EQ(
210       curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
211       CURLE_OK);
212 
213   if (bytes_downloaded_ > 0 || download_length_) {
214     // Resume from where we left off.
215     resume_offset_ = bytes_downloaded_;
216     CHECK_GE(resume_offset_, 0);
217 
218     // Compute end offset, if one is specified. As per HTTP specification, this
219     // is an inclusive boundary. Make sure it doesn't overflow.
220     size_t end_offset = 0;
221     if (download_length_) {
222       end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
223       CHECK_LE((size_t)resume_offset_, end_offset);
224     }
225 
226     // Create a string representation of the desired range.
227     string range_str = base::StringPrintf(
228         "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
229     if (end_offset)
230       range_str += std::to_string(end_offset);
231     CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
232              CURLE_OK);
233   }
234 
235   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
236   CHECK_EQ(
237       curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
238       CURLE_OK);
239   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
240 
241   // If the connection drops under |low_speed_limit_bps_| (10
242   // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
243   // 180 on non-official builds), reconnect.
244   CHECK_EQ(curl_easy_setopt(
245                curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
246            CURLE_OK);
247   CHECK_EQ(curl_easy_setopt(
248                curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
249            CURLE_OK);
250   CHECK_EQ(curl_easy_setopt(
251                curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
252            CURLE_OK);
253 
254   // By default, libcurl doesn't follow redirections. Allow up to
255   // |kDownloadMaxRedirects| redirections.
256   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
257   CHECK_EQ(
258       curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
259       CURLE_OK);
260 
261   // Lock down the appropriate curl options for HTTP or HTTPS depending on
262   // the url.
263   if (hardware_->IsOfficialBuild()) {
264     if (base::StartsWith(
265             url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
266       SetCurlOptionsForHttp();
267     } else if (base::StartsWith(
268                    url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
269       SetCurlOptionsForHttps();
270 #ifdef __ANDROID__
271     } else if (base::StartsWith(
272                    url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
273       SetCurlOptionsForFile();
274 #endif  // __ANDROID__
275     } else {
276       LOG(ERROR) << "Received invalid URI: " << url_;
277       // Lock down to no protocol supported for the transfer.
278       CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
279     }
280   } else {
281     LOG(INFO) << "Not setting http(s) curl options because we are "
282               << "running a dev/test image";
283   }
284 
285   CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
286   transfer_in_progress_ = true;
287 }
288 
289 // Lock down only the protocol in case of HTTP.
SetCurlOptionsForHttp()290 void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
291   LOG(INFO) << "Setting up curl options for HTTP";
292   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
293            CURLE_OK);
294   CHECK_EQ(
295       curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
296       CURLE_OK);
297 }
298 
299 // Security lock-down in official builds: makes sure that peer certificate
300 // verification is enabled, restricts the set of trusted certificates,
301 // restricts protocols to HTTPS, restricts ciphers to HIGH.
SetCurlOptionsForHttps()302 void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
303   LOG(INFO) << "Setting up curl options for HTTPS";
304   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
305   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
306   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_CAINFO, nullptr), CURLE_OK);
307   CHECK_EQ(curl_easy_setopt(
308                curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
309            CURLE_OK);
310   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
311            CURLE_OK);
312   CHECK_EQ(
313       curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
314       CURLE_OK);
315   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
316            CURLE_OK);
317   if (server_to_check_ != ServerToCheck::kNone) {
318     CHECK_EQ(
319         curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
320         CURLE_OK);
321     CHECK_EQ(curl_easy_setopt(curl_handle_,
322                               CURLOPT_SSL_CTX_FUNCTION,
323                               CertificateChecker::ProcessSSLContext),
324              CURLE_OK);
325   }
326 }
327 
328 // Lock down only the protocol in case of a local file.
SetCurlOptionsForFile()329 void LibcurlHttpFetcher::SetCurlOptionsForFile() {
330   LOG(INFO) << "Setting up curl options for FILE";
331   CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
332            CURLE_OK);
333   CHECK_EQ(
334       curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
335       CURLE_OK);
336 }
337 
338 // Begins the transfer, which must not have already been started.
BeginTransfer(const string & url)339 void LibcurlHttpFetcher::BeginTransfer(const string& url) {
340   CHECK(!transfer_in_progress_);
341   url_ = url;
342   auto closure =
343       base::Bind(&LibcurlHttpFetcher::ProxiesResolved, base::Unretained(this));
344   ResolveProxiesForUrl(url_, closure);
345 }
346 
ProxiesResolved()347 void LibcurlHttpFetcher::ProxiesResolved() {
348   transfer_size_ = -1;
349   resume_offset_ = 0;
350   retry_count_ = 0;
351   no_network_retry_count_ = 0;
352   http_response_code_ = 0;
353   terminate_requested_ = false;
354   sent_byte_ = false;
355 
356   // If we are paused, we delay these two operations until Unpause is called.
357   if (transfer_paused_) {
358     restart_transfer_on_unpause_ = true;
359     return;
360   }
361   ResumeTransfer(url_);
362   CurlPerformOnce();
363 }
364 
ForceTransferTermination()365 void LibcurlHttpFetcher::ForceTransferTermination() {
366   CancelProxyResolution();
367   CleanUp();
368   if (delegate_) {
369     // Note that after the callback returns this object may be destroyed.
370     delegate_->TransferTerminated(this);
371   }
372 }
373 
TerminateTransfer()374 void LibcurlHttpFetcher::TerminateTransfer() {
375   if (in_write_callback_) {
376     terminate_requested_ = true;
377   } else {
378     ForceTransferTermination();
379   }
380 }
381 
SetHeader(const string & header_name,const string & header_value)382 void LibcurlHttpFetcher::SetHeader(const string& header_name,
383                                    const string& header_value) {
384   string header_line = header_name + ": " + header_value;
385   // Avoid the space if no data on the right side of the semicolon.
386   if (header_value.empty())
387     header_line = header_name + ":";
388   TEST_AND_RETURN(header_line.find('\n') == string::npos);
389   TEST_AND_RETURN(header_name.find(':') == string::npos);
390   extra_headers_[base::ToLowerASCII(header_name)] = header_line;
391 }
392 
393 // Inputs: header_name, header_value
394 // Example:
395 //   extra_headers_ = { {"foo":"foo: 123"}, {"bar":"bar:"} }
396 //   string tmp = "gibberish";
397 //   Case 1:
398 //     GetHeader("foo", &tmp) -> tmp = "123", return true.
399 //   Case 2:
400 //     GetHeader("bar", &tmp) -> tmp = "", return true.
401 //   Case 3:
402 //     GetHeader("moo", &tmp) -> tmp = "", return false.
GetHeader(const string & header_name,string * header_value) const403 bool LibcurlHttpFetcher::GetHeader(const string& header_name,
404                                    string* header_value) const {
405   // Initially clear |header_value| to handle both success and failures without
406   // leaving |header_value| in a unclear state.
407   header_value->clear();
408   auto header_key = base::ToLowerASCII(header_name);
409   auto header_line_itr = extra_headers_.find(header_key);
410   // If the |header_name| was never set, indicate so by returning false.
411   if (header_line_itr == extra_headers_.end())
412     return false;
413   // From |SetHeader()| the check for |header_name| to not include ":" is
414   // verified, so finding the first index of ":" is a safe operation.
415   auto header_line = header_line_itr->second;
416   *header_value = header_line.substr(header_line.find(':') + 1);
417   // The following is neccessary to remove the leading ' ' before the header
418   // value that was place only if |header_value| passed to |SetHeader()| was
419   // a non-empty string.
420   header_value->erase(0, 1);
421   return true;
422 }
423 
CurlPerformOnce()424 void LibcurlHttpFetcher::CurlPerformOnce() {
425   CHECK(transfer_in_progress_);
426   int running_handles = 0;
427   CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
428 
429   // libcurl may request that we immediately call curl_multi_perform after it
430   // returns, so we do. libcurl promises that curl_multi_perform will not block.
431   while (CURLM_CALL_MULTI_PERFORM == retcode) {
432     retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
433     if (terminate_requested_) {
434       ForceTransferTermination();
435       return;
436     }
437   }
438 
439   // When retcode is not |CURLM_OK| at this point, libcurl has an internal error
440   // that it is less likely to recover from (libcurl bug, out-of-memory, etc.).
441   // In case of an update check, we send UMA metrics and log the error.
442   if (is_update_check_ &&
443       (retcode == CURLM_OUT_OF_MEMORY || retcode == CURLM_INTERNAL_ERROR)) {
444     auxiliary_error_code_ = ErrorCode::kInternalLibCurlError;
445     LOG(ERROR) << "curl_multi_perform is in an unrecoverable error condition: "
446                << retcode;
447   } else if (retcode != CURLM_OK) {
448     LOG(ERROR) << "curl_multi_perform returns error: " << retcode;
449   }
450 
451   // If the transfer completes while paused, we should ignore the failure once
452   // the fetcher is unpaused.
453   if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
454     LOG(INFO) << "Connection closed while paused, ignoring failure.";
455     ignore_failure_ = true;
456   }
457 
458   if (running_handles != 0 || transfer_paused_) {
459     // There's either more work to do or we are paused, so we just keep the
460     // file descriptors to watch up to date and exit, until we are done with the
461     // work and we are not paused.
462 #ifdef __ANDROID__
463     // When there's no base::SingleThreadTaskRunner on current thread, it's not
464     // possible to watch file descriptors. Just poll it later. This usually
465     // happens if brillo::FakeMessageLoop is used.
466     if (!base::ThreadTaskRunnerHandle::IsSet()) {
467         MessageLoop::current()->PostDelayedTask(
468             FROM_HERE,
469             base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
470                        base::Unretained(this)),
471             TimeDelta::FromSeconds(1));
472         return;
473     }
474 #endif
475     SetupMessageLoopSources();
476     return;
477   }
478 
479   // At this point, the transfer was completed in some way (error, connection
480   // closed or download finished).
481 
482   GetHttpResponseCode();
483   if (http_response_code_) {
484     LOG(INFO) << "HTTP response code: " << http_response_code_;
485     no_network_retry_count_ = 0;
486     unresolved_host_state_machine_.UpdateState(false);
487   } else {
488     LOG(ERROR) << "Unable to get http response code.";
489     CURLcode curl_code = GetCurlCode();
490     LOG(ERROR) << "Return code for the transfer: " << curl_code;
491     if (curl_code == CURLE_COULDNT_RESOLVE_HOST) {
492       LOG(ERROR) << "libcurl can not resolve host.";
493       unresolved_host_state_machine_.UpdateState(true);
494       auxiliary_error_code_ = ErrorCode::kUnresolvedHostError;
495     }
496   }
497 
498   // we're done!
499   CleanUp();
500 
501   if (unresolved_host_state_machine_.GetState() ==
502       UnresolvedHostStateMachine::State::kRetry) {
503     // Based on
504     // https://curl.haxx.se/docs/todo.html#updated_DNS_server_while_running,
505     // update_engine process should call res_init() and unconditionally retry.
506     res_init();
507     no_network_max_retries_++;
508     LOG(INFO) << "Will retry after reloading resolv.conf because last attempt "
509                  "failed to resolve host.";
510   } else if (unresolved_host_state_machine_.GetState() ==
511              UnresolvedHostStateMachine::State::kRetriedSuccess) {
512     auxiliary_error_code_ = ErrorCode::kUnresolvedHostRecovered;
513   }
514 
515   // TODO(petkov): This temporary code tries to deal with the case where the
516   // update engine performs an update check while the network is not ready
517   // (e.g., right after resume). Longer term, we should check if the network
518   // is online/offline and return an appropriate error code.
519   if (!sent_byte_ && http_response_code_ == 0 &&
520       no_network_retry_count_ < no_network_max_retries_) {
521     no_network_retry_count_++;
522     retry_task_id_ = MessageLoop::current()->PostDelayedTask(
523         FROM_HERE,
524         base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
525                    base::Unretained(this)),
526         TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
527     LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
528   } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
529              IsHttpResponseError()) {
530     // The transfer completed w/ error and we didn't get any bytes.
531     // If we have another proxy to try, try that.
532     //
533     // TODO(garnold) in fact there are two separate cases here: one case is an
534     // other-than-success return code (including no return code) and no
535     // received bytes, which is necessary due to the way callbacks are
536     // currently processing error conditions;  the second is an explicit HTTP
537     // error code, where some data may have been received (as in the case of a
538     // semi-successful multi-chunk fetch).  This is a confusing behavior and
539     // should be unified into a complete, coherent interface.
540     LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
541               << "), " << bytes_downloaded_ << " bytes downloaded";
542 
543     PopProxy();  // Delete the proxy we just gave up on.
544 
545     if (HasProxy()) {
546       // We have another proxy. Retry immediately.
547       LOG(INFO) << "Retrying with next proxy setting";
548       retry_task_id_ = MessageLoop::current()->PostTask(
549           FROM_HERE,
550           base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
551                      base::Unretained(this)));
552     } else {
553       // Out of proxies. Give up.
554       LOG(INFO) << "No further proxies, indicating transfer complete";
555       if (delegate_)
556         delegate_->TransferComplete(this, false);  // signal fail
557       return;
558     }
559   } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
560     if (!ignore_failure_)
561       retry_count_++;
562     LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
563               << " of " << transfer_size_ << " bytes. "
564               << transfer_size_ - bytes_downloaded_ << " bytes remaining "
565               << "after " << retry_count_ << " attempt(s)";
566 
567     if (retry_count_ > max_retry_count_) {
568       LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
569       if (delegate_)
570         delegate_->TransferComplete(this, false);  // signal fail
571       return;
572     }
573     // Need to restart transfer
574     LOG(INFO) << "Restarting transfer to download the remaining bytes";
575     retry_task_id_ = MessageLoop::current()->PostDelayedTask(
576         FROM_HERE,
577         base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
578                    base::Unretained(this)),
579         TimeDelta::FromSeconds(retry_seconds_));
580   } else {
581     LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
582               << bytes_downloaded_ << " bytes downloaded";
583     if (delegate_) {
584       bool success = IsHttpResponseSuccess();
585       delegate_->TransferComplete(this, success);
586     }
587     return;
588   }
589   // If we reach this point is because TransferComplete() was not called in any
590   // of the previous branches. The delegate is allowed to destroy the object
591   // once TransferComplete is called so this would be illegal.
592   ignore_failure_ = false;
593 }
594 
LibcurlWrite(void * ptr,size_t size,size_t nmemb)595 size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
596   // Update HTTP response first.
597   GetHttpResponseCode();
598   const size_t payload_size = size * nmemb;
599 
600   // Do nothing if no payload or HTTP response is an error.
601   if (payload_size == 0 || !IsHttpResponseSuccess()) {
602     LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
603               << ") or no payload (" << payload_size << "), nothing to do";
604     return 0;
605   }
606 
607   sent_byte_ = true;
608   {
609     double transfer_size_double;
610     CHECK_EQ(curl_easy_getinfo(curl_handle_,
611                                CURLINFO_CONTENT_LENGTH_DOWNLOAD,
612                                &transfer_size_double),
613              CURLE_OK);
614     off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
615     if (new_transfer_size > 0) {
616       transfer_size_ = resume_offset_ + new_transfer_size;
617     }
618   }
619   bytes_downloaded_ += payload_size;
620   if (delegate_) {
621     in_write_callback_ = true;
622     auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
623     in_write_callback_ = false;
624     if (should_terminate) {
625       LOG(INFO) << "Requesting libcurl to terminate transfer.";
626       // Returning an amount that differs from the received size signals an
627       // error condition to libcurl, which will cause the transfer to be
628       // aborted.
629       return 0;
630     }
631   }
632   return payload_size;
633 }
634 
Pause()635 void LibcurlHttpFetcher::Pause() {
636   if (transfer_paused_) {
637     LOG(ERROR) << "Fetcher already paused.";
638     return;
639   }
640   transfer_paused_ = true;
641   if (!transfer_in_progress_) {
642     // If pause before we started a connection, we don't need to notify curl
643     // about that, we will simply not start the connection later.
644     return;
645   }
646   CHECK(curl_handle_);
647   CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
648 }
649 
Unpause()650 void LibcurlHttpFetcher::Unpause() {
651   if (!transfer_paused_) {
652     LOG(ERROR) << "Resume attempted when fetcher not paused.";
653     return;
654   }
655   transfer_paused_ = false;
656   if (restart_transfer_on_unpause_) {
657     restart_transfer_on_unpause_ = false;
658     ResumeTransfer(url_);
659     CurlPerformOnce();
660     return;
661   }
662   if (!transfer_in_progress_) {
663     // If resumed before starting the connection, there's no need to notify
664     // anybody. We will simply start the connection once it is time.
665     return;
666   }
667   CHECK(curl_handle_);
668   CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
669   // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
670   // now to let the connection continue, otherwise it would be called by the
671   // TimeoutCallback but with a delay.
672   CurlPerformOnce();
673 }
674 
675 // This method sets up callbacks with the MessageLoop.
SetupMessageLoopSources()676 void LibcurlHttpFetcher::SetupMessageLoopSources() {
677   fd_set fd_read;
678   fd_set fd_write;
679   fd_set fd_exc;
680 
681   FD_ZERO(&fd_read);
682   FD_ZERO(&fd_write);
683   FD_ZERO(&fd_exc);
684 
685   int fd_max = 0;
686 
687   // Ask libcurl for the set of file descriptors we should track on its
688   // behalf.
689   CHECK_EQ(curl_multi_fdset(
690                curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
691            CURLM_OK);
692 
693   // We should iterate through all file descriptors up to libcurl's fd_max or
694   // the highest one we're tracking, whichever is larger.
695   for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
696     if (!fd_controller_maps_[t].empty())
697       fd_max = max(fd_max, fd_controller_maps_[t].rbegin()->first);
698   }
699 
700   // For each fd, if we're not tracking it, track it. If we are tracking it, but
701   // libcurl doesn't care about it anymore, stop tracking it. After this loop,
702   // there should be exactly as many tasks scheduled in
703   // fd_controller_maps_[0|1] as there are read/write fds that we're tracking.
704   for (int fd = 0; fd <= fd_max; ++fd) {
705     // Note that fd_exc is unused in the current version of libcurl so is_exc
706     // should always be false.
707     bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
708     bool must_track[2] = {
709         is_exc || (FD_ISSET(fd, &fd_read) != 0),  // track 0 -- read
710         is_exc || (FD_ISSET(fd, &fd_write) != 0)  // track 1 -- write
711     };
712 
713     for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
714       bool tracked =
715           fd_controller_maps_[t].find(fd) != fd_controller_maps_[t].end();
716 
717       if (!must_track[t]) {
718         // If we have an outstanding io_channel, remove it.
719         fd_controller_maps_[t].erase(fd);
720         continue;
721       }
722 
723       // If we are already tracking this fd, continue -- nothing to do.
724       if (tracked)
725         continue;
726 
727       // Track a new fd.
728       switch (t) {
729         case 0:  // Read
730           fd_controller_maps_[t][fd] =
731               base::FileDescriptorWatcher::WatchReadable(
732                   fd,
733                   base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
734                                       base::Unretained(this)));
735           break;
736         case 1:  // Write
737           fd_controller_maps_[t][fd] =
738               base::FileDescriptorWatcher::WatchWritable(
739                   fd,
740                   base::BindRepeating(&LibcurlHttpFetcher::CurlPerformOnce,
741                                       base::Unretained(this)));
742       }
743       static int io_counter = 0;
744       io_counter++;
745       if (io_counter % 50 == 0) {
746         LOG(INFO) << "io_counter = " << io_counter;
747       }
748     }
749   }
750 
751   // Set up a timeout callback for libcurl.
752   if (timeout_id_ == MessageLoop::kTaskIdNull) {
753     VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
754     timeout_id_ = MessageLoop::current()->PostDelayedTask(
755         FROM_HERE,
756         base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
757                    base::Unretained(this)),
758         TimeDelta::FromSeconds(idle_seconds_));
759   }
760 }
761 
RetryTimeoutCallback()762 void LibcurlHttpFetcher::RetryTimeoutCallback() {
763   retry_task_id_ = MessageLoop::kTaskIdNull;
764   if (transfer_paused_) {
765     restart_transfer_on_unpause_ = true;
766     return;
767   }
768   ResumeTransfer(url_);
769   CurlPerformOnce();
770 }
771 
TimeoutCallback()772 void LibcurlHttpFetcher::TimeoutCallback() {
773   // We always re-schedule the callback, even if we don't want to be called
774   // anymore. We will remove the event source separately if we don't want to
775   // be called back.
776   timeout_id_ = MessageLoop::current()->PostDelayedTask(
777       FROM_HERE,
778       base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
779       TimeDelta::FromSeconds(idle_seconds_));
780 
781   // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
782   // first, since it could be canceled by this call.
783   if (transfer_in_progress_)
784     CurlPerformOnce();
785 }
786 
CleanUp()787 void LibcurlHttpFetcher::CleanUp() {
788   MessageLoop::current()->CancelTask(retry_task_id_);
789   retry_task_id_ = MessageLoop::kTaskIdNull;
790 
791   MessageLoop::current()->CancelTask(timeout_id_);
792   timeout_id_ = MessageLoop::kTaskIdNull;
793 
794   for (size_t t = 0; t < base::size(fd_controller_maps_); ++t) {
795     fd_controller_maps_[t].clear();
796   }
797 
798   if (curl_http_headers_) {
799     curl_slist_free_all(curl_http_headers_);
800     curl_http_headers_ = nullptr;
801   }
802   if (curl_handle_) {
803     if (curl_multi_handle_) {
804       CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
805                CURLM_OK);
806     }
807     curl_easy_cleanup(curl_handle_);
808     curl_handle_ = nullptr;
809   }
810   if (curl_multi_handle_) {
811     CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
812     curl_multi_handle_ = nullptr;
813   }
814   transfer_in_progress_ = false;
815   transfer_paused_ = false;
816   restart_transfer_on_unpause_ = false;
817 }
818 
GetHttpResponseCode()819 void LibcurlHttpFetcher::GetHttpResponseCode() {
820   long http_response_code = 0;  // NOLINT(runtime/int) - curl needs long.
821   if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
822     // Fake out a valid response code for file:// URLs.
823     http_response_code_ = 299;
824   } else if (curl_easy_getinfo(curl_handle_,
825                                CURLINFO_RESPONSE_CODE,
826                                &http_response_code) == CURLE_OK) {
827     http_response_code_ = static_cast<int>(http_response_code);
828   } else {
829     LOG(ERROR) << "Unable to get http response code from curl_easy_getinfo";
830   }
831 }
832 
GetCurlCode()833 CURLcode LibcurlHttpFetcher::GetCurlCode() {
834   CURLcode curl_code = CURLE_OK;
835   while (true) {
836     // Repeated calls to |curl_multi_info_read| will return a new struct each
837     // time, until a NULL is returned as a signal that there is no more to get
838     // at this point.
839     int msgs_in_queue;
840     CURLMsg* curl_msg =
841         curl_multi_info_read(curl_multi_handle_, &msgs_in_queue);
842     if (curl_msg == nullptr)
843       break;
844     // When |curl_msg| is |CURLMSG_DONE|, a transfer of an easy handle is done,
845     // and then data contains the return code for this transfer.
846     if (curl_msg->msg == CURLMSG_DONE) {
847       // Make sure |curl_multi_handle_| has one and only one easy handle
848       // |curl_handle_|.
849       CHECK_EQ(curl_handle_, curl_msg->easy_handle);
850       // Transfer return code reference:
851       // https://curl.haxx.se/libcurl/c/libcurl-errors.html
852       curl_code = curl_msg->data.result;
853     }
854   }
855 
856   // Gets connection error if exists.
857   long connect_error = 0;  // NOLINT(runtime/int) - curl needs long.
858   CURLcode res =
859       curl_easy_getinfo(curl_handle_, CURLINFO_OS_ERRNO, &connect_error);
860   if (res == CURLE_OK && connect_error) {
861     LOG(ERROR) << "Connect error code from the OS: " << connect_error;
862   }
863 
864   return curl_code;
865 }
866 
UpdateState(bool failed_to_resolve_host)867 void UnresolvedHostStateMachine::UpdateState(bool failed_to_resolve_host) {
868   switch (state_) {
869     case State::kInit:
870       if (failed_to_resolve_host) {
871         state_ = State::kRetry;
872       }
873       break;
874     case State::kRetry:
875       if (failed_to_resolve_host) {
876         state_ = State::kNotRetry;
877       } else {
878         state_ = State::kRetriedSuccess;
879       }
880       break;
881     case State::kNotRetry:
882       break;
883     case State::kRetriedSuccess:
884       break;
885     default:
886       NOTREACHED();
887       break;
888   }
889 }
890 
891 }  // namespace chromeos_update_engine
892