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