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