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::queue<HTTPFetchResult> > g_httpfetch_results;
42 HTTPFetchRequest::HTTPFetchRequest()
45 caller = HTTPFETCH_DISCARD;
47 timeout = g_settings->getS32("curl_timeout");
48 connect_timeout = timeout;
51 useragent = std::string("Minetest/") + minetest_version_hash + " (" + porting::get_sysinfo() + ")";
55 static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
57 unsigned long caller = fetch_result.caller;
58 if (caller != HTTPFETCH_DISCARD) {
59 JMutexAutoLock lock(g_httpfetch_mutex);
60 g_httpfetch_results[caller].push(fetch_result);
64 static void httpfetch_request_clear(unsigned long caller);
66 unsigned long httpfetch_caller_alloc()
68 JMutexAutoLock lock(g_httpfetch_mutex);
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::queue<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];
84 assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
88 void httpfetch_caller_free(unsigned long caller)
90 verbosestream<<"httpfetch_caller_free: freeing "
93 httpfetch_request_clear(caller);
94 if (caller != HTTPFETCH_DISCARD) {
95 JMutexAutoLock lock(g_httpfetch_mutex);
96 g_httpfetch_results.erase(caller);
100 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result)
102 JMutexAutoLock lock(g_httpfetch_mutex);
104 // Check that caller exists
105 std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
106 it = g_httpfetch_results.find(caller);
107 if (it == g_httpfetch_results.end())
110 // Check that result queue is nonempty
111 std::queue<HTTPFetchResult> &caller_results = it->second;
112 if (caller_results.empty())
116 fetch_result = caller_results.front();
117 caller_results.pop();
122 #include <curl/curl.h>
125 USE_CURL is on: use cURL based httpfetch implementation
128 static size_t httpfetch_writefunction(
129 char *ptr, size_t size, size_t nmemb, void *userdata)
131 std::ostringstream *stream = (std::ostringstream*)userdata;
132 size_t count = size * nmemb;
133 stream->write(ptr, count);
137 static size_t httpfetch_discardfunction(
138 char *ptr, size_t size, size_t nmemb, void *userdata)
145 std::list<CURL*> handles;
151 for (std::list<CURL*>::iterator it = handles.begin();
152 it != handles.end(); ++it) {
153 curl_easy_cleanup(*it);
159 if (handles.empty()) {
160 curl = curl_easy_init();
162 errorstream<<"curl_easy_init returned NULL"<<std::endl;
166 curl = handles.front();
171 void free(CURL *handle)
174 handles.push_back(handle);
178 class HTTPFetchOngoing
181 HTTPFetchOngoing(HTTPFetchRequest request, CurlHandlePool *pool);
184 CURLcode start(CURLM *multi);
185 const HTTPFetchResult * complete(CURLcode res);
187 const HTTPFetchRequest &getRequest() const { return request; };
188 const CURL *getEasyHandle() const { return curl; };
191 CurlHandlePool *pool;
194 HTTPFetchRequest request;
195 HTTPFetchResult result;
196 std::ostringstream oss;
197 struct curl_slist *http_header;
202 HTTPFetchOngoing::HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
208 oss(std::ios::binary),
212 curl = pool->alloc();
217 // Set static cURL options
218 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
219 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
220 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
221 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
223 std::string bind_address = g_settings->get("bind_address");
224 if (!bind_address.empty()) {
225 curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
228 #if LIBCURL_VERSION_NUM >= 0x071304
229 // Restrict protocols so that curl vulnerabilities in
230 // other protocols don't affect us.
231 // These settings were introduced in curl 7.19.4.
237 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
238 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
241 // Set cURL options based on HTTPFetchRequest
242 curl_easy_setopt(curl, CURLOPT_URL,
243 request.url.c_str());
244 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
246 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
247 request.connect_timeout);
249 if (request.useragent != "")
250 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
252 // Set up a write callback that writes to the
253 // ostringstream ongoing->oss, unless the data
254 // is to be discarded
255 if (request.caller == HTTPFETCH_DISCARD) {
256 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
257 httpfetch_discardfunction);
258 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
260 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
261 httpfetch_writefunction);
262 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
265 // Set POST (or GET) data
266 if (request.post_fields.empty()) {
267 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
268 } else if (request.multipart) {
269 curl_httppost *last = NULL;
270 for (std::map<std::string, std::string>::iterator it =
271 request.post_fields.begin();
272 it != request.post_fields.end(); ++it) {
273 curl_formadd(&post, &last,
274 CURLFORM_NAMELENGTH, it->first.size(),
275 CURLFORM_PTRNAME, it->first.c_str(),
276 CURLFORM_CONTENTSLENGTH, it->second.size(),
277 CURLFORM_PTRCONTENTS, it->second.c_str(),
280 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
281 // request.post_fields must now *never* be
282 // modified until CURLOPT_HTTPPOST is cleared
283 } else if (request.post_data.empty()) {
284 curl_easy_setopt(curl, CURLOPT_POST, 1);
286 for (std::map<std::string, std::string>::iterator it =
287 request.post_fields.begin();
288 it != request.post_fields.end();
292 str += urlencode(it->first);
294 str += urlencode(it->second);
296 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
298 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
301 curl_easy_setopt(curl, CURLOPT_POST, 1);
302 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
303 request.post_data.size());
304 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
305 request.post_data.c_str());
306 // request.post_data must now *never* be
307 // modified until CURLOPT_POSTFIELDS is cleared
309 // Set additional HTTP headers
310 for (std::vector<std::string>::iterator it = request.extra_headers.begin();
311 it != request.extra_headers.end(); ++it) {
312 http_header = curl_slist_append(http_header, it->c_str());
314 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
316 if (!g_settings->getBool("curl_verify_cert")) {
317 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
321 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
324 return CURLE_FAILED_INIT;
327 // Easy interface (sync)
328 return curl_easy_perform(curl);
331 // Multi interface (async)
332 CURLMcode mres = curl_multi_add_handle(multi_, curl);
333 if (mres != CURLM_OK) {
334 errorstream << "curl_multi_add_handle"
335 << " returned error code " << mres
337 return CURLE_FAILED_INIT;
339 multi = multi_; // store for curl_multi_remove_handle
343 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
345 result.succeeded = (res == CURLE_OK);
346 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
347 result.data = oss.str();
349 // Get HTTP/FTP response code
350 result.response_code = 0;
351 if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
352 &result.response_code) != CURLE_OK)) {
353 // We failed to get a return code, make sure it is still 0
354 result.response_code = 0;
357 if (res != CURLE_OK) {
358 errorstream << request.url << " not found ("
359 << curl_easy_strerror(res) << ")"
360 << " (response code " << result.response_code << ")"
367 HTTPFetchOngoing::~HTTPFetchOngoing()
370 CURLMcode mres = curl_multi_remove_handle(multi, curl);
371 if (mres != CURLM_OK) {
372 errorstream << "curl_multi_remove_handle"
373 << " returned error code " << mres
378 // Set safe options for the reusable cURL handle
379 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
380 httpfetch_discardfunction);
381 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
382 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
384 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
385 curl_slist_free_all(http_header);
388 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
392 // Store the cURL handle for reuse
397 class CurlFetchThread : public JThread
408 HTTPFetchRequest fetch_request;
413 MutexedQueue<Request> m_requests;
414 size_t m_parallel_limit;
416 // Variables exclusively used within thread
417 std::vector<HTTPFetchOngoing*> m_all_ongoing;
418 std::list<HTTPFetchRequest> m_queued_fetches;
421 CurlFetchThread(int parallel_limit)
423 if (parallel_limit >= 1)
424 m_parallel_limit = parallel_limit;
426 m_parallel_limit = 1;
429 void requestFetch(const HTTPFetchRequest &fetch_request)
433 req.fetch_request = fetch_request;
435 m_requests.push_back(req);
438 void requestClear(unsigned long caller, Event *event)
442 req.fetch_request.caller = caller;
444 m_requests.push_back(req);
450 req.type = RT_WAKEUP;
452 m_requests.push_back(req);
456 // Handle a request from some other thread
457 // E.g. new fetch; clear fetches for one caller; wake up
458 void processRequest(const Request &req)
460 if (req.type == RT_FETCH) {
461 // New fetch, queue until there are less
462 // than m_parallel_limit ongoing fetches
463 m_queued_fetches.push_back(req.fetch_request);
465 // see processQueued() for what happens next
468 else if (req.type == RT_CLEAR) {
469 unsigned long caller = req.fetch_request.caller;
471 // Abort all ongoing fetches for the caller
472 for (std::vector<HTTPFetchOngoing*>::iterator
473 it = m_all_ongoing.begin();
474 it != m_all_ongoing.end();) {
475 if ((*it)->getRequest().caller == caller) {
477 it = m_all_ongoing.erase(it);
483 // Also abort all queued fetches for the caller
484 for (std::list<HTTPFetchRequest>::iterator
485 it = m_queued_fetches.begin();
486 it != m_queued_fetches.end();) {
487 if ((*it).caller == caller)
488 it = m_queued_fetches.erase(it);
493 else if (req.type == RT_WAKEUP) {
494 // Wakeup: Nothing to do, thread is awake at this point
497 if (req.event != NULL)
501 // Start new ongoing fetches if m_parallel_limit allows
502 void processQueued(CurlHandlePool *pool)
504 while (m_all_ongoing.size() < m_parallel_limit &&
505 !m_queued_fetches.empty()) {
506 HTTPFetchRequest request = m_queued_fetches.front();
507 m_queued_fetches.pop_front();
509 // Create ongoing fetch data and make a cURL handle
510 // Set cURL options based on HTTPFetchRequest
511 HTTPFetchOngoing *ongoing =
512 new HTTPFetchOngoing(request, pool);
514 // Initiate the connection (curl_multi_add_handle)
515 CURLcode res = ongoing->start(m_multi);
516 if (res == CURLE_OK) {
517 m_all_ongoing.push_back(ongoing);
520 httpfetch_deliver_result(*ongoing->complete(res));
526 // Process CURLMsg (indicates completion of a fetch)
527 void processCurlMessage(CURLMsg *msg)
529 // Determine which ongoing fetch the message pertains to
532 for (i = 0; i < m_all_ongoing.size(); ++i) {
533 if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
538 if (msg->msg == CURLMSG_DONE && found) {
539 // m_all_ongoing[i] succeeded or failed.
540 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
541 httpfetch_deliver_result(*ongoing->complete(msg->data.result));
543 m_all_ongoing.erase(m_all_ongoing.begin() + i);
547 // Wait for a request from another thread, or timeout elapses
548 void waitForRequest(long timeout)
550 if (m_queued_fetches.empty()) {
552 Request req = m_requests.pop_front(timeout);
555 catch (ItemNotFoundException &e) {}
559 // Wait until some IO happens, or timeout elapses
560 void waitForIO(long timeout)
566 long select_timeout = -1;
567 struct timeval select_tv;
570 FD_ZERO(&read_fd_set);
571 FD_ZERO(&write_fd_set);
572 FD_ZERO(&exc_fd_set);
574 mres = curl_multi_fdset(m_multi, &read_fd_set,
575 &write_fd_set, &exc_fd_set, &max_fd);
576 if (mres != CURLM_OK) {
577 errorstream<<"curl_multi_fdset"
578 <<" returned error code "<<mres
583 mres = curl_multi_timeout(m_multi, &select_timeout);
584 if (mres != CURLM_OK) {
585 errorstream<<"curl_multi_timeout"
586 <<" returned error code "<<mres
591 // Limit timeout so new requests get through
592 if (select_timeout < 0 || select_timeout > timeout)
593 select_timeout = timeout;
595 if (select_timeout > 0) {
596 // in Winsock it is forbidden to pass three empty
597 // fd_sets to select(), so in that case use sleep_ms
599 select_tv.tv_sec = select_timeout / 1000;
600 select_tv.tv_usec = (select_timeout % 1000) * 1000;
601 int retval = select(max_fd + 1, &read_fd_set,
602 &write_fd_set, &exc_fd_set,
606 errorstream<<"select returned error code "
607 <<WSAGetLastError()<<std::endl;
609 errorstream<<"select returned error code "
615 sleep_ms(select_timeout);
623 log_register_thread("CurlFetchThread");
624 DSTACK(__FUNCTION_NAME);
626 porting::setThreadName("CurlFetchThread");
630 m_multi = curl_multi_init();
631 if (m_multi == NULL) {
632 errorstream<<"curl_multi_init returned NULL\n";
636 assert(m_all_ongoing.empty());
638 while (!StopRequested()) {
639 BEGIN_DEBUG_EXCEPTION_HANDLER
642 Handle new async requests
645 while (!m_requests.empty()) {
646 Request req = m_requests.pop_frontNoEx();
649 processQueued(&pool);
652 Handle ongoing async requests
655 int still_ongoing = 0;
656 while (curl_multi_perform(m_multi, &still_ongoing) ==
657 CURLM_CALL_MULTI_PERFORM)
661 Handle completed async requests
663 if (still_ongoing < (int) m_all_ongoing.size()) {
666 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
667 while (msg != NULL) {
668 processCurlMessage(msg);
669 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
674 If there are ongoing requests, wait for data
675 (with a timeout of 100ms so that new requests
678 If no ongoing requests, wait for a new request.
679 (Possibly an empty request that signals
680 that the thread should be stopped.)
682 if (m_all_ongoing.empty())
683 waitForRequest(100000000);
687 END_DEBUG_EXCEPTION_HANDLER(errorstream)
690 // Call curl_multi_remove_handle and cleanup easy handles
691 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
692 delete m_all_ongoing[i];
694 m_all_ongoing.clear();
696 m_queued_fetches.clear();
698 CURLMcode mres = curl_multi_cleanup(m_multi);
699 if (mres != CURLM_OK) {
700 errorstream<<"curl_multi_cleanup"
701 <<" returned error code "<<mres
709 CurlFetchThread *g_httpfetch_thread = NULL;
711 void httpfetch_init(int parallel_limit)
713 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
716 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
717 assert(res == CURLE_OK);
719 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
722 void httpfetch_cleanup()
724 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
726 g_httpfetch_thread->Stop();
727 g_httpfetch_thread->requestWakeUp();
728 g_httpfetch_thread->Wait();
729 delete g_httpfetch_thread;
731 curl_global_cleanup();
734 void httpfetch_async(const HTTPFetchRequest &fetch_request)
736 g_httpfetch_thread->requestFetch(fetch_request);
737 if (!g_httpfetch_thread->IsRunning())
738 g_httpfetch_thread->Start();
741 static void httpfetch_request_clear(unsigned long caller)
743 if (g_httpfetch_thread->IsRunning()) {
745 g_httpfetch_thread->requestClear(caller, &event);
749 g_httpfetch_thread->requestClear(caller, NULL);
753 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
754 HTTPFetchResult &fetch_result)
756 // Create ongoing fetch data and make a cURL handle
757 // Set cURL options based on HTTPFetchRequest
759 HTTPFetchOngoing ongoing(fetch_request, &pool);
760 // Do the fetch (curl_easy_perform)
761 CURLcode res = ongoing.start(NULL);
762 // Update fetch result
763 fetch_result = *ongoing.complete(res);
771 Dummy httpfetch implementation that always returns an error.
774 void httpfetch_init(int parallel_limit)
778 void httpfetch_cleanup()
782 void httpfetch_async(const HTTPFetchRequest &fetch_request)
784 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
785 << " because USE_CURL=0" << std::endl;
787 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
788 httpfetch_deliver_result(fetch_result);
791 static void httpfetch_request_clear(unsigned long caller)
795 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
796 HTTPFetchResult &fetch_result)
798 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
799 << " because USE_CURL=0" << std::endl;
801 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.