]> git.lizzy.rs Git - dragonfireclient.git/blob - src/httpfetch.cpp
Reduce indentation of HTTPFetchOngoing
[dragonfireclient.git] / src / httpfetch.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "socket.h" // for select()
21 #include "porting.h" // for sleep_ms(), get_sysinfo()
22 #include "httpfetch.h"
23 #include <iostream>
24 #include <sstream>
25 #include <list>
26 #include <map>
27 #include <errno.h>
28 #include "jthread/jevent.h"
29 #include "config.h"
30 #include "exceptions.h"
31 #include "debug.h"
32 #include "log.h"
33 #include "util/container.h"
34 #include "util/thread.h"
35 #include "version.h"
36 #include "main.h"
37 #include "settings.h"
38
39 JMutex g_httpfetch_mutex;
40 std::map<unsigned long, std::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 &fetch_result)
56 {
57         unsigned long caller = fetch_result.caller;
58         if (caller != HTTPFETCH_DISCARD) {
59                 JMutexAutoLock lock(g_httpfetch_mutex);
60                 g_httpfetch_results[caller].push_back(fetch_result);
61         }
62 }
63
64 static void httpfetch_request_clear(unsigned long caller);
65
66 unsigned long httpfetch_caller_alloc()
67 {
68         JMutexAutoLock lock(g_httpfetch_mutex);
69
70         // Check each caller ID except HTTPFETCH_DISCARD
71         const unsigned long discard = HTTPFETCH_DISCARD;
72         for (unsigned long caller = discard + 1; caller != discard; ++caller) {
73                 std::map<unsigned long, std::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 &fetch_result)
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> &caller_results = it->second;
112         if (caller_results.empty())
113                 return false;
114
115         // Pop first result
116         fetch_result = caller_results.front();
117         caller_results.pop_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 class HTTPFetchOngoing
179 {
180 public:
181         HTTPFetchOngoing(HTTPFetchRequest request, CurlHandlePool *pool);
182         ~HTTPFetchOngoing();
183
184         CURLcode start(CURLM *multi);
185         const HTTPFetchResult * complete(CURLcode res);
186
187         const HTTPFetchRequest &getRequest()    const { return request; };
188         const CURL             *getEasyHandle() const { return curl; };
189
190 private:
191         CurlHandlePool *pool;
192         CURL *curl;
193         CURLM *multi;
194         HTTPFetchRequest request;
195         HTTPFetchResult result;
196         std::ostringstream oss;
197         char *post_fields;
198         struct curl_slist *http_header;
199         curl_httppost *post;
200 };
201
202
203 HTTPFetchOngoing::HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
204         pool(pool_),
205         curl(NULL),
206         multi(NULL),
207         request(request_),
208         result(request_),
209         oss(std::ios::binary),
210         http_header(NULL),
211         post(NULL)
212 {
213         curl = pool->alloc();
214         if (curl == NULL) {
215                 return;
216         }
217
218         // Set static cURL options
219         curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
220         curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
221         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
222         curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
223
224 #if LIBCURL_VERSION_NUM >= 0x071304
225         // Restrict protocols so that curl vulnerabilities in
226         // other protocols don't affect us.
227         // These settings were introduced in curl 7.19.4.
228         long protocols =
229                 CURLPROTO_HTTP |
230                 CURLPROTO_HTTPS |
231                 CURLPROTO_FTP |
232                 CURLPROTO_FTPS;
233         curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
234         curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
235 #endif
236
237         // Set cURL options based on HTTPFetchRequest
238         curl_easy_setopt(curl, CURLOPT_URL,
239                         request.url.c_str());
240         curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
241                         request.timeout);
242         curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
243                         request.connect_timeout);
244
245         if (request.useragent != "")
246                 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
247
248         // Set up a write callback that writes to the
249         // ostringstream ongoing->oss, unless the data
250         // is to be discarded
251         if (request.caller == HTTPFETCH_DISCARD) {
252                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
253                                 httpfetch_discardfunction);
254                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
255         } else {
256                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
257                                 httpfetch_writefunction);
258                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
259         }
260
261         // Set POST (or GET) data
262         if (request.post_fields.empty()) {
263                 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
264         } else if (request.multipart) {
265                 curl_httppost *last = NULL;
266                 for (std::map<std::string, std::string>::iterator it =
267                                         request.post_fields.begin();
268                                 it != request.post_fields.end(); ++it) {
269                         curl_formadd(&post, &last,
270                                         CURLFORM_NAMELENGTH, it->first.size(),
271                                         CURLFORM_PTRNAME, it->first.c_str(),
272                                         CURLFORM_CONTENTSLENGTH, it->second.size(),
273                                         CURLFORM_PTRCONTENTS, it->second.c_str(),
274                                         CURLFORM_END);
275                 }
276                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
277                 // request.post_fields must now *never* be
278                 // modified until CURLOPT_HTTPPOST is cleared
279         } else if (request.post_data.empty()) {
280                 curl_easy_setopt(curl, CURLOPT_POST, 1);
281                 std::string str;
282                 for (std::map<std::string, std::string>::iterator it =
283                                         request.post_fields.begin();
284                                 it != request.post_fields.end();
285                                 ++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 JThread
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         {
419                 if (parallel_limit >= 1)
420                         m_parallel_limit = parallel_limit;
421                 else
422                         m_parallel_limit = 1;
423         }
424
425         void requestFetch(const HTTPFetchRequest &fetch_request)
426         {
427                 Request req;
428                 req.type = RT_FETCH;
429                 req.fetch_request = fetch_request;
430                 req.event = NULL;
431                 m_requests.push_back(req);
432         }
433
434         void requestClear(unsigned long caller, Event *event)
435         {
436                 Request req;
437                 req.type = RT_CLEAR;
438                 req.fetch_request.caller = caller;
439                 req.event = event;
440                 m_requests.push_back(req);
441         }
442
443         void requestWakeUp()
444         {
445                 Request req;
446                 req.type = RT_WAKEUP;
447                 req.event = NULL;
448                 m_requests.push_back(req);
449         }
450
451 protected:
452         // Handle a request from some other thread
453         // E.g. new fetch; clear fetches for one caller; wake up
454         void processRequest(const Request &req)
455         {
456                 if (req.type == RT_FETCH) {
457                         // New fetch, queue until there are less
458                         // than m_parallel_limit ongoing fetches
459                         m_queued_fetches.push_back(req.fetch_request);
460
461                         // see processQueued() for what happens next
462
463                 }
464                 else if (req.type == RT_CLEAR) {
465                         unsigned long caller = req.fetch_request.caller;
466
467                         // Abort all ongoing fetches for the caller
468                         for (std::vector<HTTPFetchOngoing*>::iterator
469                                         it = m_all_ongoing.begin();
470                                         it != m_all_ongoing.end();) {
471                                 if ((*it)->getRequest().caller == caller) {
472                                         delete (*it);
473                                         it = m_all_ongoing.erase(it);
474                                 } else {
475                                         ++it;
476                                 }
477                         }
478
479                         // Also abort all queued fetches for the caller
480                         for (std::list<HTTPFetchRequest>::iterator
481                                         it = m_queued_fetches.begin();
482                                         it != m_queued_fetches.end();) {
483                                 if ((*it).caller == caller)
484                                         it = m_queued_fetches.erase(it);
485                                 else
486                                         ++it;
487                         }
488                 }
489                 else if (req.type == RT_WAKEUP) {
490                         // Wakeup: Nothing to do, thread is awake at this point
491                 }
492
493                 if (req.event != NULL)
494                         req.event->signal();
495         }
496
497         // Start new ongoing fetches if m_parallel_limit allows
498         void processQueued(CurlHandlePool *pool)
499         {
500                 while (m_all_ongoing.size() < m_parallel_limit &&
501                                 !m_queued_fetches.empty()) {
502                         HTTPFetchRequest request = m_queued_fetches.front();
503                         m_queued_fetches.pop_front();
504
505                         // Create ongoing fetch data and make a cURL handle
506                         // Set cURL options based on HTTPFetchRequest
507                         HTTPFetchOngoing *ongoing =
508                                 new HTTPFetchOngoing(request, pool);
509
510                         // Initiate the connection (curl_multi_add_handle)
511                         CURLcode res = ongoing->start(m_multi);
512                         if (res == CURLE_OK) {
513                                 m_all_ongoing.push_back(ongoing);
514                         }
515                         else {
516                                 httpfetch_deliver_result(*ongoing->complete(res));
517                                 delete ongoing;
518                         }
519                 }
520         }
521
522         // Process CURLMsg (indicates completion of a fetch)
523         void processCurlMessage(CURLMsg *msg)
524         {
525                 // Determine which ongoing fetch the message pertains to
526                 size_t i = 0;
527                 bool found = false;
528                 for (i = 0; i < m_all_ongoing.size(); ++i) {
529                         if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
530                                 found = true;
531                                 break;
532                         }
533                 }
534                 if (msg->msg == CURLMSG_DONE && found) {
535                         // m_all_ongoing[i] succeeded or failed.
536                         HTTPFetchOngoing *ongoing = m_all_ongoing[i];
537                         httpfetch_deliver_result(*ongoing->complete(msg->data.result));
538                         delete ongoing;
539                         m_all_ongoing.erase(m_all_ongoing.begin() + i);
540                 }
541         }
542
543         // Wait for a request from another thread, or timeout elapses
544         void waitForRequest(long timeout)
545         {
546                 if (m_queued_fetches.empty()) {
547                         try {
548                                 Request req = m_requests.pop_front(timeout);
549                                 processRequest(req);
550                         }
551                         catch (ItemNotFoundException &e) {}
552                 }
553         }
554
555         // Wait until some IO happens, or timeout elapses
556         void waitForIO(long timeout)
557         {
558                 fd_set read_fd_set;
559                 fd_set write_fd_set;
560                 fd_set exc_fd_set;
561                 int max_fd;
562                 long select_timeout = -1;
563                 struct timeval select_tv;
564                 CURLMcode mres;
565
566                 FD_ZERO(&read_fd_set);
567                 FD_ZERO(&write_fd_set);
568                 FD_ZERO(&exc_fd_set);
569
570                 mres = curl_multi_fdset(m_multi, &read_fd_set,
571                                 &write_fd_set, &exc_fd_set, &max_fd);
572                 if (mres != CURLM_OK) {
573                         errorstream<<"curl_multi_fdset"
574                                 <<" returned error code "<<mres
575                                 <<std::endl;
576                         select_timeout = 0;
577                 }
578
579                 mres = curl_multi_timeout(m_multi, &select_timeout);
580                 if (mres != CURLM_OK) {
581                         errorstream<<"curl_multi_timeout"
582                                 <<" returned error code "<<mres
583                                 <<std::endl;
584                         select_timeout = 0;
585                 }
586
587                 // Limit timeout so new requests get through
588                 if (select_timeout < 0 || select_timeout > timeout)
589                         select_timeout = timeout;
590
591                 if (select_timeout > 0) {
592                         // in Winsock it is forbidden to pass three empty
593                         // fd_sets to select(), so in that case use sleep_ms
594                         if (max_fd != -1) {
595                                 select_tv.tv_sec = select_timeout / 1000;
596                                 select_tv.tv_usec = (select_timeout % 1000) * 1000;
597                                 int retval = select(max_fd + 1, &read_fd_set,
598                                                 &write_fd_set, &exc_fd_set,
599                                                 &select_tv);
600                                 if (retval == -1) {
601                                         #ifdef _WIN32
602                                         errorstream<<"select returned error code "
603                                                 <<WSAGetLastError()<<std::endl;
604                                         #else
605                                         errorstream<<"select returned error code "
606                                                 <<errno<<std::endl;
607                                         #endif
608                                 }
609                         }
610                         else {
611                                 sleep_ms(select_timeout);
612                         }
613                 }
614         }
615
616         void * Thread()
617         {
618                 ThreadStarted();
619                 log_register_thread("CurlFetchThread");
620                 DSTACK(__FUNCTION_NAME);
621
622                 porting::setThreadName("CurlFetchThread");
623
624                 CurlHandlePool pool;
625
626                 m_multi = curl_multi_init();
627                 if (m_multi == NULL) {
628                         errorstream<<"curl_multi_init returned NULL\n";
629                         return NULL;
630                 }
631
632                 assert(m_all_ongoing.empty());
633
634                 while (!StopRequested()) {
635                         BEGIN_DEBUG_EXCEPTION_HANDLER
636
637                         /*
638                                 Handle new async requests
639                         */
640
641                         while (!m_requests.empty()) {
642                                 Request req = m_requests.pop_frontNoEx();
643                                 processRequest(req);
644                         }
645                         processQueued(&pool);
646
647                         /*
648                                 Handle ongoing async requests
649                         */
650
651                         int still_ongoing = 0;
652                         while (curl_multi_perform(m_multi, &still_ongoing) ==
653                                         CURLM_CALL_MULTI_PERFORM)
654                                 /* noop */;
655
656                         /*
657                                 Handle completed async requests
658                         */
659                         if (still_ongoing < (int) m_all_ongoing.size()) {
660                                 CURLMsg *msg;
661                                 int msgs_in_queue;
662                                 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
663                                 while (msg != NULL) {
664                                         processCurlMessage(msg);
665                                         msg = curl_multi_info_read(m_multi, &msgs_in_queue);
666                                 }
667                         }
668
669                         /*
670                                 If there are ongoing requests, wait for data
671                                 (with a timeout of 100ms so that new requests
672                                 can be processed).
673
674                                 If no ongoing requests, wait for a new request.
675                                 (Possibly an empty request that signals
676                                 that the thread should be stopped.)
677                         */
678                         if (m_all_ongoing.empty())
679                                 waitForRequest(100000000);
680                         else
681                                 waitForIO(100);
682
683                         END_DEBUG_EXCEPTION_HANDLER(errorstream)
684                 }
685
686                 // Call curl_multi_remove_handle and cleanup easy handles
687                 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
688                         delete m_all_ongoing[i];
689                 }
690                 m_all_ongoing.clear();
691
692                 m_queued_fetches.clear();
693
694                 CURLMcode mres = curl_multi_cleanup(m_multi);
695                 if (mres != CURLM_OK) {
696                         errorstream<<"curl_multi_cleanup"
697                                 <<" returned error code "<<mres
698                                 <<std::endl;
699                 }
700
701                 return NULL;
702         }
703 };
704
705 CurlFetchThread *g_httpfetch_thread = NULL;
706
707 void httpfetch_init(int parallel_limit)
708 {
709         verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
710                         <<std::endl;
711
712         CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
713         assert(res == CURLE_OK);
714
715         g_httpfetch_thread = new CurlFetchThread(parallel_limit);
716 }
717
718 void httpfetch_cleanup()
719 {
720         verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
721
722         g_httpfetch_thread->Stop();
723         g_httpfetch_thread->requestWakeUp();
724         g_httpfetch_thread->Wait();
725         delete g_httpfetch_thread;
726
727         curl_global_cleanup();
728 }
729
730 void httpfetch_async(const HTTPFetchRequest &fetch_request)
731 {
732         g_httpfetch_thread->requestFetch(fetch_request);
733         if (!g_httpfetch_thread->IsRunning())
734                 g_httpfetch_thread->Start();
735 }
736
737 static void httpfetch_request_clear(unsigned long caller)
738 {
739         if (g_httpfetch_thread->IsRunning()) {
740                 Event event;
741                 g_httpfetch_thread->requestClear(caller, &event);
742                 event.wait();
743         }
744         else {
745                 g_httpfetch_thread->requestClear(caller, NULL);
746         }
747 }
748
749 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
750                 HTTPFetchResult &fetch_result)
751 {
752         // Create ongoing fetch data and make a cURL handle
753         // Set cURL options based on HTTPFetchRequest
754         CurlHandlePool pool;
755         HTTPFetchOngoing ongoing(fetch_request, &pool);
756         // Do the fetch (curl_easy_perform)
757         CURLcode res = ongoing.start(NULL);
758         // Update fetch result
759         fetch_result = *ongoing.complete(res);
760 }
761
762 #else  // USE_CURL
763
764 /*
765         USE_CURL is off:
766
767         Dummy httpfetch implementation that always returns an error.
768 */
769
770 void httpfetch_init(int parallel_limit)
771 {
772 }
773
774 void httpfetch_cleanup()
775 {
776 }
777
778 void httpfetch_async(const HTTPFetchRequest &fetch_request)
779 {
780         errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
781                         << " because USE_CURL=0" << std::endl;
782
783         HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
784         httpfetch_deliver_result(fetch_result);
785 }
786
787 static void httpfetch_request_clear(unsigned long caller)
788 {
789 }
790
791 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
792                 HTTPFetchResult &fetch_result)
793 {
794         errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
795                         << " because USE_CURL=0" << std::endl;
796
797         fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.
798 }
799
800 #endif  // USE_CURL