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()
22 #include "httpfetch.h"
29 #include <sys/utsname.h>
31 #include "jthread/jevent.h"
33 #include "exceptions.h"
36 #include "util/container.h"
37 #include "util/thread.h"
42 JMutex g_httpfetch_mutex;
43 std::map<unsigned long, std::list<HTTPFetchResult> > g_httpfetch_results;
45 HTTPFetchRequest::HTTPFetchRequest()
48 caller = HTTPFETCH_DISCARD;
50 timeout = g_settings->getS32("curl_timeout");
51 connect_timeout = timeout * 5;
53 useragent = std::string("Minetest/") + minetest_version_hash + " ";
55 useragent += "(Windows)";
57 struct utsname osinfo;
59 useragent += std::string("(") + osinfo.sysname + "/"
60 + osinfo.release + " " + osinfo.machine + ")";
65 static void httpfetch_deliver_result(const HTTPFetchResult &fetchresult)
67 unsigned long caller = fetchresult.caller;
68 if (caller != HTTPFETCH_DISCARD) {
69 JMutexAutoLock lock(g_httpfetch_mutex);
70 g_httpfetch_results[caller].push_back(fetchresult);
74 static void httpfetch_request_clear(unsigned long caller);
76 unsigned long httpfetch_caller_alloc()
78 JMutexAutoLock lock(g_httpfetch_mutex);
80 // Check each caller ID except HTTPFETCH_DISCARD
81 const unsigned long discard = HTTPFETCH_DISCARD;
82 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
83 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
84 it = g_httpfetch_results.find(caller);
85 if (it == g_httpfetch_results.end()) {
86 verbosestream<<"httpfetch_caller_alloc: allocating "
88 // Access element to create it
89 g_httpfetch_results[caller];
94 assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
98 void httpfetch_caller_free(unsigned long caller)
100 verbosestream<<"httpfetch_caller_free: freeing "
103 httpfetch_request_clear(caller);
104 if (caller != HTTPFETCH_DISCARD) {
105 JMutexAutoLock lock(g_httpfetch_mutex);
106 g_httpfetch_results.erase(caller);
110 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetchresult)
112 JMutexAutoLock lock(g_httpfetch_mutex);
114 // Check that caller exists
115 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
116 it = g_httpfetch_results.find(caller);
117 if (it == g_httpfetch_results.end())
120 // Check that result queue is nonempty
121 std::list<HTTPFetchResult> &callerresults = it->second;
122 if (callerresults.empty())
126 fetchresult = callerresults.front();
127 callerresults.pop_front();
132 #include <curl/curl.h>
135 USE_CURL is on: use cURL based httpfetch implementation
138 static size_t httpfetch_writefunction(
139 char *ptr, size_t size, size_t nmemb, void *userdata)
141 std::ostringstream *stream = (std::ostringstream*)userdata;
142 size_t count = size * nmemb;
143 stream->write(ptr, count);
147 static size_t httpfetch_discardfunction(
148 char *ptr, size_t size, size_t nmemb, void *userdata)
155 std::list<CURL*> handles;
161 for (std::list<CURL*>::iterator it = handles.begin();
162 it != handles.end(); ++it) {
163 curl_easy_cleanup(*it);
169 if (handles.empty()) {
170 curl = curl_easy_init();
172 errorstream<<"curl_easy_init returned NULL"<<std::endl;
176 curl = handles.front();
181 void free(CURL *handle)
184 handles.push_back(handle);
188 struct HTTPFetchOngoing
190 CurlHandlePool *pool;
193 HTTPFetchRequest request;
194 HTTPFetchResult result;
195 std::ostringstream oss;
197 struct curl_slist *httpheader;
199 HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
205 oss(std::ios::binary),
208 curl = pool->alloc();
210 // Set static cURL options
211 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
212 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
213 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
214 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
216 #if LIBCURL_VERSION_NUM >= 0x071304
217 // Restrict protocols so that curl vulnerabilities in
218 // other protocols don't affect us.
219 // These settings were introduced in curl 7.19.4.
225 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
226 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
229 // Set cURL options based on HTTPFetchRequest
230 curl_easy_setopt(curl, CURLOPT_URL,
231 request.url.c_str());
232 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
234 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
235 request.connect_timeout);
237 if (request.useragent != "")
238 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
240 // Set up a write callback that writes to the
241 // ostringstream ongoing->oss, unless the data
242 // is to be discarded
243 if (request.caller == HTTPFETCH_DISCARD) {
244 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
245 httpfetch_discardfunction);
246 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
249 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
250 httpfetch_writefunction);
251 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
253 // Set POST (or GET) data
254 if (request.post_fields.empty()) {
255 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
258 curl_easy_setopt(curl, CURLOPT_POST, 1);
259 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
260 request.post_fields.size());
261 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
262 request.post_fields.c_str());
263 // request.post_fields must now *never* be
264 // modified until CURLOPT_POSTFIELDS is cleared
266 // Set additional HTTP headers
267 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
268 httpheader = curl_slist_append(
270 request.extra_headers[i].c_str());
272 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
276 CURLcode start(CURLM *multi_)
279 return CURLE_FAILED_INIT;
282 // Multi interface (async)
283 CURLMcode mres = curl_multi_add_handle(multi_, curl);
284 if (mres != CURLM_OK) {
285 errorstream<<"curl_multi_add_handle"
286 <<" returned error code "<<mres
288 return CURLE_FAILED_INIT;
290 multi = multi_; // store for curl_multi_remove_handle
294 // Easy interface (sync)
295 return curl_easy_perform(curl);
299 void complete(CURLcode res)
301 result.succeeded = (res == CURLE_OK);
302 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
303 result.data = oss.str();
305 // Get HTTP/FTP response code
306 result.response_code = 0;
308 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
309 &result.response_code) != CURLE_OK) {
310 //we failed to get a return code make sure it is still 0
311 result.response_code = 0;
315 if (res != CURLE_OK) {
316 infostream<<request.url<<" not found ("
317 <<curl_easy_strerror(res)<<")"
318 <<" (response code "<<result.response_code<<")"
326 CURLMcode mres = curl_multi_remove_handle(multi, curl);
327 if (mres != CURLM_OK) {
328 errorstream<<"curl_multi_remove_handle"
329 <<" returned error code "<<mres
334 // Set safe options for the reusable cURL handle
335 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
336 httpfetch_discardfunction);
337 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
338 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
339 if (httpheader != NULL) {
340 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
341 curl_slist_free_all(httpheader);
344 // Store the cURL handle for reuse
349 class CurlFetchThread : public JThread
360 HTTPFetchRequest fetchrequest;
365 MutexedQueue<Request> m_requests;
366 size_t m_parallel_limit;
368 // Variables exclusively used within thread
369 std::vector<HTTPFetchOngoing*> m_all_ongoing;
370 std::list<HTTPFetchRequest> m_queued_fetches;
373 CurlFetchThread(int parallel_limit)
375 if (parallel_limit >= 1)
376 m_parallel_limit = parallel_limit;
378 m_parallel_limit = 1;
381 void requestFetch(const HTTPFetchRequest &fetchrequest)
385 req.fetchrequest = fetchrequest;
387 m_requests.push_back(req);
390 void requestClear(unsigned long caller, Event *event)
394 req.fetchrequest.caller = caller;
396 m_requests.push_back(req);
402 req.type = RT_WAKEUP;
404 m_requests.push_back(req);
408 // Handle a request from some other thread
409 // E.g. new fetch; clear fetches for one caller; wake up
410 void processRequest(const Request &req)
412 if (req.type == RT_FETCH) {
413 // New fetch, queue until there are less
414 // than m_parallel_limit ongoing fetches
415 m_queued_fetches.push_back(req.fetchrequest);
417 // see processQueued() for what happens next
420 else if (req.type == RT_CLEAR) {
421 unsigned long caller = req.fetchrequest.caller;
423 // Abort all ongoing fetches for the caller
424 for (std::vector<HTTPFetchOngoing*>::iterator
425 it = m_all_ongoing.begin();
426 it != m_all_ongoing.end();) {
427 if ((*it)->request.caller == caller) {
429 it = m_all_ongoing.erase(it);
435 // Also abort all queued fetches for the caller
436 for (std::list<HTTPFetchRequest>::iterator
437 it = m_queued_fetches.begin();
438 it != m_queued_fetches.end();) {
439 if ((*it).caller == caller)
440 it = m_queued_fetches.erase(it);
445 else if (req.type == RT_WAKEUP) {
446 // Wakeup: Nothing to do, thread is awake at this point
449 if (req.event != NULL)
453 // Start new ongoing fetches if m_parallel_limit allows
454 void processQueued(CurlHandlePool *pool)
456 while (m_all_ongoing.size() < m_parallel_limit &&
457 !m_queued_fetches.empty()) {
458 HTTPFetchRequest request = m_queued_fetches.front();
459 m_queued_fetches.pop_front();
461 // Create ongoing fetch data and make a cURL handle
462 // Set cURL options based on HTTPFetchRequest
463 HTTPFetchOngoing *ongoing =
464 new HTTPFetchOngoing(request, pool);
466 // Initiate the connection (curl_multi_add_handle)
467 CURLcode res = ongoing->start(m_multi);
468 if (res == CURLE_OK) {
469 m_all_ongoing.push_back(ongoing);
472 ongoing->complete(res);
473 httpfetch_deliver_result(ongoing->result);
479 // Process CURLMsg (indicates completion of a fetch)
480 void processCurlMessage(CURLMsg *msg)
482 // Determine which ongoing fetch the message pertains to
485 for (i = 0; i < m_all_ongoing.size(); ++i) {
486 if (m_all_ongoing[i]->curl == msg->easy_handle) {
491 if (msg->msg == CURLMSG_DONE && found) {
492 // m_all_ongoing[i] succeeded or failed.
493 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
494 ongoing->complete(msg->data.result);
495 httpfetch_deliver_result(ongoing->result);
497 m_all_ongoing.erase(m_all_ongoing.begin() + i);
501 // Wait for a request from another thread, or timeout elapses
502 void waitForRequest(long timeout)
504 if (m_queued_fetches.empty()) {
506 Request req = m_requests.pop_front(timeout);
509 catch (ItemNotFoundException &e) {}
513 // Wait until some IO happens, or timeout elapses
514 void waitForIO(long timeout)
520 long select_timeout = -1;
521 struct timeval select_tv;
524 FD_ZERO(&read_fd_set);
525 FD_ZERO(&write_fd_set);
526 FD_ZERO(&exc_fd_set);
528 mres = curl_multi_fdset(m_multi, &read_fd_set,
529 &write_fd_set, &exc_fd_set, &max_fd);
530 if (mres != CURLM_OK) {
531 errorstream<<"curl_multi_fdset"
532 <<" returned error code "<<mres
537 mres = curl_multi_timeout(m_multi, &select_timeout);
538 if (mres != CURLM_OK) {
539 errorstream<<"curl_multi_timeout"
540 <<" returned error code "<<mres
545 // Limit timeout so new requests get through
546 if (select_timeout < 0 || select_timeout > timeout)
547 select_timeout = timeout;
549 if (select_timeout > 0) {
550 // in Winsock it is forbidden to pass three empty
551 // fd_sets to select(), so in that case use sleep_ms
553 select_tv.tv_sec = select_timeout / 1000;
554 select_tv.tv_usec = (select_timeout % 1000) * 1000;
555 int retval = select(max_fd + 1, &read_fd_set,
556 &write_fd_set, &exc_fd_set,
560 errorstream<<"select returned error code "
561 <<WSAGetLastError()<<std::endl;
563 errorstream<<"select returned error code "
569 sleep_ms(select_timeout);
577 log_register_thread("CurlFetchThread");
578 DSTACK(__FUNCTION_NAME);
582 m_multi = curl_multi_init();
583 if (m_multi == NULL) {
584 errorstream<<"curl_multi_init returned NULL\n";
588 assert(m_all_ongoing.empty());
590 while (!StopRequested()) {
591 BEGIN_DEBUG_EXCEPTION_HANDLER
594 Handle new async requests
597 while (!m_requests.empty()) {
598 Request req = m_requests.pop_frontNoEx();
601 processQueued(&pool);
604 Handle ongoing async requests
607 int still_ongoing = 0;
608 while (curl_multi_perform(m_multi, &still_ongoing) ==
609 CURLM_CALL_MULTI_PERFORM)
613 Handle completed async requests
615 if (still_ongoing < (int) m_all_ongoing.size()) {
618 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
619 while (msg != NULL) {
620 processCurlMessage(msg);
621 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
626 If there are ongoing requests, wait for data
627 (with a timeout of 100ms so that new requests
630 If no ongoing requests, wait for a new request.
631 (Possibly an empty request that signals
632 that the thread should be stopped.)
634 if (m_all_ongoing.empty())
635 waitForRequest(100000000);
639 END_DEBUG_EXCEPTION_HANDLER(errorstream)
642 // Call curl_multi_remove_handle and cleanup easy handles
643 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
644 delete m_all_ongoing[i];
646 m_all_ongoing.clear();
648 m_queued_fetches.clear();
650 CURLMcode mres = curl_multi_cleanup(m_multi);
651 if (mres != CURLM_OK) {
652 errorstream<<"curl_multi_cleanup"
653 <<" returned error code "<<mres
661 CurlFetchThread *g_httpfetch_thread = NULL;
663 void httpfetch_init(int parallel_limit)
665 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
668 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
669 assert(res == CURLE_OK);
671 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
674 void httpfetch_cleanup()
676 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
678 g_httpfetch_thread->Stop();
679 g_httpfetch_thread->requestWakeUp();
680 g_httpfetch_thread->Wait();
681 delete g_httpfetch_thread;
683 curl_global_cleanup();
686 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
688 g_httpfetch_thread->requestFetch(fetchrequest);
689 if (!g_httpfetch_thread->IsRunning())
690 g_httpfetch_thread->Start();
693 static void httpfetch_request_clear(unsigned long caller)
695 if (g_httpfetch_thread->IsRunning()) {
697 g_httpfetch_thread->requestClear(caller, &event);
701 g_httpfetch_thread->requestClear(caller, NULL);
705 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
706 HTTPFetchResult &fetchresult)
708 // Create ongoing fetch data and make a cURL handle
709 // Set cURL options based on HTTPFetchRequest
711 HTTPFetchOngoing ongoing(fetchrequest, &pool);
712 // Do the fetch (curl_easy_perform)
713 CURLcode res = ongoing.start(NULL);
714 // Update fetchresult
715 ongoing.complete(res);
716 fetchresult = ongoing.result;
724 Dummy httpfetch implementation that always returns an error.
727 void httpfetch_init(int parallel_limit)
731 void httpfetch_cleanup()
735 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
737 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
738 <<" because USE_CURL=0"<<std::endl;
740 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
741 httpfetch_deliver_result(fetchresult);
744 static void httpfetch_request_clear(unsigned long caller)
748 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
749 HTTPFetchResult &fetchresult)
751 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
752 <<" because USE_CURL=0"<<std::endl;
754 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.