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);
265 CURLcode start(CURLM *multi_)
268 return CURLE_FAILED_INIT;
271 // Multi interface (async)
272 CURLMcode mres = curl_multi_add_handle(multi_, curl);
273 if (mres != CURLM_OK) {
274 errorstream<<"curl_multi_add_handle"
275 <<" returned error code "<<mres
277 return CURLE_FAILED_INIT;
279 multi = multi_; // store for curl_multi_remove_handle
283 // Easy interface (sync)
284 return curl_easy_perform(curl);
288 void complete(CURLcode res)
290 result.succeeded = (res == CURLE_OK);
291 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
292 result.data = oss.str();
294 // Get HTTP/FTP response code
295 result.response_code = 0;
297 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
298 &result.response_code) != CURLE_OK) {
299 //we failed to get a return code make sure it is still 0
300 result.response_code = 0;
304 if (res != CURLE_OK) {
305 infostream<<request.url<<" not found ("
306 <<curl_easy_strerror(res)<<")"
307 <<" (response code "<<result.response_code<<")"
315 CURLMcode mres = curl_multi_remove_handle(multi, curl);
316 if (mres != CURLM_OK) {
317 errorstream<<"curl_multi_remove_handle"
318 <<" returned error code "<<mres
323 // Set safe options for the reusable cURL handle
324 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
325 httpfetch_discardfunction);
326 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
327 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
328 if (httpheader != NULL) {
329 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
330 curl_slist_free_all(httpheader);
333 // Store the cURL handle for reuse
338 class CurlFetchThread : public JThread
349 HTTPFetchRequest fetchrequest;
354 MutexedQueue<Request> m_requests;
355 size_t m_parallel_limit;
357 // Variables exclusively used within thread
358 std::vector<HTTPFetchOngoing*> m_all_ongoing;
359 std::list<HTTPFetchRequest> m_queued_fetches;
362 CurlFetchThread(int parallel_limit)
364 if (parallel_limit >= 1)
365 m_parallel_limit = parallel_limit;
367 m_parallel_limit = 1;
370 void requestFetch(const HTTPFetchRequest &fetchrequest)
374 req.fetchrequest = fetchrequest;
376 m_requests.push_back(req);
379 void requestClear(unsigned long caller, Event *event)
383 req.fetchrequest.caller = caller;
385 m_requests.push_back(req);
391 req.type = RT_WAKEUP;
393 m_requests.push_back(req);
397 // Handle a request from some other thread
398 // E.g. new fetch; clear fetches for one caller; wake up
399 void processRequest(const Request &req)
401 if (req.type == RT_FETCH) {
402 // New fetch, queue until there are less
403 // than m_parallel_limit ongoing fetches
404 m_queued_fetches.push_back(req.fetchrequest);
406 // see processQueued() for what happens next
409 else if (req.type == RT_CLEAR) {
410 unsigned long caller = req.fetchrequest.caller;
412 // Abort all ongoing fetches for the caller
413 for (std::vector<HTTPFetchOngoing*>::iterator
414 it = m_all_ongoing.begin();
415 it != m_all_ongoing.end();) {
416 if ((*it)->request.caller == caller) {
418 it = m_all_ongoing.erase(it);
424 // Also abort all queued fetches for the caller
425 for (std::list<HTTPFetchRequest>::iterator
426 it = m_queued_fetches.begin();
427 it != m_queued_fetches.end();) {
428 if ((*it).caller == caller)
429 it = m_queued_fetches.erase(it);
434 else if (req.type == RT_WAKEUP) {
435 // Wakeup: Nothing to do, thread is awake at this point
438 if (req.event != NULL)
442 // Start new ongoing fetches if m_parallel_limit allows
443 void processQueued(CurlHandlePool *pool)
445 while (m_all_ongoing.size() < m_parallel_limit &&
446 !m_queued_fetches.empty()) {
447 HTTPFetchRequest request = m_queued_fetches.front();
448 m_queued_fetches.pop_front();
450 // Create ongoing fetch data and make a cURL handle
451 // Set cURL options based on HTTPFetchRequest
452 HTTPFetchOngoing *ongoing =
453 new HTTPFetchOngoing(request, pool);
455 // Initiate the connection (curl_multi_add_handle)
456 CURLcode res = ongoing->start(m_multi);
457 if (res == CURLE_OK) {
458 m_all_ongoing.push_back(ongoing);
461 ongoing->complete(res);
462 httpfetch_deliver_result(ongoing->result);
468 // Process CURLMsg (indicates completion of a fetch)
469 void processCurlMessage(CURLMsg *msg)
471 // Determine which ongoing fetch the message pertains to
474 for (i = 0; i < m_all_ongoing.size(); ++i) {
475 if (m_all_ongoing[i]->curl == msg->easy_handle) {
480 if (msg->msg == CURLMSG_DONE && found) {
481 // m_all_ongoing[i] succeeded or failed.
482 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
483 ongoing->complete(msg->data.result);
484 httpfetch_deliver_result(ongoing->result);
486 m_all_ongoing.erase(m_all_ongoing.begin() + i);
490 // Wait for a request from another thread, or timeout elapses
491 void waitForRequest(long timeout)
493 if (m_queued_fetches.empty()) {
495 Request req = m_requests.pop_front(timeout);
498 catch (ItemNotFoundException &e) {}
502 // Wait until some IO happens, or timeout elapses
503 void waitForIO(long timeout)
509 long select_timeout = -1;
510 struct timeval select_tv;
513 FD_ZERO(&read_fd_set);
514 FD_ZERO(&write_fd_set);
515 FD_ZERO(&exc_fd_set);
517 mres = curl_multi_fdset(m_multi, &read_fd_set,
518 &write_fd_set, &exc_fd_set, &max_fd);
519 if (mres != CURLM_OK) {
520 errorstream<<"curl_multi_fdset"
521 <<" returned error code "<<mres
526 mres = curl_multi_timeout(m_multi, &select_timeout);
527 if (mres != CURLM_OK) {
528 errorstream<<"curl_multi_timeout"
529 <<" returned error code "<<mres
534 // Limit timeout so new requests get through
535 if (select_timeout < 0 || select_timeout > timeout)
536 select_timeout = timeout;
538 if (select_timeout > 0) {
539 // in Winsock it is forbidden to pass three empty
540 // fd_sets to select(), so in that case use sleep_ms
542 select_tv.tv_sec = select_timeout / 1000;
543 select_tv.tv_usec = (select_timeout % 1000) * 1000;
544 int retval = select(max_fd + 1, &read_fd_set,
545 &write_fd_set, &exc_fd_set,
549 errorstream<<"select returned error code "
550 <<WSAGetLastError()<<std::endl;
552 errorstream<<"select returned error code "
558 sleep_ms(select_timeout);
566 log_register_thread("CurlFetchThread");
567 DSTACK(__FUNCTION_NAME);
569 porting::setThreadName("CurlFetchThread");
573 m_multi = curl_multi_init();
574 if (m_multi == NULL) {
575 errorstream<<"curl_multi_init returned NULL\n";
579 assert(m_all_ongoing.empty());
581 while (!StopRequested()) {
582 BEGIN_DEBUG_EXCEPTION_HANDLER
585 Handle new async requests
588 while (!m_requests.empty()) {
589 Request req = m_requests.pop_frontNoEx();
592 processQueued(&pool);
595 Handle ongoing async requests
598 int still_ongoing = 0;
599 while (curl_multi_perform(m_multi, &still_ongoing) ==
600 CURLM_CALL_MULTI_PERFORM)
604 Handle completed async requests
606 if (still_ongoing < (int) m_all_ongoing.size()) {
609 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
610 while (msg != NULL) {
611 processCurlMessage(msg);
612 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
617 If there are ongoing requests, wait for data
618 (with a timeout of 100ms so that new requests
621 If no ongoing requests, wait for a new request.
622 (Possibly an empty request that signals
623 that the thread should be stopped.)
625 if (m_all_ongoing.empty())
626 waitForRequest(100000000);
630 END_DEBUG_EXCEPTION_HANDLER(errorstream)
633 // Call curl_multi_remove_handle and cleanup easy handles
634 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
635 delete m_all_ongoing[i];
637 m_all_ongoing.clear();
639 m_queued_fetches.clear();
641 CURLMcode mres = curl_multi_cleanup(m_multi);
642 if (mres != CURLM_OK) {
643 errorstream<<"curl_multi_cleanup"
644 <<" returned error code "<<mres
652 CurlFetchThread *g_httpfetch_thread = NULL;
654 void httpfetch_init(int parallel_limit)
656 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
659 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
660 assert(res == CURLE_OK);
662 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
665 void httpfetch_cleanup()
667 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
669 g_httpfetch_thread->Stop();
670 g_httpfetch_thread->requestWakeUp();
671 g_httpfetch_thread->Wait();
672 delete g_httpfetch_thread;
674 curl_global_cleanup();
677 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
679 g_httpfetch_thread->requestFetch(fetchrequest);
680 if (!g_httpfetch_thread->IsRunning())
681 g_httpfetch_thread->Start();
684 static void httpfetch_request_clear(unsigned long caller)
686 if (g_httpfetch_thread->IsRunning()) {
688 g_httpfetch_thread->requestClear(caller, &event);
692 g_httpfetch_thread->requestClear(caller, NULL);
696 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
697 HTTPFetchResult &fetchresult)
699 // Create ongoing fetch data and make a cURL handle
700 // Set cURL options based on HTTPFetchRequest
702 HTTPFetchOngoing ongoing(fetchrequest, &pool);
703 // Do the fetch (curl_easy_perform)
704 CURLcode res = ongoing.start(NULL);
705 // Update fetchresult
706 ongoing.complete(res);
707 fetchresult = ongoing.result;
715 Dummy httpfetch implementation that always returns an error.
718 void httpfetch_init(int parallel_limit)
722 void httpfetch_cleanup()
726 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
728 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
729 <<" because USE_CURL=0"<<std::endl;
731 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
732 httpfetch_deliver_result(fetchresult);
735 static void httpfetch_request_clear(unsigned long caller)
739 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
740 HTTPFetchResult &fetchresult)
742 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
743 <<" because USE_CURL=0"<<std::endl;
745 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.