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