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 &fetchresult)
57 unsigned long caller = fetchresult.caller;
58 if (caller != HTTPFETCH_DISCARD) {
59 JMutexAutoLock lock(g_httpfetch_mutex);
60 g_httpfetch_results[caller].push_back(fetchresult);
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 &fetchresult)
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> &callerresults = it->second;
112 if (callerresults.empty())
116 fetchresult = callerresults.front();
117 callerresults.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 struct HTTPFetchOngoing
180 CurlHandlePool *pool;
183 HTTPFetchRequest request;
184 HTTPFetchResult result;
185 std::ostringstream oss;
187 struct curl_slist *httpheader;
190 HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
196 oss(std::ios::binary),
200 curl = pool->alloc();
202 // Set static cURL options
203 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
204 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
205 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
206 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
208 #if LIBCURL_VERSION_NUM >= 0x071304
209 // Restrict protocols so that curl vulnerabilities in
210 // other protocols don't affect us.
211 // These settings were introduced in curl 7.19.4.
217 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
218 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
221 // Set cURL options based on HTTPFetchRequest
222 curl_easy_setopt(curl, CURLOPT_URL,
223 request.url.c_str());
224 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
226 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
227 request.connect_timeout);
229 if (request.useragent != "")
230 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
232 // Set up a write callback that writes to the
233 // ostringstream ongoing->oss, unless the data
234 // is to be discarded
235 if (request.caller == HTTPFETCH_DISCARD) {
236 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
237 httpfetch_discardfunction);
238 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
241 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
242 httpfetch_writefunction);
243 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
246 // Set POST (or GET) data
247 if (request.post_fields.empty()) {
248 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
249 } else if (request.multipart) {
250 curl_httppost *last = NULL;
251 for (std::map<std::string, std::string>::iterator it =
252 request.post_fields.begin();
253 it != request.post_fields.end();
255 curl_formadd(&post, &last,
256 CURLFORM_NAMELENGTH, it->first.size(),
257 CURLFORM_PTRNAME, it->first.c_str(),
258 CURLFORM_CONTENTSLENGTH, it->second.size(),
259 CURLFORM_PTRCONTENTS, it->second.c_str(),
262 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
263 // request.post_fields must now *never* be
264 // modified until CURLOPT_HTTPPOST is cleared
266 curl_easy_setopt(curl, CURLOPT_POST, 1);
267 if (request.post_data.empty()) {
269 for (std::map<std::string, std::string>::iterator it =
270 request.post_fields.begin();
271 it != request.post_fields.end();
275 str += urlencode(it->first);
277 str += urlencode(it->second);
279 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
281 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
284 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
285 request.post_data.size());
286 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
287 request.post_data.c_str());
288 // request.post_data must now *never* be
289 // modified until CURLOPT_POSTFIELDS is cleared
292 // Set additional HTTP headers
293 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
294 httpheader = curl_slist_append(
296 request.extra_headers[i].c_str());
298 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
300 if (!g_settings->getBool("curl_verify_cert")) {
301 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
306 CURLcode start(CURLM *multi_)
309 return CURLE_FAILED_INIT;
312 // Multi interface (async)
313 CURLMcode mres = curl_multi_add_handle(multi_, curl);
314 if (mres != CURLM_OK) {
315 errorstream<<"curl_multi_add_handle"
316 <<" returned error code "<<mres
318 return CURLE_FAILED_INIT;
320 multi = multi_; // store for curl_multi_remove_handle
324 // Easy interface (sync)
325 return curl_easy_perform(curl);
329 void complete(CURLcode res)
331 result.succeeded = (res == CURLE_OK);
332 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
333 result.data = oss.str();
335 // Get HTTP/FTP response code
336 result.response_code = 0;
338 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
339 &result.response_code) != CURLE_OK) {
340 //we failed to get a return code make sure it is still 0
341 result.response_code = 0;
345 if (res != CURLE_OK) {
346 errorstream<<request.url<<" not found ("
347 <<curl_easy_strerror(res)<<")"
348 <<" (response code "<<result.response_code<<")"
356 CURLMcode mres = curl_multi_remove_handle(multi, curl);
357 if (mres != CURLM_OK) {
358 errorstream<<"curl_multi_remove_handle"
359 <<" returned error code "<<mres
364 // Set safe options for the reusable cURL handle
365 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
366 httpfetch_discardfunction);
367 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
368 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
369 if (httpheader != NULL) {
370 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
371 curl_slist_free_all(httpheader);
374 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
378 // Store the cURL handle for reuse
383 class CurlFetchThread : public JThread
394 HTTPFetchRequest fetchrequest;
399 MutexedQueue<Request> m_requests;
400 size_t m_parallel_limit;
402 // Variables exclusively used within thread
403 std::vector<HTTPFetchOngoing*> m_all_ongoing;
404 std::list<HTTPFetchRequest> m_queued_fetches;
407 CurlFetchThread(int parallel_limit)
409 if (parallel_limit >= 1)
410 m_parallel_limit = parallel_limit;
412 m_parallel_limit = 1;
415 void requestFetch(const HTTPFetchRequest &fetchrequest)
419 req.fetchrequest = fetchrequest;
421 m_requests.push_back(req);
424 void requestClear(unsigned long caller, Event *event)
428 req.fetchrequest.caller = caller;
430 m_requests.push_back(req);
436 req.type = RT_WAKEUP;
438 m_requests.push_back(req);
442 // Handle a request from some other thread
443 // E.g. new fetch; clear fetches for one caller; wake up
444 void processRequest(const Request &req)
446 if (req.type == RT_FETCH) {
447 // New fetch, queue until there are less
448 // than m_parallel_limit ongoing fetches
449 m_queued_fetches.push_back(req.fetchrequest);
451 // see processQueued() for what happens next
454 else if (req.type == RT_CLEAR) {
455 unsigned long caller = req.fetchrequest.caller;
457 // Abort all ongoing fetches for the caller
458 for (std::vector<HTTPFetchOngoing*>::iterator
459 it = m_all_ongoing.begin();
460 it != m_all_ongoing.end();) {
461 if ((*it)->request.caller == caller) {
463 it = m_all_ongoing.erase(it);
469 // Also abort all queued fetches for the caller
470 for (std::list<HTTPFetchRequest>::iterator
471 it = m_queued_fetches.begin();
472 it != m_queued_fetches.end();) {
473 if ((*it).caller == caller)
474 it = m_queued_fetches.erase(it);
479 else if (req.type == RT_WAKEUP) {
480 // Wakeup: Nothing to do, thread is awake at this point
483 if (req.event != NULL)
487 // Start new ongoing fetches if m_parallel_limit allows
488 void processQueued(CurlHandlePool *pool)
490 while (m_all_ongoing.size() < m_parallel_limit &&
491 !m_queued_fetches.empty()) {
492 HTTPFetchRequest request = m_queued_fetches.front();
493 m_queued_fetches.pop_front();
495 // Create ongoing fetch data and make a cURL handle
496 // Set cURL options based on HTTPFetchRequest
497 HTTPFetchOngoing *ongoing =
498 new HTTPFetchOngoing(request, pool);
500 // Initiate the connection (curl_multi_add_handle)
501 CURLcode res = ongoing->start(m_multi);
502 if (res == CURLE_OK) {
503 m_all_ongoing.push_back(ongoing);
506 ongoing->complete(res);
507 httpfetch_deliver_result(ongoing->result);
513 // Process CURLMsg (indicates completion of a fetch)
514 void processCurlMessage(CURLMsg *msg)
516 // Determine which ongoing fetch the message pertains to
519 for (i = 0; i < m_all_ongoing.size(); ++i) {
520 if (m_all_ongoing[i]->curl == msg->easy_handle) {
525 if (msg->msg == CURLMSG_DONE && found) {
526 // m_all_ongoing[i] succeeded or failed.
527 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
528 ongoing->complete(msg->data.result);
529 httpfetch_deliver_result(ongoing->result);
531 m_all_ongoing.erase(m_all_ongoing.begin() + i);
535 // Wait for a request from another thread, or timeout elapses
536 void waitForRequest(long timeout)
538 if (m_queued_fetches.empty()) {
540 Request req = m_requests.pop_front(timeout);
543 catch (ItemNotFoundException &e) {}
547 // Wait until some IO happens, or timeout elapses
548 void waitForIO(long timeout)
554 long select_timeout = -1;
555 struct timeval select_tv;
558 FD_ZERO(&read_fd_set);
559 FD_ZERO(&write_fd_set);
560 FD_ZERO(&exc_fd_set);
562 mres = curl_multi_fdset(m_multi, &read_fd_set,
563 &write_fd_set, &exc_fd_set, &max_fd);
564 if (mres != CURLM_OK) {
565 errorstream<<"curl_multi_fdset"
566 <<" returned error code "<<mres
571 mres = curl_multi_timeout(m_multi, &select_timeout);
572 if (mres != CURLM_OK) {
573 errorstream<<"curl_multi_timeout"
574 <<" returned error code "<<mres
579 // Limit timeout so new requests get through
580 if (select_timeout < 0 || select_timeout > timeout)
581 select_timeout = timeout;
583 if (select_timeout > 0) {
584 // in Winsock it is forbidden to pass three empty
585 // fd_sets to select(), so in that case use sleep_ms
587 select_tv.tv_sec = select_timeout / 1000;
588 select_tv.tv_usec = (select_timeout % 1000) * 1000;
589 int retval = select(max_fd + 1, &read_fd_set,
590 &write_fd_set, &exc_fd_set,
594 errorstream<<"select returned error code "
595 <<WSAGetLastError()<<std::endl;
597 errorstream<<"select returned error code "
603 sleep_ms(select_timeout);
611 log_register_thread("CurlFetchThread");
612 DSTACK(__FUNCTION_NAME);
614 porting::setThreadName("CurlFetchThread");
618 m_multi = curl_multi_init();
619 if (m_multi == NULL) {
620 errorstream<<"curl_multi_init returned NULL\n";
624 assert(m_all_ongoing.empty());
626 while (!StopRequested()) {
627 BEGIN_DEBUG_EXCEPTION_HANDLER
630 Handle new async requests
633 while (!m_requests.empty()) {
634 Request req = m_requests.pop_frontNoEx();
637 processQueued(&pool);
640 Handle ongoing async requests
643 int still_ongoing = 0;
644 while (curl_multi_perform(m_multi, &still_ongoing) ==
645 CURLM_CALL_MULTI_PERFORM)
649 Handle completed async requests
651 if (still_ongoing < (int) m_all_ongoing.size()) {
654 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
655 while (msg != NULL) {
656 processCurlMessage(msg);
657 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
662 If there are ongoing requests, wait for data
663 (with a timeout of 100ms so that new requests
666 If no ongoing requests, wait for a new request.
667 (Possibly an empty request that signals
668 that the thread should be stopped.)
670 if (m_all_ongoing.empty())
671 waitForRequest(100000000);
675 END_DEBUG_EXCEPTION_HANDLER(errorstream)
678 // Call curl_multi_remove_handle and cleanup easy handles
679 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
680 delete m_all_ongoing[i];
682 m_all_ongoing.clear();
684 m_queued_fetches.clear();
686 CURLMcode mres = curl_multi_cleanup(m_multi);
687 if (mres != CURLM_OK) {
688 errorstream<<"curl_multi_cleanup"
689 <<" returned error code "<<mres
697 CurlFetchThread *g_httpfetch_thread = NULL;
699 void httpfetch_init(int parallel_limit)
701 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
704 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
705 assert(res == CURLE_OK);
707 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
710 void httpfetch_cleanup()
712 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
714 g_httpfetch_thread->Stop();
715 g_httpfetch_thread->requestWakeUp();
716 g_httpfetch_thread->Wait();
717 delete g_httpfetch_thread;
719 curl_global_cleanup();
722 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
724 g_httpfetch_thread->requestFetch(fetchrequest);
725 if (!g_httpfetch_thread->IsRunning())
726 g_httpfetch_thread->Start();
729 static void httpfetch_request_clear(unsigned long caller)
731 if (g_httpfetch_thread->IsRunning()) {
733 g_httpfetch_thread->requestClear(caller, &event);
737 g_httpfetch_thread->requestClear(caller, NULL);
741 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
742 HTTPFetchResult &fetchresult)
744 // Create ongoing fetch data and make a cURL handle
745 // Set cURL options based on HTTPFetchRequest
747 HTTPFetchOngoing ongoing(fetchrequest, &pool);
748 // Do the fetch (curl_easy_perform)
749 CURLcode res = ongoing.start(NULL);
750 // Update fetchresult
751 ongoing.complete(res);
752 fetchresult = ongoing.result;
760 Dummy httpfetch implementation that always returns an error.
763 void httpfetch_init(int parallel_limit)
767 void httpfetch_cleanup()
771 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
773 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
774 <<" because USE_CURL=0"<<std::endl;
776 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
777 httpfetch_deliver_result(fetchresult);
780 static void httpfetch_request_clear(unsigned long caller)
784 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
785 HTTPFetchResult &fetchresult)
787 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
788 <<" because USE_CURL=0"<<std::endl;
790 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.