3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "socket.h" // for select()
21 #include "porting.h" // for sleep_ms(), get_sysinfo()
22 #include "httpfetch.h"
28 #include "jthread/jevent.h"
30 #include "exceptions.h"
33 #include "util/container.h"
34 #include "util/thread.h"
39 JMutex g_httpfetch_mutex;
40 std::map<unsigned long, std::list<HTTPFetchResult> > g_httpfetch_results;
42 HTTPFetchRequest::HTTPFetchRequest()
45 caller = HTTPFETCH_DISCARD;
47 timeout = g_settings->getS32("curl_timeout");
48 connect_timeout = timeout;
50 useragent = std::string("Minetest/") + minetest_version_hash + " (" + porting::get_sysinfo() + ")";
54 static void httpfetch_deliver_result(const HTTPFetchResult &fetchresult)
56 unsigned long caller = fetchresult.caller;
57 if (caller != HTTPFETCH_DISCARD) {
58 JMutexAutoLock lock(g_httpfetch_mutex);
59 g_httpfetch_results[caller].push_back(fetchresult);
63 static void httpfetch_request_clear(unsigned long caller);
65 unsigned long httpfetch_caller_alloc()
67 JMutexAutoLock lock(g_httpfetch_mutex);
69 // Check each caller ID except HTTPFETCH_DISCARD
70 const unsigned long discard = HTTPFETCH_DISCARD;
71 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
72 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
73 it = g_httpfetch_results.find(caller);
74 if (it == g_httpfetch_results.end()) {
75 verbosestream<<"httpfetch_caller_alloc: allocating "
77 // Access element to create it
78 g_httpfetch_results[caller];
83 assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
87 void httpfetch_caller_free(unsigned long caller)
89 verbosestream<<"httpfetch_caller_free: freeing "
92 httpfetch_request_clear(caller);
93 if (caller != HTTPFETCH_DISCARD) {
94 JMutexAutoLock lock(g_httpfetch_mutex);
95 g_httpfetch_results.erase(caller);
99 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetchresult)
101 JMutexAutoLock lock(g_httpfetch_mutex);
103 // Check that caller exists
104 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
105 it = g_httpfetch_results.find(caller);
106 if (it == g_httpfetch_results.end())
109 // Check that result queue is nonempty
110 std::list<HTTPFetchResult> &callerresults = it->second;
111 if (callerresults.empty())
115 fetchresult = callerresults.front();
116 callerresults.pop_front();
121 #include <curl/curl.h>
124 USE_CURL is on: use cURL based httpfetch implementation
127 static size_t httpfetch_writefunction(
128 char *ptr, size_t size, size_t nmemb, void *userdata)
130 std::ostringstream *stream = (std::ostringstream*)userdata;
131 size_t count = size * nmemb;
132 stream->write(ptr, count);
136 static size_t httpfetch_discardfunction(
137 char *ptr, size_t size, size_t nmemb, void *userdata)
144 std::list<CURL*> handles;
150 for (std::list<CURL*>::iterator it = handles.begin();
151 it != handles.end(); ++it) {
152 curl_easy_cleanup(*it);
158 if (handles.empty()) {
159 curl = curl_easy_init();
161 errorstream<<"curl_easy_init returned NULL"<<std::endl;
165 curl = handles.front();
170 void free(CURL *handle)
173 handles.push_back(handle);
177 struct HTTPFetchOngoing
179 CurlHandlePool *pool;
182 HTTPFetchRequest request;
183 HTTPFetchResult result;
184 std::ostringstream oss;
186 struct curl_slist *httpheader;
188 HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
194 oss(std::ios::binary),
197 curl = pool->alloc();
199 // Set static cURL options
200 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
201 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
202 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
203 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
205 #if LIBCURL_VERSION_NUM >= 0x071304
206 // Restrict protocols so that curl vulnerabilities in
207 // other protocols don't affect us.
208 // These settings were introduced in curl 7.19.4.
214 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
215 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
218 // Set cURL options based on HTTPFetchRequest
219 curl_easy_setopt(curl, CURLOPT_URL,
220 request.url.c_str());
221 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
223 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
224 request.connect_timeout);
226 if (request.useragent != "")
227 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
229 // Set up a write callback that writes to the
230 // ostringstream ongoing->oss, unless the data
231 // is to be discarded
232 if (request.caller == HTTPFETCH_DISCARD) {
233 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
234 httpfetch_discardfunction);
235 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
238 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
239 httpfetch_writefunction);
240 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
242 // Set POST (or GET) data
243 if (request.post_fields.empty()) {
244 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
247 curl_easy_setopt(curl, CURLOPT_POST, 1);
248 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
249 request.post_fields.size());
250 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
251 request.post_fields.c_str());
252 // request.post_fields must now *never* be
253 // modified until CURLOPT_POSTFIELDS is cleared
255 // Set additional HTTP headers
256 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
257 httpheader = curl_slist_append(
259 request.extra_headers[i].c_str());
261 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
263 if (!g_settings->getBool("curl_verify_cert")) {
264 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
269 CURLcode start(CURLM *multi_)
272 return CURLE_FAILED_INIT;
275 // Multi interface (async)
276 CURLMcode mres = curl_multi_add_handle(multi_, curl);
277 if (mres != CURLM_OK) {
278 errorstream<<"curl_multi_add_handle"
279 <<" returned error code "<<mres
281 return CURLE_FAILED_INIT;
283 multi = multi_; // store for curl_multi_remove_handle
287 // Easy interface (sync)
288 return curl_easy_perform(curl);
292 void complete(CURLcode res)
294 result.succeeded = (res == CURLE_OK);
295 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
296 result.data = oss.str();
298 // Get HTTP/FTP response code
299 result.response_code = 0;
301 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
302 &result.response_code) != CURLE_OK) {
303 //we failed to get a return code make sure it is still 0
304 result.response_code = 0;
308 if (res != CURLE_OK) {
309 errorstream<<request.url<<" not found ("
310 <<curl_easy_strerror(res)<<")"
311 <<" (response code "<<result.response_code<<")"
319 CURLMcode mres = curl_multi_remove_handle(multi, curl);
320 if (mres != CURLM_OK) {
321 errorstream<<"curl_multi_remove_handle"
322 <<" returned error code "<<mres
327 // Set safe options for the reusable cURL handle
328 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
329 httpfetch_discardfunction);
330 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
331 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
332 if (httpheader != NULL) {
333 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
334 curl_slist_free_all(httpheader);
337 // Store the cURL handle for reuse
342 class CurlFetchThread : public JThread
353 HTTPFetchRequest fetchrequest;
358 MutexedQueue<Request> m_requests;
359 size_t m_parallel_limit;
361 // Variables exclusively used within thread
362 std::vector<HTTPFetchOngoing*> m_all_ongoing;
363 std::list<HTTPFetchRequest> m_queued_fetches;
366 CurlFetchThread(int parallel_limit)
368 if (parallel_limit >= 1)
369 m_parallel_limit = parallel_limit;
371 m_parallel_limit = 1;
374 void requestFetch(const HTTPFetchRequest &fetchrequest)
378 req.fetchrequest = fetchrequest;
380 m_requests.push_back(req);
383 void requestClear(unsigned long caller, Event *event)
387 req.fetchrequest.caller = caller;
389 m_requests.push_back(req);
395 req.type = RT_WAKEUP;
397 m_requests.push_back(req);
401 // Handle a request from some other thread
402 // E.g. new fetch; clear fetches for one caller; wake up
403 void processRequest(const Request &req)
405 if (req.type == RT_FETCH) {
406 // New fetch, queue until there are less
407 // than m_parallel_limit ongoing fetches
408 m_queued_fetches.push_back(req.fetchrequest);
410 // see processQueued() for what happens next
413 else if (req.type == RT_CLEAR) {
414 unsigned long caller = req.fetchrequest.caller;
416 // Abort all ongoing fetches for the caller
417 for (std::vector<HTTPFetchOngoing*>::iterator
418 it = m_all_ongoing.begin();
419 it != m_all_ongoing.end();) {
420 if ((*it)->request.caller == caller) {
422 it = m_all_ongoing.erase(it);
428 // Also abort all queued fetches for the caller
429 for (std::list<HTTPFetchRequest>::iterator
430 it = m_queued_fetches.begin();
431 it != m_queued_fetches.end();) {
432 if ((*it).caller == caller)
433 it = m_queued_fetches.erase(it);
438 else if (req.type == RT_WAKEUP) {
439 // Wakeup: Nothing to do, thread is awake at this point
442 if (req.event != NULL)
446 // Start new ongoing fetches if m_parallel_limit allows
447 void processQueued(CurlHandlePool *pool)
449 while (m_all_ongoing.size() < m_parallel_limit &&
450 !m_queued_fetches.empty()) {
451 HTTPFetchRequest request = m_queued_fetches.front();
452 m_queued_fetches.pop_front();
454 // Create ongoing fetch data and make a cURL handle
455 // Set cURL options based on HTTPFetchRequest
456 HTTPFetchOngoing *ongoing =
457 new HTTPFetchOngoing(request, pool);
459 // Initiate the connection (curl_multi_add_handle)
460 CURLcode res = ongoing->start(m_multi);
461 if (res == CURLE_OK) {
462 m_all_ongoing.push_back(ongoing);
465 ongoing->complete(res);
466 httpfetch_deliver_result(ongoing->result);
472 // Process CURLMsg (indicates completion of a fetch)
473 void processCurlMessage(CURLMsg *msg)
475 // Determine which ongoing fetch the message pertains to
478 for (i = 0; i < m_all_ongoing.size(); ++i) {
479 if (m_all_ongoing[i]->curl == msg->easy_handle) {
484 if (msg->msg == CURLMSG_DONE && found) {
485 // m_all_ongoing[i] succeeded or failed.
486 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
487 ongoing->complete(msg->data.result);
488 httpfetch_deliver_result(ongoing->result);
490 m_all_ongoing.erase(m_all_ongoing.begin() + i);
494 // Wait for a request from another thread, or timeout elapses
495 void waitForRequest(long timeout)
497 if (m_queued_fetches.empty()) {
499 Request req = m_requests.pop_front(timeout);
502 catch (ItemNotFoundException &e) {}
506 // Wait until some IO happens, or timeout elapses
507 void waitForIO(long timeout)
513 long select_timeout = -1;
514 struct timeval select_tv;
517 FD_ZERO(&read_fd_set);
518 FD_ZERO(&write_fd_set);
519 FD_ZERO(&exc_fd_set);
521 mres = curl_multi_fdset(m_multi, &read_fd_set,
522 &write_fd_set, &exc_fd_set, &max_fd);
523 if (mres != CURLM_OK) {
524 errorstream<<"curl_multi_fdset"
525 <<" returned error code "<<mres
530 mres = curl_multi_timeout(m_multi, &select_timeout);
531 if (mres != CURLM_OK) {
532 errorstream<<"curl_multi_timeout"
533 <<" returned error code "<<mres
538 // Limit timeout so new requests get through
539 if (select_timeout < 0 || select_timeout > timeout)
540 select_timeout = timeout;
542 if (select_timeout > 0) {
543 // in Winsock it is forbidden to pass three empty
544 // fd_sets to select(), so in that case use sleep_ms
546 select_tv.tv_sec = select_timeout / 1000;
547 select_tv.tv_usec = (select_timeout % 1000) * 1000;
548 int retval = select(max_fd + 1, &read_fd_set,
549 &write_fd_set, &exc_fd_set,
553 errorstream<<"select returned error code "
554 <<WSAGetLastError()<<std::endl;
556 errorstream<<"select returned error code "
562 sleep_ms(select_timeout);
570 log_register_thread("CurlFetchThread");
571 DSTACK(__FUNCTION_NAME);
573 porting::setThreadName("CurlFetchThread");
577 m_multi = curl_multi_init();
578 if (m_multi == NULL) {
579 errorstream<<"curl_multi_init returned NULL\n";
583 assert(m_all_ongoing.empty());
585 while (!StopRequested()) {
586 BEGIN_DEBUG_EXCEPTION_HANDLER
589 Handle new async requests
592 while (!m_requests.empty()) {
593 Request req = m_requests.pop_frontNoEx();
596 processQueued(&pool);
599 Handle ongoing async requests
602 int still_ongoing = 0;
603 while (curl_multi_perform(m_multi, &still_ongoing) ==
604 CURLM_CALL_MULTI_PERFORM)
608 Handle completed async requests
610 if (still_ongoing < (int) m_all_ongoing.size()) {
613 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
614 while (msg != NULL) {
615 processCurlMessage(msg);
616 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
621 If there are ongoing requests, wait for data
622 (with a timeout of 100ms so that new requests
625 If no ongoing requests, wait for a new request.
626 (Possibly an empty request that signals
627 that the thread should be stopped.)
629 if (m_all_ongoing.empty())
630 waitForRequest(100000000);
634 END_DEBUG_EXCEPTION_HANDLER(errorstream)
637 // Call curl_multi_remove_handle and cleanup easy handles
638 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
639 delete m_all_ongoing[i];
641 m_all_ongoing.clear();
643 m_queued_fetches.clear();
645 CURLMcode mres = curl_multi_cleanup(m_multi);
646 if (mres != CURLM_OK) {
647 errorstream<<"curl_multi_cleanup"
648 <<" returned error code "<<mres
656 CurlFetchThread *g_httpfetch_thread = NULL;
658 void httpfetch_init(int parallel_limit)
660 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
663 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
664 assert(res == CURLE_OK);
666 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
669 void httpfetch_cleanup()
671 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
673 g_httpfetch_thread->Stop();
674 g_httpfetch_thread->requestWakeUp();
675 g_httpfetch_thread->Wait();
676 delete g_httpfetch_thread;
678 curl_global_cleanup();
681 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
683 g_httpfetch_thread->requestFetch(fetchrequest);
684 if (!g_httpfetch_thread->IsRunning())
685 g_httpfetch_thread->Start();
688 static void httpfetch_request_clear(unsigned long caller)
690 if (g_httpfetch_thread->IsRunning()) {
692 g_httpfetch_thread->requestClear(caller, &event);
696 g_httpfetch_thread->requestClear(caller, NULL);
700 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
701 HTTPFetchResult &fetchresult)
703 // Create ongoing fetch data and make a cURL handle
704 // Set cURL options based on HTTPFetchRequest
706 HTTPFetchOngoing ongoing(fetchrequest, &pool);
707 // Do the fetch (curl_easy_perform)
708 CURLcode res = ongoing.start(NULL);
709 // Update fetchresult
710 ongoing.complete(res);
711 fetchresult = ongoing.result;
719 Dummy httpfetch implementation that always returns an error.
722 void httpfetch_init(int parallel_limit)
726 void httpfetch_cleanup()
730 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
732 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
733 <<" because USE_CURL=0"<<std::endl;
735 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
736 httpfetch_deliver_result(fetchresult);
739 static void httpfetch_request_clear(unsigned long caller)
743 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
744 HTTPFetchResult &fetchresult)
746 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
747 <<" because USE_CURL=0"<<std::endl;
749 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.