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