libcurl_http_fetcher.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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. #include "update_engine/libcurl_http_fetcher.h"
  17. #include <sys/types.h>
  18. #include <unistd.h>
  19. #include <algorithm>
  20. #include <string>
  21. #include <base/bind.h>
  22. #include <base/format_macros.h>
  23. #include <base/location.h>
  24. #include <base/logging.h>
  25. #include <base/strings/string_util.h>
  26. #include <base/strings/stringprintf.h>
  27. #ifdef __ANDROID__
  28. #include <cutils/qtaguid.h>
  29. #include <private/android_filesystem_config.h>
  30. #endif // __ANDROID__
  31. #include "update_engine/certificate_checker.h"
  32. #include "update_engine/common/hardware_interface.h"
  33. #include "update_engine/common/platform_constants.h"
  34. using base::TimeDelta;
  35. using brillo::MessageLoop;
  36. using std::max;
  37. using std::string;
  38. // This is a concrete implementation of HttpFetcher that uses libcurl to do the
  39. // http work.
  40. namespace chromeos_update_engine {
  41. namespace {
  42. const int kNoNetworkRetrySeconds = 10;
  43. // libcurl's CURLOPT_SOCKOPTFUNCTION callback function. Called after the socket
  44. // is created but before it is connected. This callback tags the created socket
  45. // so the network usage can be tracked in Android.
  46. int LibcurlSockoptCallback(void* /* clientp */,
  47. curl_socket_t curlfd,
  48. curlsocktype /* purpose */) {
  49. #ifdef __ANDROID__
  50. // Socket tag used by all network sockets. See qtaguid kernel module for
  51. // stats.
  52. const int kUpdateEngineSocketTag = 0x55417243; // "CrAU" in little-endian.
  53. qtaguid_tagSocket(curlfd, kUpdateEngineSocketTag, AID_OTA_UPDATE);
  54. #endif // __ANDROID__
  55. return CURL_SOCKOPT_OK;
  56. }
  57. } // namespace
  58. // static
  59. int LibcurlHttpFetcher::LibcurlCloseSocketCallback(void* clientp,
  60. curl_socket_t item) {
  61. #ifdef __ANDROID__
  62. qtaguid_untagSocket(item);
  63. #endif // __ANDROID__
  64. LibcurlHttpFetcher* fetcher = static_cast<LibcurlHttpFetcher*>(clientp);
  65. // Stop watching the socket before closing it.
  66. for (size_t t = 0; t < arraysize(fetcher->fd_task_maps_); ++t) {
  67. const auto fd_task_pair = fetcher->fd_task_maps_[t].find(item);
  68. if (fd_task_pair != fetcher->fd_task_maps_[t].end()) {
  69. if (!MessageLoop::current()->CancelTask(fd_task_pair->second)) {
  70. LOG(WARNING) << "Error canceling the watch task "
  71. << fd_task_pair->second << " for "
  72. << (t ? "writing" : "reading") << " the fd " << item;
  73. }
  74. fetcher->fd_task_maps_[t].erase(item);
  75. }
  76. }
  77. // Documentation for this callback says to return 0 on success or 1 on error.
  78. if (!IGNORE_EINTR(close(item)))
  79. return 0;
  80. return 1;
  81. }
  82. LibcurlHttpFetcher::LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
  83. HardwareInterface* hardware)
  84. : HttpFetcher(proxy_resolver), hardware_(hardware) {
  85. // Dev users want a longer timeout (180 seconds) because they may
  86. // be waiting on the dev server to build an image.
  87. if (!hardware_->IsOfficialBuild())
  88. low_speed_time_seconds_ = kDownloadDevModeLowSpeedTimeSeconds;
  89. if (hardware_->IsOOBEEnabled() && !hardware_->IsOOBEComplete(nullptr))
  90. max_retry_count_ = kDownloadMaxRetryCountOobeNotComplete;
  91. }
  92. LibcurlHttpFetcher::~LibcurlHttpFetcher() {
  93. LOG_IF(ERROR, transfer_in_progress_)
  94. << "Destroying the fetcher while a transfer is in progress.";
  95. CancelProxyResolution();
  96. CleanUp();
  97. }
  98. bool LibcurlHttpFetcher::GetProxyType(const string& proxy,
  99. curl_proxytype* out_type) {
  100. if (base::StartsWith(
  101. proxy, "socks5://", base::CompareCase::INSENSITIVE_ASCII) ||
  102. base::StartsWith(
  103. proxy, "socks://", base::CompareCase::INSENSITIVE_ASCII)) {
  104. *out_type = CURLPROXY_SOCKS5_HOSTNAME;
  105. return true;
  106. }
  107. if (base::StartsWith(
  108. proxy, "socks4://", base::CompareCase::INSENSITIVE_ASCII)) {
  109. *out_type = CURLPROXY_SOCKS4A;
  110. return true;
  111. }
  112. if (base::StartsWith(
  113. proxy, "http://", base::CompareCase::INSENSITIVE_ASCII) ||
  114. base::StartsWith(
  115. proxy, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
  116. *out_type = CURLPROXY_HTTP;
  117. return true;
  118. }
  119. if (base::StartsWith(proxy, kNoProxy, base::CompareCase::INSENSITIVE_ASCII)) {
  120. // known failure case. don't log.
  121. return false;
  122. }
  123. LOG(INFO) << "Unknown proxy type: " << proxy;
  124. return false;
  125. }
  126. void LibcurlHttpFetcher::ResumeTransfer(const string& url) {
  127. LOG(INFO) << "Starting/Resuming transfer";
  128. CHECK(!transfer_in_progress_);
  129. url_ = url;
  130. curl_multi_handle_ = curl_multi_init();
  131. CHECK(curl_multi_handle_);
  132. curl_handle_ = curl_easy_init();
  133. CHECK(curl_handle_);
  134. ignore_failure_ = false;
  135. // Tag and untag the socket for network usage stats.
  136. curl_easy_setopt(
  137. curl_handle_, CURLOPT_SOCKOPTFUNCTION, LibcurlSockoptCallback);
  138. curl_easy_setopt(
  139. curl_handle_, CURLOPT_CLOSESOCKETFUNCTION, LibcurlCloseSocketCallback);
  140. curl_easy_setopt(curl_handle_, CURLOPT_CLOSESOCKETDATA, this);
  141. CHECK(HasProxy());
  142. bool is_direct = (GetCurrentProxy() == kNoProxy);
  143. LOG(INFO) << "Using proxy: " << (is_direct ? "no" : "yes");
  144. if (is_direct) {
  145. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXY, ""), CURLE_OK);
  146. } else {
  147. CHECK_EQ(curl_easy_setopt(
  148. curl_handle_, CURLOPT_PROXY, GetCurrentProxy().c_str()),
  149. CURLE_OK);
  150. // Curl seems to require us to set the protocol
  151. curl_proxytype type;
  152. if (GetProxyType(GetCurrentProxy(), &type)) {
  153. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROXYTYPE, type),
  154. CURLE_OK);
  155. }
  156. }
  157. if (post_data_set_) {
  158. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_POST, 1), CURLE_OK);
  159. CHECK_EQ(
  160. curl_easy_setopt(curl_handle_, CURLOPT_POSTFIELDS, post_data_.data()),
  161. CURLE_OK);
  162. CHECK_EQ(curl_easy_setopt(
  163. curl_handle_, CURLOPT_POSTFIELDSIZE, post_data_.size()),
  164. CURLE_OK);
  165. }
  166. // Setup extra HTTP headers.
  167. if (curl_http_headers_) {
  168. curl_slist_free_all(curl_http_headers_);
  169. curl_http_headers_ = nullptr;
  170. }
  171. for (const auto& header : extra_headers_) {
  172. // curl_slist_append() copies the string.
  173. curl_http_headers_ =
  174. curl_slist_append(curl_http_headers_, header.second.c_str());
  175. }
  176. if (post_data_set_) {
  177. // Set the Content-Type HTTP header, if one was specifically set.
  178. if (post_content_type_ != kHttpContentTypeUnspecified) {
  179. const string content_type_attr = base::StringPrintf(
  180. "Content-Type: %s", GetHttpContentTypeString(post_content_type_));
  181. curl_http_headers_ =
  182. curl_slist_append(curl_http_headers_, content_type_attr.c_str());
  183. } else {
  184. LOG(WARNING) << "no content type set, using libcurl default";
  185. }
  186. }
  187. CHECK_EQ(
  188. curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, curl_http_headers_),
  189. CURLE_OK);
  190. if (bytes_downloaded_ > 0 || download_length_) {
  191. // Resume from where we left off.
  192. resume_offset_ = bytes_downloaded_;
  193. CHECK_GE(resume_offset_, 0);
  194. // Compute end offset, if one is specified. As per HTTP specification, this
  195. // is an inclusive boundary. Make sure it doesn't overflow.
  196. size_t end_offset = 0;
  197. if (download_length_) {
  198. end_offset = static_cast<size_t>(resume_offset_) + download_length_ - 1;
  199. CHECK_LE((size_t)resume_offset_, end_offset);
  200. }
  201. // Create a string representation of the desired range.
  202. string range_str = base::StringPrintf(
  203. "%" PRIu64 "-", static_cast<uint64_t>(resume_offset_));
  204. if (end_offset)
  205. range_str += std::to_string(end_offset);
  206. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_RANGE, range_str.c_str()),
  207. CURLE_OK);
  208. }
  209. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, this), CURLE_OK);
  210. CHECK_EQ(
  211. curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, StaticLibcurlWrite),
  212. CURLE_OK);
  213. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_URL, url_.c_str()), CURLE_OK);
  214. // If the connection drops under |low_speed_limit_bps_| (10
  215. // bytes/sec by default) for |low_speed_time_seconds_| (90 seconds,
  216. // 180 on non-official builds), reconnect.
  217. CHECK_EQ(curl_easy_setopt(
  218. curl_handle_, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit_bps_),
  219. CURLE_OK);
  220. CHECK_EQ(curl_easy_setopt(
  221. curl_handle_, CURLOPT_LOW_SPEED_TIME, low_speed_time_seconds_),
  222. CURLE_OK);
  223. CHECK_EQ(curl_easy_setopt(
  224. curl_handle_, CURLOPT_CONNECTTIMEOUT, connect_timeout_seconds_),
  225. CURLE_OK);
  226. // By default, libcurl doesn't follow redirections. Allow up to
  227. // |kDownloadMaxRedirects| redirections.
  228. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_FOLLOWLOCATION, 1), CURLE_OK);
  229. CHECK_EQ(
  230. curl_easy_setopt(curl_handle_, CURLOPT_MAXREDIRS, kDownloadMaxRedirects),
  231. CURLE_OK);
  232. // Lock down the appropriate curl options for HTTP or HTTPS depending on
  233. // the url.
  234. if (hardware_->IsOfficialBuild()) {
  235. if (base::StartsWith(
  236. url_, "http://", base::CompareCase::INSENSITIVE_ASCII)) {
  237. SetCurlOptionsForHttp();
  238. } else if (base::StartsWith(
  239. url_, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
  240. SetCurlOptionsForHttps();
  241. #if !USE_OMAHA
  242. } else if (base::StartsWith(
  243. url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
  244. SetCurlOptionsForFile();
  245. #endif
  246. } else {
  247. LOG(ERROR) << "Received invalid URI: " << url_;
  248. // Lock down to no protocol supported for the transfer.
  249. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, 0), CURLE_OK);
  250. }
  251. } else {
  252. LOG(INFO) << "Not setting http(s) curl options because we are "
  253. << "running a dev/test image";
  254. }
  255. CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
  256. transfer_in_progress_ = true;
  257. }
  258. // Lock down only the protocol in case of HTTP.
  259. void LibcurlHttpFetcher::SetCurlOptionsForHttp() {
  260. LOG(INFO) << "Setting up curl options for HTTP";
  261. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTP),
  262. CURLE_OK);
  263. CHECK_EQ(
  264. curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP),
  265. CURLE_OK);
  266. }
  267. // Security lock-down in official builds: makes sure that peer certificate
  268. // verification is enabled, restricts the set of trusted certificates,
  269. // restricts protocols to HTTPS, restricts ciphers to HIGH.
  270. void LibcurlHttpFetcher::SetCurlOptionsForHttps() {
  271. LOG(INFO) << "Setting up curl options for HTTPS";
  272. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, 1), CURLE_OK);
  273. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, 2), CURLE_OK);
  274. CHECK_EQ(curl_easy_setopt(
  275. curl_handle_, CURLOPT_CAPATH, constants::kCACertificatesPath),
  276. CURLE_OK);
  277. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS),
  278. CURLE_OK);
  279. CHECK_EQ(
  280. curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS),
  281. CURLE_OK);
  282. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_SSL_CIPHER_LIST, "HIGH:!ADH"),
  283. CURLE_OK);
  284. if (server_to_check_ != ServerToCheck::kNone) {
  285. CHECK_EQ(
  286. curl_easy_setopt(curl_handle_, CURLOPT_SSL_CTX_DATA, &server_to_check_),
  287. CURLE_OK);
  288. CHECK_EQ(curl_easy_setopt(curl_handle_,
  289. CURLOPT_SSL_CTX_FUNCTION,
  290. CertificateChecker::ProcessSSLContext),
  291. CURLE_OK);
  292. }
  293. }
  294. // Lock down only the protocol in case of a local file.
  295. void LibcurlHttpFetcher::SetCurlOptionsForFile() {
  296. LOG(INFO) << "Setting up curl options for FILE";
  297. CHECK_EQ(curl_easy_setopt(curl_handle_, CURLOPT_PROTOCOLS, CURLPROTO_FILE),
  298. CURLE_OK);
  299. CHECK_EQ(
  300. curl_easy_setopt(curl_handle_, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_FILE),
  301. CURLE_OK);
  302. }
  303. // Begins the transfer, which must not have already been started.
  304. void LibcurlHttpFetcher::BeginTransfer(const string& url) {
  305. CHECK(!transfer_in_progress_);
  306. url_ = url;
  307. auto closure =
  308. base::Bind(&LibcurlHttpFetcher::ProxiesResolved, base::Unretained(this));
  309. ResolveProxiesForUrl(url_, closure);
  310. }
  311. void LibcurlHttpFetcher::ProxiesResolved() {
  312. transfer_size_ = -1;
  313. resume_offset_ = 0;
  314. retry_count_ = 0;
  315. no_network_retry_count_ = 0;
  316. http_response_code_ = 0;
  317. terminate_requested_ = false;
  318. sent_byte_ = false;
  319. // If we are paused, we delay these two operations until Unpause is called.
  320. if (transfer_paused_) {
  321. restart_transfer_on_unpause_ = true;
  322. return;
  323. }
  324. ResumeTransfer(url_);
  325. CurlPerformOnce();
  326. }
  327. void LibcurlHttpFetcher::ForceTransferTermination() {
  328. CancelProxyResolution();
  329. CleanUp();
  330. if (delegate_) {
  331. // Note that after the callback returns this object may be destroyed.
  332. delegate_->TransferTerminated(this);
  333. }
  334. }
  335. void LibcurlHttpFetcher::TerminateTransfer() {
  336. if (in_write_callback_) {
  337. terminate_requested_ = true;
  338. } else {
  339. ForceTransferTermination();
  340. }
  341. }
  342. void LibcurlHttpFetcher::SetHeader(const string& header_name,
  343. const string& header_value) {
  344. string header_line = header_name + ": " + header_value;
  345. // Avoid the space if no data on the right side of the semicolon.
  346. if (header_value.empty())
  347. header_line = header_name + ":";
  348. TEST_AND_RETURN(header_line.find('\n') == string::npos);
  349. TEST_AND_RETURN(header_name.find(':') == string::npos);
  350. extra_headers_[base::ToLowerASCII(header_name)] = header_line;
  351. }
  352. void LibcurlHttpFetcher::CurlPerformOnce() {
  353. CHECK(transfer_in_progress_);
  354. int running_handles = 0;
  355. CURLMcode retcode = CURLM_CALL_MULTI_PERFORM;
  356. // libcurl may request that we immediately call curl_multi_perform after it
  357. // returns, so we do. libcurl promises that curl_multi_perform will not block.
  358. while (CURLM_CALL_MULTI_PERFORM == retcode) {
  359. retcode = curl_multi_perform(curl_multi_handle_, &running_handles);
  360. if (terminate_requested_) {
  361. ForceTransferTermination();
  362. return;
  363. }
  364. }
  365. // If the transfer completes while paused, we should ignore the failure once
  366. // the fetcher is unpaused.
  367. if (running_handles == 0 && transfer_paused_ && !ignore_failure_) {
  368. LOG(INFO) << "Connection closed while paused, ignoring failure.";
  369. ignore_failure_ = true;
  370. }
  371. if (running_handles != 0 || transfer_paused_) {
  372. // There's either more work to do or we are paused, so we just keep the
  373. // file descriptors to watch up to date and exit, until we are done with the
  374. // work and we are not paused.
  375. SetupMessageLoopSources();
  376. return;
  377. }
  378. // At this point, the transfer was completed in some way (error, connection
  379. // closed or download finished).
  380. GetHttpResponseCode();
  381. if (http_response_code_) {
  382. LOG(INFO) << "HTTP response code: " << http_response_code_;
  383. no_network_retry_count_ = 0;
  384. } else {
  385. LOG(ERROR) << "Unable to get http response code.";
  386. }
  387. // we're done!
  388. CleanUp();
  389. // TODO(petkov): This temporary code tries to deal with the case where the
  390. // update engine performs an update check while the network is not ready
  391. // (e.g., right after resume). Longer term, we should check if the network
  392. // is online/offline and return an appropriate error code.
  393. if (!sent_byte_ && http_response_code_ == 0 &&
  394. no_network_retry_count_ < no_network_max_retries_) {
  395. no_network_retry_count_++;
  396. retry_task_id_ = MessageLoop::current()->PostDelayedTask(
  397. FROM_HERE,
  398. base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
  399. base::Unretained(this)),
  400. TimeDelta::FromSeconds(kNoNetworkRetrySeconds));
  401. LOG(INFO) << "No HTTP response, retry " << no_network_retry_count_;
  402. } else if ((!sent_byte_ && !IsHttpResponseSuccess()) ||
  403. IsHttpResponseError()) {
  404. // The transfer completed w/ error and we didn't get any bytes.
  405. // If we have another proxy to try, try that.
  406. //
  407. // TODO(garnold) in fact there are two separate cases here: one case is an
  408. // other-than-success return code (including no return code) and no
  409. // received bytes, which is necessary due to the way callbacks are
  410. // currently processing error conditions; the second is an explicit HTTP
  411. // error code, where some data may have been received (as in the case of a
  412. // semi-successful multi-chunk fetch). This is a confusing behavior and
  413. // should be unified into a complete, coherent interface.
  414. LOG(INFO) << "Transfer resulted in an error (" << http_response_code_
  415. << "), " << bytes_downloaded_ << " bytes downloaded";
  416. PopProxy(); // Delete the proxy we just gave up on.
  417. if (HasProxy()) {
  418. // We have another proxy. Retry immediately.
  419. LOG(INFO) << "Retrying with next proxy setting";
  420. retry_task_id_ = MessageLoop::current()->PostTask(
  421. FROM_HERE,
  422. base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
  423. base::Unretained(this)));
  424. } else {
  425. // Out of proxies. Give up.
  426. LOG(INFO) << "No further proxies, indicating transfer complete";
  427. if (delegate_)
  428. delegate_->TransferComplete(this, false); // signal fail
  429. return;
  430. }
  431. } else if ((transfer_size_ >= 0) && (bytes_downloaded_ < transfer_size_)) {
  432. if (!ignore_failure_)
  433. retry_count_++;
  434. LOG(INFO) << "Transfer interrupted after downloading " << bytes_downloaded_
  435. << " of " << transfer_size_ << " bytes. "
  436. << transfer_size_ - bytes_downloaded_ << " bytes remaining "
  437. << "after " << retry_count_ << " attempt(s)";
  438. if (retry_count_ > max_retry_count_) {
  439. LOG(INFO) << "Reached max attempts (" << retry_count_ << ")";
  440. if (delegate_)
  441. delegate_->TransferComplete(this, false); // signal fail
  442. return;
  443. }
  444. // Need to restart transfer
  445. LOG(INFO) << "Restarting transfer to download the remaining bytes";
  446. retry_task_id_ = MessageLoop::current()->PostDelayedTask(
  447. FROM_HERE,
  448. base::Bind(&LibcurlHttpFetcher::RetryTimeoutCallback,
  449. base::Unretained(this)),
  450. TimeDelta::FromSeconds(retry_seconds_));
  451. } else {
  452. LOG(INFO) << "Transfer completed (" << http_response_code_ << "), "
  453. << bytes_downloaded_ << " bytes downloaded";
  454. if (delegate_) {
  455. bool success = IsHttpResponseSuccess();
  456. delegate_->TransferComplete(this, success);
  457. }
  458. return;
  459. }
  460. // If we reach this point is because TransferComplete() was not called in any
  461. // of the previous branches. The delegate is allowed to destroy the object
  462. // once TransferComplete is called so this would be illegal.
  463. ignore_failure_ = false;
  464. }
  465. size_t LibcurlHttpFetcher::LibcurlWrite(void* ptr, size_t size, size_t nmemb) {
  466. // Update HTTP response first.
  467. GetHttpResponseCode();
  468. const size_t payload_size = size * nmemb;
  469. // Do nothing if no payload or HTTP response is an error.
  470. if (payload_size == 0 || !IsHttpResponseSuccess()) {
  471. LOG(INFO) << "HTTP response unsuccessful (" << http_response_code_
  472. << ") or no payload (" << payload_size << "), nothing to do";
  473. return 0;
  474. }
  475. sent_byte_ = true;
  476. {
  477. double transfer_size_double;
  478. CHECK_EQ(curl_easy_getinfo(curl_handle_,
  479. CURLINFO_CONTENT_LENGTH_DOWNLOAD,
  480. &transfer_size_double),
  481. CURLE_OK);
  482. off_t new_transfer_size = static_cast<off_t>(transfer_size_double);
  483. if (new_transfer_size > 0) {
  484. transfer_size_ = resume_offset_ + new_transfer_size;
  485. }
  486. }
  487. bytes_downloaded_ += payload_size;
  488. if (delegate_) {
  489. in_write_callback_ = true;
  490. auto should_terminate = !delegate_->ReceivedBytes(this, ptr, payload_size);
  491. in_write_callback_ = false;
  492. if (should_terminate) {
  493. LOG(INFO) << "Requesting libcurl to terminate transfer.";
  494. // Returning an amount that differs from the received size signals an
  495. // error condition to libcurl, which will cause the transfer to be
  496. // aborted.
  497. return 0;
  498. }
  499. }
  500. return payload_size;
  501. }
  502. void LibcurlHttpFetcher::Pause() {
  503. if (transfer_paused_) {
  504. LOG(ERROR) << "Fetcher already paused.";
  505. return;
  506. }
  507. transfer_paused_ = true;
  508. if (!transfer_in_progress_) {
  509. // If pause before we started a connection, we don't need to notify curl
  510. // about that, we will simply not start the connection later.
  511. return;
  512. }
  513. CHECK(curl_handle_);
  514. CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_ALL), CURLE_OK);
  515. }
  516. void LibcurlHttpFetcher::Unpause() {
  517. if (!transfer_paused_) {
  518. LOG(ERROR) << "Resume attempted when fetcher not paused.";
  519. return;
  520. }
  521. transfer_paused_ = false;
  522. if (restart_transfer_on_unpause_) {
  523. restart_transfer_on_unpause_ = false;
  524. ResumeTransfer(url_);
  525. CurlPerformOnce();
  526. return;
  527. }
  528. if (!transfer_in_progress_) {
  529. // If resumed before starting the connection, there's no need to notify
  530. // anybody. We will simply start the connection once it is time.
  531. return;
  532. }
  533. CHECK(curl_handle_);
  534. CHECK_EQ(curl_easy_pause(curl_handle_, CURLPAUSE_CONT), CURLE_OK);
  535. // Since the transfer is in progress, we need to dispatch a CurlPerformOnce()
  536. // now to let the connection continue, otherwise it would be called by the
  537. // TimeoutCallback but with a delay.
  538. CurlPerformOnce();
  539. }
  540. // This method sets up callbacks with the MessageLoop.
  541. void LibcurlHttpFetcher::SetupMessageLoopSources() {
  542. fd_set fd_read;
  543. fd_set fd_write;
  544. fd_set fd_exc;
  545. FD_ZERO(&fd_read);
  546. FD_ZERO(&fd_write);
  547. FD_ZERO(&fd_exc);
  548. int fd_max = 0;
  549. // Ask libcurl for the set of file descriptors we should track on its
  550. // behalf.
  551. CHECK_EQ(curl_multi_fdset(
  552. curl_multi_handle_, &fd_read, &fd_write, &fd_exc, &fd_max),
  553. CURLM_OK);
  554. // We should iterate through all file descriptors up to libcurl's fd_max or
  555. // the highest one we're tracking, whichever is larger.
  556. for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
  557. if (!fd_task_maps_[t].empty())
  558. fd_max = max(fd_max, fd_task_maps_[t].rbegin()->first);
  559. }
  560. // For each fd, if we're not tracking it, track it. If we are tracking it, but
  561. // libcurl doesn't care about it anymore, stop tracking it. After this loop,
  562. // there should be exactly as many tasks scheduled in fd_task_maps_[0|1] as
  563. // there are read/write fds that we're tracking.
  564. for (int fd = 0; fd <= fd_max; ++fd) {
  565. // Note that fd_exc is unused in the current version of libcurl so is_exc
  566. // should always be false.
  567. bool is_exc = FD_ISSET(fd, &fd_exc) != 0;
  568. bool must_track[2] = {
  569. is_exc || (FD_ISSET(fd, &fd_read) != 0), // track 0 -- read
  570. is_exc || (FD_ISSET(fd, &fd_write) != 0) // track 1 -- write
  571. };
  572. MessageLoop::WatchMode watch_modes[2] = {
  573. MessageLoop::WatchMode::kWatchRead,
  574. MessageLoop::WatchMode::kWatchWrite,
  575. };
  576. for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
  577. auto fd_task_it = fd_task_maps_[t].find(fd);
  578. bool tracked = fd_task_it != fd_task_maps_[t].end();
  579. if (!must_track[t]) {
  580. // If we have an outstanding io_channel, remove it.
  581. if (tracked) {
  582. MessageLoop::current()->CancelTask(fd_task_it->second);
  583. fd_task_maps_[t].erase(fd_task_it);
  584. }
  585. continue;
  586. }
  587. // If we are already tracking this fd, continue -- nothing to do.
  588. if (tracked)
  589. continue;
  590. // Track a new fd.
  591. fd_task_maps_[t][fd] = MessageLoop::current()->WatchFileDescriptor(
  592. FROM_HERE,
  593. fd,
  594. watch_modes[t],
  595. true, // persistent
  596. base::Bind(&LibcurlHttpFetcher::CurlPerformOnce,
  597. base::Unretained(this)));
  598. static int io_counter = 0;
  599. io_counter++;
  600. if (io_counter % 50 == 0) {
  601. LOG(INFO) << "io_counter = " << io_counter;
  602. }
  603. }
  604. }
  605. // Set up a timeout callback for libcurl.
  606. if (timeout_id_ == MessageLoop::kTaskIdNull) {
  607. VLOG(1) << "Setting up timeout source: " << idle_seconds_ << " seconds.";
  608. timeout_id_ = MessageLoop::current()->PostDelayedTask(
  609. FROM_HERE,
  610. base::Bind(&LibcurlHttpFetcher::TimeoutCallback,
  611. base::Unretained(this)),
  612. TimeDelta::FromSeconds(idle_seconds_));
  613. }
  614. }
  615. void LibcurlHttpFetcher::RetryTimeoutCallback() {
  616. retry_task_id_ = MessageLoop::kTaskIdNull;
  617. if (transfer_paused_) {
  618. restart_transfer_on_unpause_ = true;
  619. return;
  620. }
  621. ResumeTransfer(url_);
  622. CurlPerformOnce();
  623. }
  624. void LibcurlHttpFetcher::TimeoutCallback() {
  625. // We always re-schedule the callback, even if we don't want to be called
  626. // anymore. We will remove the event source separately if we don't want to
  627. // be called back.
  628. timeout_id_ = MessageLoop::current()->PostDelayedTask(
  629. FROM_HERE,
  630. base::Bind(&LibcurlHttpFetcher::TimeoutCallback, base::Unretained(this)),
  631. TimeDelta::FromSeconds(idle_seconds_));
  632. // CurlPerformOnce() may call CleanUp(), so we need to schedule our callback
  633. // first, since it could be canceled by this call.
  634. if (transfer_in_progress_)
  635. CurlPerformOnce();
  636. }
  637. void LibcurlHttpFetcher::CleanUp() {
  638. MessageLoop::current()->CancelTask(retry_task_id_);
  639. retry_task_id_ = MessageLoop::kTaskIdNull;
  640. MessageLoop::current()->CancelTask(timeout_id_);
  641. timeout_id_ = MessageLoop::kTaskIdNull;
  642. for (size_t t = 0; t < arraysize(fd_task_maps_); ++t) {
  643. for (const auto& fd_taks_pair : fd_task_maps_[t]) {
  644. if (!MessageLoop::current()->CancelTask(fd_taks_pair.second)) {
  645. LOG(WARNING) << "Error canceling the watch task " << fd_taks_pair.second
  646. << " for " << (t ? "writing" : "reading") << " the fd "
  647. << fd_taks_pair.first;
  648. }
  649. }
  650. fd_task_maps_[t].clear();
  651. }
  652. if (curl_http_headers_) {
  653. curl_slist_free_all(curl_http_headers_);
  654. curl_http_headers_ = nullptr;
  655. }
  656. if (curl_handle_) {
  657. if (curl_multi_handle_) {
  658. CHECK_EQ(curl_multi_remove_handle(curl_multi_handle_, curl_handle_),
  659. CURLM_OK);
  660. }
  661. curl_easy_cleanup(curl_handle_);
  662. curl_handle_ = nullptr;
  663. }
  664. if (curl_multi_handle_) {
  665. CHECK_EQ(curl_multi_cleanup(curl_multi_handle_), CURLM_OK);
  666. curl_multi_handle_ = nullptr;
  667. }
  668. transfer_in_progress_ = false;
  669. transfer_paused_ = false;
  670. restart_transfer_on_unpause_ = false;
  671. }
  672. void LibcurlHttpFetcher::GetHttpResponseCode() {
  673. long http_response_code = 0; // NOLINT(runtime/int) - curl needs long.
  674. if (base::StartsWith(url_, "file://", base::CompareCase::INSENSITIVE_ASCII)) {
  675. // Fake out a valid response code for file:// URLs.
  676. http_response_code_ = 299;
  677. } else if (curl_easy_getinfo(curl_handle_,
  678. CURLINFO_RESPONSE_CODE,
  679. &http_response_code) == CURLE_OK) {
  680. http_response_code_ = static_cast<int>(http_response_code);
  681. }
  682. }
  683. } // namespace chromeos_update_engine