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