httpfetch.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "httpfetch.h"
  17. #include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf()
  18. #include <iostream>
  19. #include <sstream>
  20. #include <list>
  21. #include <unordered_map>
  22. #include <cerrno>
  23. #include <mutex>
  24. #include "network/socket.h" // for select()
  25. #include "threading/event.h"
  26. #include "config.h"
  27. #include "exceptions.h"
  28. #include "debug.h"
  29. #include "log.h"
  30. #include "util/container.h"
  31. #include "util/thread.h"
  32. #include "version.h"
  33. #include "settings.h"
  34. #include "noise.h"
  35. static std::mutex g_httpfetch_mutex;
  36. static std::unordered_map<u64, std::queue<HTTPFetchResult>>
  37. g_httpfetch_results;
  38. static PcgRandom g_callerid_randomness;
  39. HTTPFetchRequest::HTTPFetchRequest() :
  40. timeout(g_settings->getS32("curl_timeout")),
  41. connect_timeout(10 * 1000),
  42. useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")")
  43. {
  44. }
  45. static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
  46. {
  47. u64 caller = fetch_result.caller;
  48. if (caller != HTTPFETCH_DISCARD) {
  49. MutexAutoLock lock(g_httpfetch_mutex);
  50. g_httpfetch_results[caller].emplace(fetch_result);
  51. }
  52. }
  53. static void httpfetch_request_clear(u64 caller);
  54. u64 httpfetch_caller_alloc()
  55. {
  56. MutexAutoLock lock(g_httpfetch_mutex);
  57. // Check each caller ID except reserved ones
  58. for (u64 caller = HTTPFETCH_CID_START; caller != 0; ++caller) {
  59. auto it = g_httpfetch_results.find(caller);
  60. if (it == g_httpfetch_results.end()) {
  61. verbosestream << "httpfetch_caller_alloc: allocating "
  62. << caller << std::endl;
  63. // Access element to create it
  64. g_httpfetch_results[caller];
  65. return caller;
  66. }
  67. }
  68. FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
  69. }
  70. u64 httpfetch_caller_alloc_secure()
  71. {
  72. MutexAutoLock lock(g_httpfetch_mutex);
  73. // Generate random caller IDs and make sure they're not
  74. // already used or reserved.
  75. // Give up after 100 tries to prevent infinite loop
  76. size_t tries = 100;
  77. u64 caller;
  78. do {
  79. caller = (((u64) g_callerid_randomness.next()) << 32) |
  80. g_callerid_randomness.next();
  81. if (--tries < 1) {
  82. FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs");
  83. return HTTPFETCH_DISCARD;
  84. }
  85. } while (caller >= HTTPFETCH_CID_START &&
  86. g_httpfetch_results.find(caller) != g_httpfetch_results.end());
  87. verbosestream << "httpfetch_caller_alloc_secure: allocating "
  88. << caller << std::endl;
  89. // Access element to create it
  90. g_httpfetch_results[caller];
  91. return caller;
  92. }
  93. void httpfetch_caller_free(u64 caller)
  94. {
  95. verbosestream<<"httpfetch_caller_free: freeing "
  96. <<caller<<std::endl;
  97. httpfetch_request_clear(caller);
  98. if (caller != HTTPFETCH_DISCARD) {
  99. MutexAutoLock lock(g_httpfetch_mutex);
  100. g_httpfetch_results.erase(caller);
  101. }
  102. }
  103. bool httpfetch_async_get(u64 caller, HTTPFetchResult &fetch_result)
  104. {
  105. MutexAutoLock lock(g_httpfetch_mutex);
  106. // Check that caller exists
  107. auto it = g_httpfetch_results.find(caller);
  108. if (it == g_httpfetch_results.end())
  109. return false;
  110. // Check that result queue is nonempty
  111. std::queue<HTTPFetchResult> &caller_results = it->second;
  112. if (caller_results.empty())
  113. return false;
  114. // Pop first result
  115. fetch_result = std::move(caller_results.front());
  116. caller_results.pop();
  117. return true;
  118. }
  119. #if USE_CURL
  120. #include <curl/curl.h>
  121. /*
  122. USE_CURL is on: use cURL based httpfetch implementation
  123. */
  124. static size_t httpfetch_writefunction(
  125. char *ptr, size_t size, size_t nmemb, void *userdata)
  126. {
  127. std::ostringstream *stream = (std::ostringstream*)userdata;
  128. size_t count = size * nmemb;
  129. stream->write(ptr, count);
  130. return count;
  131. }
  132. static size_t httpfetch_discardfunction(
  133. char *ptr, size_t size, size_t nmemb, void *userdata)
  134. {
  135. return size * nmemb;
  136. }
  137. class CurlHandlePool
  138. {
  139. std::list<CURL*> handles;
  140. public:
  141. CurlHandlePool() = default;
  142. ~CurlHandlePool()
  143. {
  144. for (std::list<CURL*>::iterator it = handles.begin();
  145. it != handles.end(); ++it) {
  146. curl_easy_cleanup(*it);
  147. }
  148. }
  149. CURL * alloc()
  150. {
  151. CURL *curl;
  152. if (handles.empty()) {
  153. curl = curl_easy_init();
  154. if (curl == NULL) {
  155. errorstream<<"curl_easy_init returned NULL"<<std::endl;
  156. }
  157. }
  158. else {
  159. curl = handles.front();
  160. handles.pop_front();
  161. }
  162. return curl;
  163. }
  164. void free(CURL *handle)
  165. {
  166. if (handle)
  167. handles.push_back(handle);
  168. }
  169. };
  170. class HTTPFetchOngoing
  171. {
  172. public:
  173. HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool);
  174. ~HTTPFetchOngoing();
  175. CURLcode start(CURLM *multi);
  176. const HTTPFetchResult * complete(CURLcode res);
  177. const HTTPFetchRequest &getRequest() const { return request; };
  178. const CURL *getEasyHandle() const { return curl; };
  179. private:
  180. CurlHandlePool *pool;
  181. CURL *curl;
  182. CURLM *multi;
  183. HTTPFetchRequest request;
  184. HTTPFetchResult result;
  185. std::ostringstream oss;
  186. struct curl_slist *http_header;
  187. curl_httppost *post;
  188. };
  189. HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
  190. CurlHandlePool *pool_):
  191. pool(pool_),
  192. curl(NULL),
  193. multi(NULL),
  194. request(request_),
  195. result(request_),
  196. oss(std::ios::binary),
  197. http_header(NULL),
  198. post(NULL)
  199. {
  200. curl = pool->alloc();
  201. if (curl == NULL) {
  202. return;
  203. }
  204. // Set static cURL options
  205. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  206. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  207. curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3);
  208. curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
  209. std::string bind_address = g_settings->get("bind_address");
  210. if (!bind_address.empty()) {
  211. curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
  212. }
  213. if (!g_settings->getBool("enable_ipv6")) {
  214. curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  215. }
  216. #if LIBCURL_VERSION_NUM >= 0x071304
  217. // Restrict protocols so that curl vulnerabilities in
  218. // other protocols don't affect us.
  219. // These settings were introduced in curl 7.19.4.
  220. long protocols =
  221. CURLPROTO_HTTP |
  222. CURLPROTO_HTTPS |
  223. CURLPROTO_FTP |
  224. CURLPROTO_FTPS;
  225. curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
  226. curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
  227. #endif
  228. // Set cURL options based on HTTPFetchRequest
  229. curl_easy_setopt(curl, CURLOPT_URL,
  230. request.url.c_str());
  231. curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
  232. request.timeout);
  233. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
  234. request.connect_timeout);
  235. if (!request.useragent.empty())
  236. curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
  237. // Set up a write callback that writes to the
  238. // ostringstream ongoing->oss, unless the data
  239. // is to be discarded
  240. if (request.caller == HTTPFETCH_DISCARD) {
  241. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  242. httpfetch_discardfunction);
  243. curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
  244. } else {
  245. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  246. httpfetch_writefunction);
  247. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
  248. }
  249. // Set data from fields or raw_data
  250. if (request.multipart) {
  251. curl_httppost *last = NULL;
  252. for (StringMap::iterator it = request.fields.begin();
  253. it != request.fields.end(); ++it) {
  254. curl_formadd(&post, &last,
  255. CURLFORM_NAMELENGTH, it->first.size(),
  256. CURLFORM_PTRNAME, it->first.c_str(),
  257. CURLFORM_CONTENTSLENGTH, it->second.size(),
  258. CURLFORM_PTRCONTENTS, it->second.c_str(),
  259. CURLFORM_END);
  260. }
  261. curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
  262. // request.post_fields must now *never* be
  263. // modified until CURLOPT_HTTPPOST is cleared
  264. } else {
  265. switch (request.method) {
  266. case HTTP_GET:
  267. curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
  268. break;
  269. case HTTP_POST:
  270. curl_easy_setopt(curl, CURLOPT_POST, 1);
  271. break;
  272. case HTTP_PUT:
  273. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
  274. break;
  275. case HTTP_DELETE:
  276. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
  277. break;
  278. }
  279. if (request.method != HTTP_GET) {
  280. if (!request.raw_data.empty()) {
  281. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
  282. request.raw_data.size());
  283. curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
  284. request.raw_data.c_str());
  285. } else if (!request.fields.empty()) {
  286. std::string str;
  287. for (auto &field : request.fields) {
  288. if (!str.empty())
  289. str += "&";
  290. str += urlencode(field.first);
  291. str += "=";
  292. str += urlencode(field.second);
  293. }
  294. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
  295. str.size());
  296. curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
  297. str.c_str());
  298. }
  299. }
  300. }
  301. // Set additional HTTP headers
  302. for (const std::string &extra_header : request.extra_headers) {
  303. http_header = curl_slist_append(http_header, extra_header.c_str());
  304. }
  305. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
  306. if (!g_settings->getBool("curl_verify_cert")) {
  307. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
  308. }
  309. }
  310. CURLcode HTTPFetchOngoing::start(CURLM *multi_)
  311. {
  312. if (!curl)
  313. return CURLE_FAILED_INIT;
  314. if (!multi_) {
  315. // Easy interface (sync)
  316. return curl_easy_perform(curl);
  317. }
  318. // Multi interface (async)
  319. CURLMcode mres = curl_multi_add_handle(multi_, curl);
  320. if (mres != CURLM_OK) {
  321. errorstream << "curl_multi_add_handle"
  322. << " returned error code " << mres
  323. << std::endl;
  324. return CURLE_FAILED_INIT;
  325. }
  326. multi = multi_; // store for curl_multi_remove_handle
  327. return CURLE_OK;
  328. }
  329. const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
  330. {
  331. result.succeeded = (res == CURLE_OK);
  332. result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
  333. result.data = oss.str();
  334. // Get HTTP/FTP response code
  335. result.response_code = 0;
  336. if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
  337. &result.response_code) != CURLE_OK)) {
  338. // We failed to get a return code, make sure it is still 0
  339. result.response_code = 0;
  340. }
  341. if (res != CURLE_OK) {
  342. errorstream << "HTTPFetch for " << request.url << " failed ("
  343. << curl_easy_strerror(res) << ")" << std::endl;
  344. } else if (result.response_code >= 400) {
  345. errorstream << "HTTPFetch for " << request.url
  346. << " returned response code " << result.response_code
  347. << std::endl;
  348. if (result.caller == HTTPFETCH_PRINT_ERR && !result.data.empty()) {
  349. errorstream << "Response body:" << std::endl;
  350. safe_print_string(errorstream, result.data);
  351. errorstream << std::endl;
  352. }
  353. }
  354. return &result;
  355. }
  356. HTTPFetchOngoing::~HTTPFetchOngoing()
  357. {
  358. if (multi) {
  359. CURLMcode mres = curl_multi_remove_handle(multi, curl);
  360. if (mres != CURLM_OK) {
  361. errorstream << "curl_multi_remove_handle"
  362. << " returned error code " << mres
  363. << std::endl;
  364. }
  365. }
  366. // Set safe options for the reusable cURL handle
  367. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  368. httpfetch_discardfunction);
  369. curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
  370. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
  371. if (http_header) {
  372. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
  373. curl_slist_free_all(http_header);
  374. }
  375. if (post) {
  376. curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
  377. curl_formfree(post);
  378. }
  379. // Store the cURL handle for reuse
  380. pool->free(curl);
  381. }
  382. class CurlFetchThread : public Thread
  383. {
  384. protected:
  385. enum RequestType {
  386. RT_FETCH,
  387. RT_CLEAR,
  388. RT_WAKEUP,
  389. };
  390. struct Request {
  391. RequestType type;
  392. HTTPFetchRequest fetch_request;
  393. Event *event;
  394. };
  395. CURLM *m_multi;
  396. MutexedQueue<Request> m_requests;
  397. size_t m_parallel_limit;
  398. // Variables exclusively used within thread
  399. std::vector<HTTPFetchOngoing*> m_all_ongoing;
  400. std::list<HTTPFetchRequest> m_queued_fetches;
  401. public:
  402. CurlFetchThread(int parallel_limit) :
  403. Thread("CurlFetch")
  404. {
  405. if (parallel_limit >= 1)
  406. m_parallel_limit = parallel_limit;
  407. else
  408. m_parallel_limit = 1;
  409. }
  410. void requestFetch(const HTTPFetchRequest &fetch_request)
  411. {
  412. Request req;
  413. req.type = RT_FETCH;
  414. req.fetch_request = fetch_request;
  415. req.event = NULL;
  416. m_requests.push_back(req);
  417. }
  418. void requestClear(u64 caller, Event *event)
  419. {
  420. Request req;
  421. req.type = RT_CLEAR;
  422. req.fetch_request.caller = caller;
  423. req.event = event;
  424. m_requests.push_back(req);
  425. }
  426. void requestWakeUp()
  427. {
  428. Request req;
  429. req.type = RT_WAKEUP;
  430. req.event = NULL;
  431. m_requests.push_back(req);
  432. }
  433. protected:
  434. // Handle a request from some other thread
  435. // E.g. new fetch; clear fetches for one caller; wake up
  436. void processRequest(const Request &req)
  437. {
  438. if (req.type == RT_FETCH) {
  439. // New fetch, queue until there are less
  440. // than m_parallel_limit ongoing fetches
  441. m_queued_fetches.push_back(req.fetch_request);
  442. // see processQueued() for what happens next
  443. }
  444. else if (req.type == RT_CLEAR) {
  445. u64 caller = req.fetch_request.caller;
  446. // Abort all ongoing fetches for the caller
  447. for (std::vector<HTTPFetchOngoing*>::iterator
  448. it = m_all_ongoing.begin();
  449. it != m_all_ongoing.end();) {
  450. if ((*it)->getRequest().caller == caller) {
  451. delete (*it);
  452. it = m_all_ongoing.erase(it);
  453. } else {
  454. ++it;
  455. }
  456. }
  457. // Also abort all queued fetches for the caller
  458. for (std::list<HTTPFetchRequest>::iterator
  459. it = m_queued_fetches.begin();
  460. it != m_queued_fetches.end();) {
  461. if ((*it).caller == caller)
  462. it = m_queued_fetches.erase(it);
  463. else
  464. ++it;
  465. }
  466. }
  467. else if (req.type == RT_WAKEUP) {
  468. // Wakeup: Nothing to do, thread is awake at this point
  469. }
  470. if (req.event != NULL)
  471. req.event->signal();
  472. }
  473. // Start new ongoing fetches if m_parallel_limit allows
  474. void processQueued(CurlHandlePool *pool)
  475. {
  476. while (m_all_ongoing.size() < m_parallel_limit &&
  477. !m_queued_fetches.empty()) {
  478. HTTPFetchRequest request = m_queued_fetches.front();
  479. m_queued_fetches.pop_front();
  480. // Create ongoing fetch data and make a cURL handle
  481. // Set cURL options based on HTTPFetchRequest
  482. HTTPFetchOngoing *ongoing =
  483. new HTTPFetchOngoing(request, pool);
  484. // Initiate the connection (curl_multi_add_handle)
  485. CURLcode res = ongoing->start(m_multi);
  486. if (res == CURLE_OK) {
  487. m_all_ongoing.push_back(ongoing);
  488. }
  489. else {
  490. httpfetch_deliver_result(*ongoing->complete(res));
  491. delete ongoing;
  492. }
  493. }
  494. }
  495. // Process CURLMsg (indicates completion of a fetch)
  496. void processCurlMessage(CURLMsg *msg)
  497. {
  498. // Determine which ongoing fetch the message pertains to
  499. size_t i = 0;
  500. bool found = false;
  501. for (i = 0; i < m_all_ongoing.size(); ++i) {
  502. if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
  503. found = true;
  504. break;
  505. }
  506. }
  507. if (msg->msg == CURLMSG_DONE && found) {
  508. // m_all_ongoing[i] succeeded or failed.
  509. HTTPFetchOngoing *ongoing = m_all_ongoing[i];
  510. httpfetch_deliver_result(*ongoing->complete(msg->data.result));
  511. delete ongoing;
  512. m_all_ongoing.erase(m_all_ongoing.begin() + i);
  513. }
  514. }
  515. // Wait for a request from another thread, or timeout elapses
  516. void waitForRequest(long timeout)
  517. {
  518. if (m_queued_fetches.empty()) {
  519. try {
  520. Request req = m_requests.pop_front(timeout);
  521. processRequest(req);
  522. }
  523. catch (ItemNotFoundException &e) {}
  524. }
  525. }
  526. // Wait until some IO happens, or timeout elapses
  527. void waitForIO(long timeout)
  528. {
  529. fd_set read_fd_set;
  530. fd_set write_fd_set;
  531. fd_set exc_fd_set;
  532. int max_fd;
  533. long select_timeout = -1;
  534. struct timeval select_tv;
  535. CURLMcode mres;
  536. FD_ZERO(&read_fd_set);
  537. FD_ZERO(&write_fd_set);
  538. FD_ZERO(&exc_fd_set);
  539. mres = curl_multi_fdset(m_multi, &read_fd_set,
  540. &write_fd_set, &exc_fd_set, &max_fd);
  541. if (mres != CURLM_OK) {
  542. errorstream<<"curl_multi_fdset"
  543. <<" returned error code "<<mres
  544. <<std::endl;
  545. select_timeout = 0;
  546. }
  547. mres = curl_multi_timeout(m_multi, &select_timeout);
  548. if (mres != CURLM_OK) {
  549. errorstream<<"curl_multi_timeout"
  550. <<" returned error code "<<mres
  551. <<std::endl;
  552. select_timeout = 0;
  553. }
  554. // Limit timeout so new requests get through
  555. if (select_timeout < 0 || select_timeout > timeout)
  556. select_timeout = timeout;
  557. if (select_timeout > 0) {
  558. // in Winsock it is forbidden to pass three empty
  559. // fd_sets to select(), so in that case use sleep_ms
  560. if (max_fd != -1) {
  561. select_tv.tv_sec = select_timeout / 1000;
  562. select_tv.tv_usec = (select_timeout % 1000) * 1000;
  563. int retval = select(max_fd + 1, &read_fd_set,
  564. &write_fd_set, &exc_fd_set,
  565. &select_tv);
  566. if (retval == -1) {
  567. #ifdef _WIN32
  568. errorstream<<"select returned error code "
  569. <<WSAGetLastError()<<std::endl;
  570. #else
  571. errorstream<<"select returned error code "
  572. <<errno<<std::endl;
  573. #endif
  574. }
  575. }
  576. else {
  577. sleep_ms(select_timeout);
  578. }
  579. }
  580. }
  581. void *run()
  582. {
  583. CurlHandlePool pool;
  584. m_multi = curl_multi_init();
  585. if (m_multi == NULL) {
  586. errorstream<<"curl_multi_init returned NULL\n";
  587. return NULL;
  588. }
  589. FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
  590. while (!stopRequested()) {
  591. BEGIN_DEBUG_EXCEPTION_HANDLER
  592. /*
  593. Handle new async requests
  594. */
  595. while (!m_requests.empty()) {
  596. Request req = m_requests.pop_frontNoEx();
  597. processRequest(req);
  598. }
  599. processQueued(&pool);
  600. /*
  601. Handle ongoing async requests
  602. */
  603. int still_ongoing = 0;
  604. while (curl_multi_perform(m_multi, &still_ongoing) ==
  605. CURLM_CALL_MULTI_PERFORM)
  606. /* noop */;
  607. /*
  608. Handle completed async requests
  609. */
  610. if (still_ongoing < (int) m_all_ongoing.size()) {
  611. CURLMsg *msg;
  612. int msgs_in_queue;
  613. msg = curl_multi_info_read(m_multi, &msgs_in_queue);
  614. while (msg != NULL) {
  615. processCurlMessage(msg);
  616. msg = curl_multi_info_read(m_multi, &msgs_in_queue);
  617. }
  618. }
  619. /*
  620. If there are ongoing requests, wait for data
  621. (with a timeout of 100ms so that new requests
  622. can be processed).
  623. If no ongoing requests, wait for a new request.
  624. (Possibly an empty request that signals
  625. that the thread should be stopped.)
  626. */
  627. if (m_all_ongoing.empty())
  628. waitForRequest(100000000);
  629. else
  630. waitForIO(100);
  631. END_DEBUG_EXCEPTION_HANDLER
  632. }
  633. // Call curl_multi_remove_handle and cleanup easy handles
  634. for (HTTPFetchOngoing *i : m_all_ongoing) {
  635. delete i;
  636. }
  637. m_all_ongoing.clear();
  638. m_queued_fetches.clear();
  639. CURLMcode mres = curl_multi_cleanup(m_multi);
  640. if (mres != CURLM_OK) {
  641. errorstream<<"curl_multi_cleanup"
  642. <<" returned error code "<<mres
  643. <<std::endl;
  644. }
  645. return NULL;
  646. }
  647. };
  648. CurlFetchThread *g_httpfetch_thread = NULL;
  649. void httpfetch_init(int parallel_limit)
  650. {
  651. verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
  652. <<std::endl;
  653. CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
  654. FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
  655. g_httpfetch_thread = new CurlFetchThread(parallel_limit);
  656. // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
  657. u64 randbuf[2];
  658. porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
  659. g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
  660. }
  661. void httpfetch_cleanup()
  662. {
  663. verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
  664. if (g_httpfetch_thread) {
  665. g_httpfetch_thread->stop();
  666. g_httpfetch_thread->requestWakeUp();
  667. g_httpfetch_thread->wait();
  668. delete g_httpfetch_thread;
  669. }
  670. curl_global_cleanup();
  671. }
  672. void httpfetch_async(const HTTPFetchRequest &fetch_request)
  673. {
  674. g_httpfetch_thread->requestFetch(fetch_request);
  675. if (!g_httpfetch_thread->isRunning())
  676. g_httpfetch_thread->start();
  677. }
  678. static void httpfetch_request_clear(u64 caller)
  679. {
  680. if (g_httpfetch_thread->isRunning()) {
  681. Event event;
  682. g_httpfetch_thread->requestClear(caller, &event);
  683. event.wait();
  684. } else {
  685. g_httpfetch_thread->requestClear(caller, NULL);
  686. }
  687. }
  688. void httpfetch_sync(const HTTPFetchRequest &fetch_request,
  689. HTTPFetchResult &fetch_result)
  690. {
  691. // Create ongoing fetch data and make a cURL handle
  692. // Set cURL options based on HTTPFetchRequest
  693. CurlHandlePool pool;
  694. HTTPFetchOngoing ongoing(fetch_request, &pool);
  695. // Do the fetch (curl_easy_perform)
  696. CURLcode res = ongoing.start(NULL);
  697. // Update fetch result
  698. fetch_result = *ongoing.complete(res);
  699. }
  700. #else // USE_CURL
  701. /*
  702. USE_CURL is off:
  703. Dummy httpfetch implementation that always returns an error.
  704. */
  705. void httpfetch_init(int parallel_limit)
  706. {
  707. }
  708. void httpfetch_cleanup()
  709. {
  710. }
  711. void httpfetch_async(const HTTPFetchRequest &fetch_request)
  712. {
  713. errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
  714. << " because USE_CURL=0" << std::endl;
  715. HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
  716. httpfetch_deliver_result(fetch_result);
  717. }
  718. static void httpfetch_request_clear(u64 caller)
  719. {
  720. }
  721. void httpfetch_sync(const HTTPFetchRequest &fetch_request,
  722. HTTPFetchResult &fetch_result)
  723. {
  724. errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
  725. << " because USE_CURL=0" << std::endl;
  726. fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.
  727. }
  728. #endif // USE_CURL