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 + "; " + osinfo.release + "; " + osinfo.machine + ")";
64 static void httpfetch_deliver_result(const HTTPFetchResult &fetchresult)
66 unsigned long caller = fetchresult.caller;
67 if (caller != HTTPFETCH_DISCARD) {
68 JMutexAutoLock lock(g_httpfetch_mutex);
69 g_httpfetch_results[caller].push_back(fetchresult);
73 static void httpfetch_request_clear(unsigned long caller);
75 unsigned long httpfetch_caller_alloc()
77 JMutexAutoLock lock(g_httpfetch_mutex);
79 // Check each caller ID except HTTPFETCH_DISCARD
80 const unsigned long discard = HTTPFETCH_DISCARD;
81 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
82 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
83 it = g_httpfetch_results.find(caller);
84 if (it == g_httpfetch_results.end()) {
85 verbosestream<<"httpfetch_caller_alloc: allocating "
87 // Access element to create it
88 g_httpfetch_results[caller];
93 assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
97 void httpfetch_caller_free(unsigned long caller)
99 verbosestream<<"httpfetch_caller_free: freeing "
102 httpfetch_request_clear(caller);
103 if (caller != HTTPFETCH_DISCARD) {
104 JMutexAutoLock lock(g_httpfetch_mutex);
105 g_httpfetch_results.erase(caller);
109 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetchresult)
111 JMutexAutoLock lock(g_httpfetch_mutex);
113 // Check that caller exists
114 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
115 it = g_httpfetch_results.find(caller);
116 if (it == g_httpfetch_results.end())
119 // Check that result queue is nonempty
120 std::list<HTTPFetchResult> &callerresults = it->second;
121 if (callerresults.empty())
125 fetchresult = callerresults.front();
126 callerresults.pop_front();
131 #include <curl/curl.h>
134 USE_CURL is on: use cURL based httpfetch implementation
137 static size_t httpfetch_writefunction(
138 char *ptr, size_t size, size_t nmemb, void *userdata)
140 std::ostringstream *stream = (std::ostringstream*)userdata;
141 size_t count = size * nmemb;
142 stream->write(ptr, count);
146 static size_t httpfetch_discardfunction(
147 char *ptr, size_t size, size_t nmemb, void *userdata)
154 std::list<CURL*> handles;
160 for (std::list<CURL*>::iterator it = handles.begin();
161 it != handles.end(); ++it) {
162 curl_easy_cleanup(*it);
168 if (handles.empty()) {
169 curl = curl_easy_init();
171 errorstream<<"curl_easy_init returned NULL"<<std::endl;
175 curl = handles.front();
180 void free(CURL *handle)
183 handles.push_back(handle);
187 struct HTTPFetchOngoing
189 CurlHandlePool *pool;
192 HTTPFetchRequest request;
193 HTTPFetchResult result;
194 std::ostringstream oss;
196 struct curl_slist *httpheader;
198 HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
204 oss(std::ios::binary),
207 curl = pool->alloc();
209 // Set static cURL options
210 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
211 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
212 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
213 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
215 #if LIBCURL_VERSION_NUM >= 0x071304
216 // Restrict protocols so that curl vulnerabilities in
217 // other protocols don't affect us.
218 // These settings were introduced in curl 7.19.4.
224 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
225 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
228 // Set cURL options based on HTTPFetchRequest
229 curl_easy_setopt(curl, CURLOPT_URL,
230 request.url.c_str());
231 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
233 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
234 request.connect_timeout);
236 if (request.useragent != "")
237 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
239 // Set up a write callback that writes to the
240 // ostringstream ongoing->oss, unless the data
241 // is to be discarded
242 if (request.caller == HTTPFETCH_DISCARD) {
243 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
244 httpfetch_discardfunction);
245 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
248 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
249 httpfetch_writefunction);
250 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
252 // Set POST (or GET) data
253 if (request.post_fields.empty()) {
254 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
257 curl_easy_setopt(curl, CURLOPT_POST, 1);
258 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
259 request.post_fields.size());
260 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
261 request.post_fields.c_str());
262 // request.post_fields must now *never* be
263 // modified until CURLOPT_POSTFIELDS is cleared
265 // Set additional HTTP headers
266 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
267 httpheader = curl_slist_append(
269 request.extra_headers[i].c_str());
271 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
275 CURLcode start(CURLM *multi_)
278 return CURLE_FAILED_INIT;
281 // Multi interface (async)
282 CURLMcode mres = curl_multi_add_handle(multi_, curl);
283 if (mres != CURLM_OK) {
284 errorstream<<"curl_multi_add_handle"
285 <<" returned error code "<<mres
287 return CURLE_FAILED_INIT;
289 multi = multi_; // store for curl_multi_remove_handle
293 // Easy interface (sync)
294 return curl_easy_perform(curl);
298 void complete(CURLcode res)
300 result.succeeded = (res == CURLE_OK);
301 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
302 result.data = oss.str();
304 // Get HTTP/FTP response code
305 result.response_code = 0;
307 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
308 &result.response_code) != CURLE_OK) {
309 //we failed to get a return code make sure it is still 0
310 result.response_code = 0;
314 if (res != CURLE_OK) {
315 infostream<<request.url<<" not found ("
316 <<curl_easy_strerror(res)<<")"
317 <<" (response code "<<result.response_code<<")"
325 CURLMcode mres = curl_multi_remove_handle(multi, curl);
326 if (mres != CURLM_OK) {
327 errorstream<<"curl_multi_remove_handle"
328 <<" returned error code "<<mres
333 // Set safe options for the reusable cURL handle
334 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
335 httpfetch_discardfunction);
336 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
337 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
338 if (httpheader != NULL) {
339 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
340 curl_slist_free_all(httpheader);
343 // Store the cURL handle for reuse
348 class CurlFetchThread : public JThread
359 HTTPFetchRequest fetchrequest;
364 MutexedQueue<Request> m_requests;
365 size_t m_parallel_limit;
367 // Variables exclusively used within thread
368 std::vector<HTTPFetchOngoing*> m_all_ongoing;
369 std::list<HTTPFetchRequest> m_queued_fetches;
372 CurlFetchThread(int parallel_limit)
374 if (parallel_limit >= 1)
375 m_parallel_limit = parallel_limit;
377 m_parallel_limit = 1;
380 void requestFetch(const HTTPFetchRequest &fetchrequest)
384 req.fetchrequest = fetchrequest;
386 m_requests.push_back(req);
389 void requestClear(unsigned long caller, Event *event)
393 req.fetchrequest.caller = caller;
395 m_requests.push_back(req);
401 req.type = RT_WAKEUP;
403 m_requests.push_back(req);
407 // Handle a request from some other thread
408 // E.g. new fetch; clear fetches for one caller; wake up
409 void processRequest(const Request &req)
411 if (req.type == RT_FETCH) {
412 // New fetch, queue until there are less
413 // than m_parallel_limit ongoing fetches
414 m_queued_fetches.push_back(req.fetchrequest);
416 // see processQueued() for what happens next
419 else if (req.type == RT_CLEAR) {
420 unsigned long caller = req.fetchrequest.caller;
422 // Abort all ongoing fetches for the caller
423 for (std::vector<HTTPFetchOngoing*>::iterator
424 it = m_all_ongoing.begin();
425 it != m_all_ongoing.end();) {
426 if ((*it)->request.caller == caller) {
428 it = m_all_ongoing.erase(it);
434 // Also abort all queued fetches for the caller
435 for (std::list<HTTPFetchRequest>::iterator
436 it = m_queued_fetches.begin();
437 it != m_queued_fetches.end();) {
438 if ((*it).caller == caller)
439 it = m_queued_fetches.erase(it);
444 else if (req.type == RT_WAKEUP) {
445 // Wakeup: Nothing to do, thread is awake at this point
448 if (req.event != NULL)
452 // Start new ongoing fetches if m_parallel_limit allows
453 void processQueued(CurlHandlePool *pool)
455 while (m_all_ongoing.size() < m_parallel_limit &&
456 !m_queued_fetches.empty()) {
457 HTTPFetchRequest request = m_queued_fetches.front();
458 m_queued_fetches.pop_front();
460 // Create ongoing fetch data and make a cURL handle
461 // Set cURL options based on HTTPFetchRequest
462 HTTPFetchOngoing *ongoing =
463 new HTTPFetchOngoing(request, pool);
465 // Initiate the connection (curl_multi_add_handle)
466 CURLcode res = ongoing->start(m_multi);
467 if (res == CURLE_OK) {
468 m_all_ongoing.push_back(ongoing);
471 ongoing->complete(res);
472 httpfetch_deliver_result(ongoing->result);
478 // Process CURLMsg (indicates completion of a fetch)
479 void processCurlMessage(CURLMsg *msg)
481 // Determine which ongoing fetch the message pertains to
484 for (i = 0; i < m_all_ongoing.size(); ++i) {
485 if (m_all_ongoing[i]->curl == msg->easy_handle) {
490 if (msg->msg == CURLMSG_DONE && found) {
491 // m_all_ongoing[i] succeeded or failed.
492 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
493 ongoing->complete(msg->data.result);
494 httpfetch_deliver_result(ongoing->result);
496 m_all_ongoing.erase(m_all_ongoing.begin() + i);
500 // Wait for a request from another thread, or timeout elapses
501 void waitForRequest(long timeout)
503 if (m_queued_fetches.empty()) {
505 Request req = m_requests.pop_front(timeout);
508 catch (ItemNotFoundException &e) {}
512 // Wait until some IO happens, or timeout elapses
513 void waitForIO(long timeout)
519 long select_timeout = -1;
520 struct timeval select_tv;
523 FD_ZERO(&read_fd_set);
524 FD_ZERO(&write_fd_set);
525 FD_ZERO(&exc_fd_set);
527 mres = curl_multi_fdset(m_multi, &read_fd_set,
528 &write_fd_set, &exc_fd_set, &max_fd);
529 if (mres != CURLM_OK) {
530 errorstream<<"curl_multi_fdset"
531 <<" returned error code "<<mres
536 mres = curl_multi_timeout(m_multi, &select_timeout);
537 if (mres != CURLM_OK) {
538 errorstream<<"curl_multi_timeout"
539 <<" returned error code "<<mres
544 // Limit timeout so new requests get through
545 if (select_timeout < 0 || select_timeout > timeout)
546 select_timeout = timeout;
548 if (select_timeout > 0) {
549 // in Winsock it is forbidden to pass three empty
550 // fd_sets to select(), so in that case use sleep_ms
552 select_tv.tv_sec = select_timeout / 1000;
553 select_tv.tv_usec = (select_timeout % 1000) * 1000;
554 int retval = select(max_fd + 1, &read_fd_set,
555 &write_fd_set, &exc_fd_set,
559 errorstream<<"select returned error code "
560 <<WSAGetLastError()<<std::endl;
562 errorstream<<"select returned error code "
568 sleep_ms(select_timeout);
576 log_register_thread("CurlFetchThread");
577 DSTACK(__FUNCTION_NAME);
581 m_multi = curl_multi_init();
582 if (m_multi == NULL) {
583 errorstream<<"curl_multi_init returned NULL\n";
587 assert(m_all_ongoing.empty());
589 while (!StopRequested()) {
590 BEGIN_DEBUG_EXCEPTION_HANDLER
593 Handle new async requests
596 while (!m_requests.empty()) {
597 Request req = m_requests.pop_frontNoEx();
600 processQueued(&pool);
603 Handle ongoing async requests
606 int still_ongoing = 0;
607 while (curl_multi_perform(m_multi, &still_ongoing) ==
608 CURLM_CALL_MULTI_PERFORM)
612 Handle completed async requests
614 if (still_ongoing < (int) m_all_ongoing.size()) {
617 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
618 while (msg != NULL) {
619 processCurlMessage(msg);
620 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
625 If there are ongoing requests, wait for data
626 (with a timeout of 100ms so that new requests
629 If no ongoing requests, wait for a new request.
630 (Possibly an empty request that signals
631 that the thread should be stopped.)
633 if (m_all_ongoing.empty())
634 waitForRequest(100000000);
638 END_DEBUG_EXCEPTION_HANDLER(errorstream)
641 // Call curl_multi_remove_handle and cleanup easy handles
642 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
643 delete m_all_ongoing[i];
645 m_all_ongoing.clear();
647 m_queued_fetches.clear();
649 CURLMcode mres = curl_multi_cleanup(m_multi);
650 if (mres != CURLM_OK) {
651 errorstream<<"curl_multi_cleanup"
652 <<" returned error code "<<mres
660 CurlFetchThread *g_httpfetch_thread = NULL;
662 void httpfetch_init(int parallel_limit)
664 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
667 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
668 assert(res == CURLE_OK);
670 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
673 void httpfetch_cleanup()
675 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
677 g_httpfetch_thread->Stop();
678 g_httpfetch_thread->requestWakeUp();
679 g_httpfetch_thread->Wait();
680 delete g_httpfetch_thread;
682 curl_global_cleanup();
685 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
687 g_httpfetch_thread->requestFetch(fetchrequest);
688 if (!g_httpfetch_thread->IsRunning())
689 g_httpfetch_thread->Start();
692 static void httpfetch_request_clear(unsigned long caller)
694 if (g_httpfetch_thread->IsRunning()) {
696 g_httpfetch_thread->requestClear(caller, &event);
700 g_httpfetch_thread->requestClear(caller, NULL);
704 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
705 HTTPFetchResult &fetchresult)
707 // Create ongoing fetch data and make a cURL handle
708 // Set cURL options based on HTTPFetchRequest
710 HTTPFetchOngoing ongoing(fetchrequest, &pool);
711 // Do the fetch (curl_easy_perform)
712 CURLcode res = ongoing.start(NULL);
713 // Update fetchresult
714 ongoing.complete(res);
715 fetchresult = ongoing.result;
723 Dummy httpfetch implementation that always returns an error.
726 void httpfetch_init(int parallel_limit)
730 void httpfetch_cleanup()
734 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
736 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
737 <<" because USE_CURL=0"<<std::endl;
739 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
740 httpfetch_deliver_result(fetchresult);
743 static void httpfetch_request_clear(unsigned long caller)
747 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
748 HTTPFetchResult &fetchresult)
750 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
751 <<" because USE_CURL=0"<<std::endl;
753 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.