Network cleanup (#6302)
[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, 1);
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 LIBCURL_VERSION_NUM >= 0x071304
256         // Restrict protocols so that curl vulnerabilities in
257         // other protocols don't affect us.
258         // These settings were introduced in curl 7.19.4.
259         long protocols =
260                 CURLPROTO_HTTP |
261                 CURLPROTO_HTTPS |
262                 CURLPROTO_FTP |
263                 CURLPROTO_FTPS;
264         curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
265         curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
266 #endif
267
268         // Set cURL options based on HTTPFetchRequest
269         curl_easy_setopt(curl, CURLOPT_URL,
270                         request.url.c_str());
271         curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
272                         request.timeout);
273         curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
274                         request.connect_timeout);
275
276         if (!request.useragent.empty())
277                 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
278
279         // Set up a write callback that writes to the
280         // ostringstream ongoing->oss, unless the data
281         // is to be discarded
282         if (request.caller == HTTPFETCH_DISCARD) {
283                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
284                                 httpfetch_discardfunction);
285                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
286         } else {
287                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
288                                 httpfetch_writefunction);
289                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
290         }
291
292         // Set POST (or GET) data
293         if (request.post_fields.empty() && request.post_data.empty()) {
294                 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
295         } else if (request.multipart) {
296                 curl_httppost *last = NULL;
297                 for (StringMap::iterator it = request.post_fields.begin();
298                                 it != request.post_fields.end(); ++it) {
299                         curl_formadd(&post, &last,
300                                         CURLFORM_NAMELENGTH, it->first.size(),
301                                         CURLFORM_PTRNAME, it->first.c_str(),
302                                         CURLFORM_CONTENTSLENGTH, it->second.size(),
303                                         CURLFORM_PTRCONTENTS, it->second.c_str(),
304                                         CURLFORM_END);
305                 }
306                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
307                 // request.post_fields must now *never* be
308                 // modified until CURLOPT_HTTPPOST is cleared
309         } else if (request.post_data.empty()) {
310                 curl_easy_setopt(curl, CURLOPT_POST, 1);
311                 std::string str;
312                 for (auto &post_field : request.post_fields) {
313                         if (!str.empty())
314                                 str += "&";
315                         str += urlencode(post_field.first);
316                         str += "=";
317                         str += urlencode(post_field.second);
318                 }
319                 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
320                                 str.size());
321                 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
322                                 str.c_str());
323         } else {
324                 curl_easy_setopt(curl, CURLOPT_POST, 1);
325                 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
326                                 request.post_data.size());
327                 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
328                                 request.post_data.c_str());
329                 // request.post_data must now *never* be
330                 // modified until CURLOPT_POSTFIELDS is cleared
331         }
332         // Set additional HTTP headers
333         for (const std::string &extra_header : request.extra_headers) {
334                 http_header = curl_slist_append(http_header, extra_header.c_str());
335         }
336         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
337
338         if (!g_settings->getBool("curl_verify_cert")) {
339                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
340         }
341 }
342
343 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
344 {
345         if (!curl)
346                 return CURLE_FAILED_INIT;
347
348         if (!multi_) {
349                 // Easy interface (sync)
350                 return curl_easy_perform(curl);
351         }
352
353         // Multi interface (async)
354         CURLMcode mres = curl_multi_add_handle(multi_, curl);
355         if (mres != CURLM_OK) {
356                 errorstream << "curl_multi_add_handle"
357                         << " returned error code " << mres
358                         << std::endl;
359                 return CURLE_FAILED_INIT;
360         }
361         multi = multi_; // store for curl_multi_remove_handle
362         return CURLE_OK;
363 }
364
365 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
366 {
367         result.succeeded = (res == CURLE_OK);
368         result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
369         result.data = oss.str();
370
371         // Get HTTP/FTP response code
372         result.response_code = 0;
373         if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
374                                 &result.response_code) != CURLE_OK)) {
375                 // We failed to get a return code, make sure it is still 0
376                 result.response_code = 0;
377         }
378
379         if (res != CURLE_OK) {
380                 errorstream << request.url << " not found ("
381                         << curl_easy_strerror(res) << ")"
382                         << " (response code " << result.response_code << ")"
383                         << std::endl;
384         }
385
386         return &result;
387 }
388
389 HTTPFetchOngoing::~HTTPFetchOngoing()
390 {
391         if (multi) {
392                 CURLMcode mres = curl_multi_remove_handle(multi, curl);
393                 if (mres != CURLM_OK) {
394                         errorstream << "curl_multi_remove_handle"
395                                 << " returned error code " << mres
396                                 << std::endl;
397                 }
398         }
399
400         // Set safe options for the reusable cURL handle
401         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
402                         httpfetch_discardfunction);
403         curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
404         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
405         if (http_header) {
406                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
407                 curl_slist_free_all(http_header);
408         }
409         if (post) {
410                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
411                 curl_formfree(post);
412         }
413
414         // Store the cURL handle for reuse
415         pool->free(curl);
416 }
417
418
419 class CurlFetchThread : public Thread
420 {
421 protected:
422         enum RequestType {
423                 RT_FETCH,
424                 RT_CLEAR,
425                 RT_WAKEUP,
426         };
427
428         struct Request {
429                 RequestType type;
430                 HTTPFetchRequest fetch_request;
431                 Event *event;
432         };
433
434         CURLM *m_multi;
435         MutexedQueue<Request> m_requests;
436         size_t m_parallel_limit;
437
438         // Variables exclusively used within thread
439         std::vector<HTTPFetchOngoing*> m_all_ongoing;
440         std::list<HTTPFetchRequest> m_queued_fetches;
441
442 public:
443         CurlFetchThread(int parallel_limit) :
444                 Thread("CurlFetch")
445         {
446                 if (parallel_limit >= 1)
447                         m_parallel_limit = parallel_limit;
448                 else
449                         m_parallel_limit = 1;
450         }
451
452         void requestFetch(const HTTPFetchRequest &fetch_request)
453         {
454                 Request req;
455                 req.type = RT_FETCH;
456                 req.fetch_request = fetch_request;
457                 req.event = NULL;
458                 m_requests.push_back(req);
459         }
460
461         void requestClear(unsigned long caller, Event *event)
462         {
463                 Request req;
464                 req.type = RT_CLEAR;
465                 req.fetch_request.caller = caller;
466                 req.event = event;
467                 m_requests.push_back(req);
468         }
469
470         void requestWakeUp()
471         {
472                 Request req;
473                 req.type = RT_WAKEUP;
474                 req.event = NULL;
475                 m_requests.push_back(req);
476         }
477
478 protected:
479         // Handle a request from some other thread
480         // E.g. new fetch; clear fetches for one caller; wake up
481         void processRequest(const Request &req)
482         {
483                 if (req.type == RT_FETCH) {
484                         // New fetch, queue until there are less
485                         // than m_parallel_limit ongoing fetches
486                         m_queued_fetches.push_back(req.fetch_request);
487
488                         // see processQueued() for what happens next
489
490                 }
491                 else if (req.type == RT_CLEAR) {
492                         unsigned long caller = req.fetch_request.caller;
493
494                         // Abort all ongoing fetches for the caller
495                         for (std::vector<HTTPFetchOngoing*>::iterator
496                                         it = m_all_ongoing.begin();
497                                         it != m_all_ongoing.end();) {
498                                 if ((*it)->getRequest().caller == caller) {
499                                         delete (*it);
500                                         it = m_all_ongoing.erase(it);
501                                 } else {
502                                         ++it;
503                                 }
504                         }
505
506                         // Also abort all queued fetches for the caller
507                         for (std::list<HTTPFetchRequest>::iterator
508                                         it = m_queued_fetches.begin();
509                                         it != m_queued_fetches.end();) {
510                                 if ((*it).caller == caller)
511                                         it = m_queued_fetches.erase(it);
512                                 else
513                                         ++it;
514                         }
515                 }
516                 else if (req.type == RT_WAKEUP) {
517                         // Wakeup: Nothing to do, thread is awake at this point
518                 }
519
520                 if (req.event != NULL)
521                         req.event->signal();
522         }
523
524         // Start new ongoing fetches if m_parallel_limit allows
525         void processQueued(CurlHandlePool *pool)
526         {
527                 while (m_all_ongoing.size() < m_parallel_limit &&
528                                 !m_queued_fetches.empty()) {
529                         HTTPFetchRequest request = m_queued_fetches.front();
530                         m_queued_fetches.pop_front();
531
532                         // Create ongoing fetch data and make a cURL handle
533                         // Set cURL options based on HTTPFetchRequest
534                         HTTPFetchOngoing *ongoing =
535                                 new HTTPFetchOngoing(request, pool);
536
537                         // Initiate the connection (curl_multi_add_handle)
538                         CURLcode res = ongoing->start(m_multi);
539                         if (res == CURLE_OK) {
540                                 m_all_ongoing.push_back(ongoing);
541                         }
542                         else {
543                                 httpfetch_deliver_result(*ongoing->complete(res));
544                                 delete ongoing;
545                         }
546                 }
547         }
548
549         // Process CURLMsg (indicates completion of a fetch)
550         void processCurlMessage(CURLMsg *msg)
551         {
552                 // Determine which ongoing fetch the message pertains to
553                 size_t i = 0;
554                 bool found = false;
555                 for (i = 0; i < m_all_ongoing.size(); ++i) {
556                         if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
557                                 found = true;
558                                 break;
559                         }
560                 }
561                 if (msg->msg == CURLMSG_DONE && found) {
562                         // m_all_ongoing[i] succeeded or failed.
563                         HTTPFetchOngoing *ongoing = m_all_ongoing[i];
564                         httpfetch_deliver_result(*ongoing->complete(msg->data.result));
565                         delete ongoing;
566                         m_all_ongoing.erase(m_all_ongoing.begin() + i);
567                 }
568         }
569
570         // Wait for a request from another thread, or timeout elapses
571         void waitForRequest(long timeout)
572         {
573                 if (m_queued_fetches.empty()) {
574                         try {
575                                 Request req = m_requests.pop_front(timeout);
576                                 processRequest(req);
577                         }
578                         catch (ItemNotFoundException &e) {}
579                 }
580         }
581
582         // Wait until some IO happens, or timeout elapses
583         void waitForIO(long timeout)
584         {
585                 fd_set read_fd_set;
586                 fd_set write_fd_set;
587                 fd_set exc_fd_set;
588                 int max_fd;
589                 long select_timeout = -1;
590                 struct timeval select_tv;
591                 CURLMcode mres;
592
593                 FD_ZERO(&read_fd_set);
594                 FD_ZERO(&write_fd_set);
595                 FD_ZERO(&exc_fd_set);
596
597                 mres = curl_multi_fdset(m_multi, &read_fd_set,
598                                 &write_fd_set, &exc_fd_set, &max_fd);
599                 if (mres != CURLM_OK) {
600                         errorstream<<"curl_multi_fdset"
601                                 <<" returned error code "<<mres
602                                 <<std::endl;
603                         select_timeout = 0;
604                 }
605
606                 mres = curl_multi_timeout(m_multi, &select_timeout);
607                 if (mres != CURLM_OK) {
608                         errorstream<<"curl_multi_timeout"
609                                 <<" returned error code "<<mres
610                                 <<std::endl;
611                         select_timeout = 0;
612                 }
613
614                 // Limit timeout so new requests get through
615                 if (select_timeout < 0 || select_timeout > timeout)
616                         select_timeout = timeout;
617
618                 if (select_timeout > 0) {
619                         // in Winsock it is forbidden to pass three empty
620                         // fd_sets to select(), so in that case use sleep_ms
621                         if (max_fd != -1) {
622                                 select_tv.tv_sec = select_timeout / 1000;
623                                 select_tv.tv_usec = (select_timeout % 1000) * 1000;
624                                 int retval = select(max_fd + 1, &read_fd_set,
625                                                 &write_fd_set, &exc_fd_set,
626                                                 &select_tv);
627                                 if (retval == -1) {
628                                         #ifdef _WIN32
629                                         errorstream<<"select returned error code "
630                                                 <<WSAGetLastError()<<std::endl;
631                                         #else
632                                         errorstream<<"select returned error code "
633                                                 <<errno<<std::endl;
634                                         #endif
635                                 }
636                         }
637                         else {
638                                 sleep_ms(select_timeout);
639                         }
640                 }
641         }
642
643         void *run()
644         {
645                 DSTACK(FUNCTION_NAME);
646
647                 CurlHandlePool pool;
648
649                 m_multi = curl_multi_init();
650                 if (m_multi == NULL) {
651                         errorstream<<"curl_multi_init returned NULL\n";
652                         return NULL;
653                 }
654
655                 FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
656
657                 while (!stopRequested()) {
658                         BEGIN_DEBUG_EXCEPTION_HANDLER
659
660                         /*
661                                 Handle new async requests
662                         */
663
664                         while (!m_requests.empty()) {
665                                 Request req = m_requests.pop_frontNoEx();
666                                 processRequest(req);
667                         }
668                         processQueued(&pool);
669
670                         /*
671                                 Handle ongoing async requests
672                         */
673
674                         int still_ongoing = 0;
675                         while (curl_multi_perform(m_multi, &still_ongoing) ==
676                                         CURLM_CALL_MULTI_PERFORM)
677                                 /* noop */;
678
679                         /*
680                                 Handle completed async requests
681                         */
682                         if (still_ongoing < (int) m_all_ongoing.size()) {
683                                 CURLMsg *msg;
684                                 int msgs_in_queue;
685                                 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
686                                 while (msg != NULL) {
687                                         processCurlMessage(msg);
688                                         msg = curl_multi_info_read(m_multi, &msgs_in_queue);
689                                 }
690                         }
691
692                         /*
693                                 If there are ongoing requests, wait for data
694                                 (with a timeout of 100ms so that new requests
695                                 can be processed).
696
697                                 If no ongoing requests, wait for a new request.
698                                 (Possibly an empty request that signals
699                                 that the thread should be stopped.)
700                         */
701                         if (m_all_ongoing.empty())
702                                 waitForRequest(100000000);
703                         else
704                                 waitForIO(100);
705
706                         END_DEBUG_EXCEPTION_HANDLER
707                 }
708
709                 // Call curl_multi_remove_handle and cleanup easy handles
710                 for (HTTPFetchOngoing *i : m_all_ongoing) {
711                         delete i;
712                 }
713                 m_all_ongoing.clear();
714
715                 m_queued_fetches.clear();
716
717                 CURLMcode mres = curl_multi_cleanup(m_multi);
718                 if (mres != CURLM_OK) {
719                         errorstream<<"curl_multi_cleanup"
720                                 <<" returned error code "<<mres
721                                 <<std::endl;
722                 }
723
724                 return NULL;
725         }
726 };
727
728 CurlFetchThread *g_httpfetch_thread = NULL;
729
730 void httpfetch_init(int parallel_limit)
731 {
732         verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
733                         <<std::endl;
734
735         CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
736         FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
737
738         g_httpfetch_thread = new CurlFetchThread(parallel_limit);
739
740         // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
741         u64 randbuf[2];
742         porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
743         g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
744 }
745
746 void httpfetch_cleanup()
747 {
748         verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
749
750         g_httpfetch_thread->stop();
751         g_httpfetch_thread->requestWakeUp();
752         g_httpfetch_thread->wait();
753         delete g_httpfetch_thread;
754
755         curl_global_cleanup();
756 }
757
758 void httpfetch_async(const HTTPFetchRequest &fetch_request)
759 {
760         g_httpfetch_thread->requestFetch(fetch_request);
761         if (!g_httpfetch_thread->isRunning())
762                 g_httpfetch_thread->start();
763 }
764
765 static void httpfetch_request_clear(unsigned long caller)
766 {
767         if (g_httpfetch_thread->isRunning()) {
768                 Event event;
769                 g_httpfetch_thread->requestClear(caller, &event);
770                 event.wait();
771         } else {
772                 g_httpfetch_thread->requestClear(caller, NULL);
773         }
774 }
775
776 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
777                 HTTPFetchResult &fetch_result)
778 {
779         // Create ongoing fetch data and make a cURL handle
780         // Set cURL options based on HTTPFetchRequest
781         CurlHandlePool pool;
782         HTTPFetchOngoing ongoing(fetch_request, &pool);
783         // Do the fetch (curl_easy_perform)
784         CURLcode res = ongoing.start(NULL);
785         // Update fetch result
786         fetch_result = *ongoing.complete(res);
787 }
788
789 #else  // USE_CURL
790
791 /*
792         USE_CURL is off:
793
794         Dummy httpfetch implementation that always returns an error.
795 */
796
797 void httpfetch_init(int parallel_limit)
798 {
799 }
800
801 void httpfetch_cleanup()
802 {
803 }
804
805 void httpfetch_async(const HTTPFetchRequest &fetch_request)
806 {
807         errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
808                         << " because USE_CURL=0" << std::endl;
809
810         HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
811         httpfetch_deliver_result(fetch_result);
812 }
813
814 static void httpfetch_request_clear(unsigned long caller)
815 {
816 }
817
818 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
819                 HTTPFetchResult &fetch_result)
820 {
821         errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
822                         << " because USE_CURL=0" << std::endl;
823
824         fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.
825 }
826
827 #endif  // USE_CURL