httpfetch.cpp 20 KB

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