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;
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_back(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::list<HTTPFetchResult> >::iterator
74 it = g_httpfetch_results.find(caller);
75 if (it == g_httpfetch_results.end()) {
76 verbosestream<<"httpfetch_caller_alloc: allocating "
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::list<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::list<HTTPFetchResult> &caller_results = it->second;
112 if (caller_results.empty())
116 fetch_result = caller_results.front();
117 caller_results.pop_front();
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;
198 struct curl_slist *http_header;
203 HTTPFetchOngoing::HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
209 oss(std::ios::binary),
213 curl = pool->alloc();
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);
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());
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.
238 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
239 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
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,
247 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
248 request.connect_timeout);
250 if (request.useragent != "")
251 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
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);
261 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
262 httpfetch_writefunction);
263 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
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(),
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);
287 for (std::map<std::string, std::string>::iterator it =
288 request.post_fields.begin();
289 it != request.post_fields.end();
293 str += urlencode(it->first);
295 str += urlencode(it->second);
297 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
299 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
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
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());
315 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
317 if (!g_settings->getBool("curl_verify_cert")) {
318 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
322 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
325 return CURLE_FAILED_INIT;
328 // Easy interface (sync)
329 return curl_easy_perform(curl);
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
338 return CURLE_FAILED_INIT;
340 multi = multi_; // store for curl_multi_remove_handle
344 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
346 result.succeeded = (res == CURLE_OK);
347 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
348 result.data = oss.str();
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;
358 if (res != CURLE_OK) {
359 errorstream << request.url << " not found ("
360 << curl_easy_strerror(res) << ")"
361 << " (response code " << result.response_code << ")"
368 HTTPFetchOngoing::~HTTPFetchOngoing()
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
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);
385 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
386 curl_slist_free_all(http_header);
389 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
393 // Store the cURL handle for reuse
398 class CurlFetchThread : public JThread
409 HTTPFetchRequest fetch_request;
414 MutexedQueue<Request> m_requests;
415 size_t m_parallel_limit;
417 // Variables exclusively used within thread
418 std::vector<HTTPFetchOngoing*> m_all_ongoing;
419 std::list<HTTPFetchRequest> m_queued_fetches;
422 CurlFetchThread(int parallel_limit)
424 if (parallel_limit >= 1)
425 m_parallel_limit = parallel_limit;
427 m_parallel_limit = 1;
430 void requestFetch(const HTTPFetchRequest &fetch_request)
434 req.fetch_request = fetch_request;
436 m_requests.push_back(req);
439 void requestClear(unsigned long caller, Event *event)
443 req.fetch_request.caller = caller;
445 m_requests.push_back(req);
451 req.type = RT_WAKEUP;
453 m_requests.push_back(req);
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)
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);
466 // see processQueued() for what happens next
469 else if (req.type == RT_CLEAR) {
470 unsigned long caller = req.fetch_request.caller;
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) {
478 it = m_all_ongoing.erase(it);
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);
494 else if (req.type == RT_WAKEUP) {
495 // Wakeup: Nothing to do, thread is awake at this point
498 if (req.event != NULL)
502 // Start new ongoing fetches if m_parallel_limit allows
503 void processQueued(CurlHandlePool *pool)
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();
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);
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);
521 httpfetch_deliver_result(*ongoing->complete(res));
527 // Process CURLMsg (indicates completion of a fetch)
528 void processCurlMessage(CURLMsg *msg)
530 // Determine which ongoing fetch the message pertains to
533 for (i = 0; i < m_all_ongoing.size(); ++i) {
534 if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
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));
544 m_all_ongoing.erase(m_all_ongoing.begin() + i);
548 // Wait for a request from another thread, or timeout elapses
549 void waitForRequest(long timeout)
551 if (m_queued_fetches.empty()) {
553 Request req = m_requests.pop_front(timeout);
556 catch (ItemNotFoundException &e) {}
560 // Wait until some IO happens, or timeout elapses
561 void waitForIO(long timeout)
567 long select_timeout = -1;
568 struct timeval select_tv;
571 FD_ZERO(&read_fd_set);
572 FD_ZERO(&write_fd_set);
573 FD_ZERO(&exc_fd_set);
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
584 mres = curl_multi_timeout(m_multi, &select_timeout);
585 if (mres != CURLM_OK) {
586 errorstream<<"curl_multi_timeout"
587 <<" returned error code "<<mres
592 // Limit timeout so new requests get through
593 if (select_timeout < 0 || select_timeout > timeout)
594 select_timeout = timeout;
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
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,
607 errorstream<<"select returned error code "
608 <<WSAGetLastError()<<std::endl;
610 errorstream<<"select returned error code "
616 sleep_ms(select_timeout);
624 log_register_thread("CurlFetchThread");
625 DSTACK(__FUNCTION_NAME);
627 porting::setThreadName("CurlFetchThread");
631 m_multi = curl_multi_init();
632 if (m_multi == NULL) {
633 errorstream<<"curl_multi_init returned NULL\n";
637 assert(m_all_ongoing.empty());
639 while (!StopRequested()) {
640 BEGIN_DEBUG_EXCEPTION_HANDLER
643 Handle new async requests
646 while (!m_requests.empty()) {
647 Request req = m_requests.pop_frontNoEx();
650 processQueued(&pool);
653 Handle ongoing async requests
656 int still_ongoing = 0;
657 while (curl_multi_perform(m_multi, &still_ongoing) ==
658 CURLM_CALL_MULTI_PERFORM)
662 Handle completed async requests
664 if (still_ongoing < (int) m_all_ongoing.size()) {
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);
675 If there are ongoing requests, wait for data
676 (with a timeout of 100ms so that new requests
679 If no ongoing requests, wait for a new request.
680 (Possibly an empty request that signals
681 that the thread should be stopped.)
683 if (m_all_ongoing.empty())
684 waitForRequest(100000000);
688 END_DEBUG_EXCEPTION_HANDLER(errorstream)
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];
695 m_all_ongoing.clear();
697 m_queued_fetches.clear();
699 CURLMcode mres = curl_multi_cleanup(m_multi);
700 if (mres != CURLM_OK) {
701 errorstream<<"curl_multi_cleanup"
702 <<" returned error code "<<mres
710 CurlFetchThread *g_httpfetch_thread = NULL;
712 void httpfetch_init(int parallel_limit)
714 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
717 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
718 assert(res == CURLE_OK);
720 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
723 void httpfetch_cleanup()
725 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
727 g_httpfetch_thread->Stop();
728 g_httpfetch_thread->requestWakeUp();
729 g_httpfetch_thread->Wait();
730 delete g_httpfetch_thread;
732 curl_global_cleanup();
735 void httpfetch_async(const HTTPFetchRequest &fetch_request)
737 g_httpfetch_thread->requestFetch(fetch_request);
738 if (!g_httpfetch_thread->IsRunning())
739 g_httpfetch_thread->Start();
742 static void httpfetch_request_clear(unsigned long caller)
744 if (g_httpfetch_thread->IsRunning()) {
746 g_httpfetch_thread->requestClear(caller, &event);
750 g_httpfetch_thread->requestClear(caller, NULL);
754 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
755 HTTPFetchResult &fetch_result)
757 // Create ongoing fetch data and make a cURL handle
758 // Set cURL options based on HTTPFetchRequest
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);
772 Dummy httpfetch implementation that always returns an error.
775 void httpfetch_init(int parallel_limit)
779 void httpfetch_cleanup()
783 void httpfetch_async(const HTTPFetchRequest &fetch_request)
785 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
786 << " because USE_CURL=0" << std::endl;
788 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
789 httpfetch_deliver_result(fetch_result);
792 static void httpfetch_request_clear(unsigned long caller)
796 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
797 HTTPFetchResult &fetch_result)
799 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
800 << " because USE_CURL=0" << std::endl;
802 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.