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