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