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