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 "httpfetch.h"
21 #include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf()
28 #include "network/socket.h" // for select()
29 #include "threading/event.h"
31 #include "exceptions.h"
34 #include "util/container.h"
35 #include "util/thread.h"
40 std::mutex g_httpfetch_mutex;
41 std::map<unsigned long, std::queue<HTTPFetchResult> > g_httpfetch_results;
42 PcgRandom g_callerid_randomness;
44 HTTPFetchRequest::HTTPFetchRequest() :
45 timeout(g_settings->getS32("curl_timeout")),
46 connect_timeout(timeout),
47 useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")")
52 static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
54 unsigned long caller = fetch_result.caller;
55 if (caller != HTTPFETCH_DISCARD) {
56 MutexAutoLock lock(g_httpfetch_mutex);
57 g_httpfetch_results[caller].push(fetch_result);
61 static void httpfetch_request_clear(unsigned long caller);
63 unsigned long httpfetch_caller_alloc()
65 MutexAutoLock lock(g_httpfetch_mutex);
67 // Check each caller ID except HTTPFETCH_DISCARD
68 const unsigned long discard = HTTPFETCH_DISCARD;
69 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
70 std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
71 it = g_httpfetch_results.find(caller);
72 if (it == g_httpfetch_results.end()) {
73 verbosestream << "httpfetch_caller_alloc: allocating "
74 << caller << std::endl;
75 // Access element to create it
76 g_httpfetch_results[caller];
81 FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
85 unsigned long httpfetch_caller_alloc_secure()
87 MutexAutoLock lock(g_httpfetch_mutex);
89 // Generate random caller IDs and make sure they're not
90 // already used or equal to HTTPFETCH_DISCARD
91 // Give up after 100 tries to prevent infinite loop
96 caller = (((u64) g_callerid_randomness.next()) << 32) |
97 g_callerid_randomness.next();
100 FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs");
101 return HTTPFETCH_DISCARD;
103 } while (g_httpfetch_results.find(caller) != g_httpfetch_results.end());
105 verbosestream << "httpfetch_caller_alloc_secure: allocating "
106 << caller << std::endl;
108 // Access element to create it
109 g_httpfetch_results[caller];
113 void httpfetch_caller_free(unsigned long caller)
115 verbosestream<<"httpfetch_caller_free: freeing "
118 httpfetch_request_clear(caller);
119 if (caller != HTTPFETCH_DISCARD) {
120 MutexAutoLock lock(g_httpfetch_mutex);
121 g_httpfetch_results.erase(caller);
125 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result)
127 MutexAutoLock lock(g_httpfetch_mutex);
129 // Check that caller exists
130 std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
131 it = g_httpfetch_results.find(caller);
132 if (it == g_httpfetch_results.end())
135 // Check that result queue is nonempty
136 std::queue<HTTPFetchResult> &caller_results = it->second;
137 if (caller_results.empty())
141 fetch_result = caller_results.front();
142 caller_results.pop();
147 #include <curl/curl.h>
150 USE_CURL is on: use cURL based httpfetch implementation
153 static size_t httpfetch_writefunction(
154 char *ptr, size_t size, size_t nmemb, void *userdata)
156 std::ostringstream *stream = (std::ostringstream*)userdata;
157 size_t count = size * nmemb;
158 stream->write(ptr, count);
162 static size_t httpfetch_discardfunction(
163 char *ptr, size_t size, size_t nmemb, void *userdata)
170 std::list<CURL*> handles;
173 CurlHandlePool() = default;
177 for (std::list<CURL*>::iterator it = handles.begin();
178 it != handles.end(); ++it) {
179 curl_easy_cleanup(*it);
185 if (handles.empty()) {
186 curl = curl_easy_init();
188 errorstream<<"curl_easy_init returned NULL"<<std::endl;
192 curl = handles.front();
197 void free(CURL *handle)
200 handles.push_back(handle);
204 class HTTPFetchOngoing
207 HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool);
210 CURLcode start(CURLM *multi);
211 const HTTPFetchResult * complete(CURLcode res);
213 const HTTPFetchRequest &getRequest() const { return request; };
214 const CURL *getEasyHandle() const { return curl; };
217 CurlHandlePool *pool;
220 HTTPFetchRequest request;
221 HTTPFetchResult result;
222 std::ostringstream oss;
223 struct curl_slist *http_header;
228 HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
229 CurlHandlePool *pool_):
235 oss(std::ios::binary),
239 curl = pool->alloc();
244 // Set static cURL options
245 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
246 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
247 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
248 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
250 std::string bind_address = g_settings->get("bind_address");
251 if (!bind_address.empty()) {
252 curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
255 #if LIBCURL_VERSION_NUM >= 0x071304
256 // Restrict protocols so that curl vulnerabilities in
257 // other protocols don't affect us.
258 // These settings were introduced in curl 7.19.4.
264 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
265 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
268 // Set cURL options based on HTTPFetchRequest
269 curl_easy_setopt(curl, CURLOPT_URL,
270 request.url.c_str());
271 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
273 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
274 request.connect_timeout);
276 if (!request.useragent.empty())
277 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
279 // Set up a write callback that writes to the
280 // ostringstream ongoing->oss, unless the data
281 // is to be discarded
282 if (request.caller == HTTPFETCH_DISCARD) {
283 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
284 httpfetch_discardfunction);
285 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
287 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
288 httpfetch_writefunction);
289 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
292 // Set POST (or GET) data
293 if (request.post_fields.empty() && request.post_data.empty()) {
294 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
295 } else if (request.multipart) {
296 curl_httppost *last = NULL;
297 for (StringMap::iterator it = request.post_fields.begin();
298 it != request.post_fields.end(); ++it) {
299 curl_formadd(&post, &last,
300 CURLFORM_NAMELENGTH, it->first.size(),
301 CURLFORM_PTRNAME, it->first.c_str(),
302 CURLFORM_CONTENTSLENGTH, it->second.size(),
303 CURLFORM_PTRCONTENTS, it->second.c_str(),
306 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
307 // request.post_fields must now *never* be
308 // modified until CURLOPT_HTTPPOST is cleared
309 } else if (request.post_data.empty()) {
310 curl_easy_setopt(curl, CURLOPT_POST, 1);
312 for (auto &post_field : request.post_fields) {
315 str += urlencode(post_field.first);
317 str += urlencode(post_field.second);
319 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
321 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
324 curl_easy_setopt(curl, CURLOPT_POST, 1);
325 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
326 request.post_data.size());
327 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
328 request.post_data.c_str());
329 // request.post_data must now *never* be
330 // modified until CURLOPT_POSTFIELDS is cleared
332 // Set additional HTTP headers
333 for (const std::string &extra_header : request.extra_headers) {
334 http_header = curl_slist_append(http_header, extra_header.c_str());
336 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
338 if (!g_settings->getBool("curl_verify_cert")) {
339 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
343 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
346 return CURLE_FAILED_INIT;
349 // Easy interface (sync)
350 return curl_easy_perform(curl);
353 // Multi interface (async)
354 CURLMcode mres = curl_multi_add_handle(multi_, curl);
355 if (mres != CURLM_OK) {
356 errorstream << "curl_multi_add_handle"
357 << " returned error code " << mres
359 return CURLE_FAILED_INIT;
361 multi = multi_; // store for curl_multi_remove_handle
365 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
367 result.succeeded = (res == CURLE_OK);
368 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
369 result.data = oss.str();
371 // Get HTTP/FTP response code
372 result.response_code = 0;
373 if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
374 &result.response_code) != CURLE_OK)) {
375 // We failed to get a return code, make sure it is still 0
376 result.response_code = 0;
379 if (res != CURLE_OK) {
380 errorstream << request.url << " not found ("
381 << curl_easy_strerror(res) << ")"
382 << " (response code " << result.response_code << ")"
389 HTTPFetchOngoing::~HTTPFetchOngoing()
392 CURLMcode mres = curl_multi_remove_handle(multi, curl);
393 if (mres != CURLM_OK) {
394 errorstream << "curl_multi_remove_handle"
395 << " returned error code " << mres
400 // Set safe options for the reusable cURL handle
401 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
402 httpfetch_discardfunction);
403 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
404 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
406 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
407 curl_slist_free_all(http_header);
410 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
414 // Store the cURL handle for reuse
419 class CurlFetchThread : public Thread
430 HTTPFetchRequest fetch_request;
435 MutexedQueue<Request> m_requests;
436 size_t m_parallel_limit;
438 // Variables exclusively used within thread
439 std::vector<HTTPFetchOngoing*> m_all_ongoing;
440 std::list<HTTPFetchRequest> m_queued_fetches;
443 CurlFetchThread(int parallel_limit) :
446 if (parallel_limit >= 1)
447 m_parallel_limit = parallel_limit;
449 m_parallel_limit = 1;
452 void requestFetch(const HTTPFetchRequest &fetch_request)
456 req.fetch_request = fetch_request;
458 m_requests.push_back(req);
461 void requestClear(unsigned long caller, Event *event)
465 req.fetch_request.caller = caller;
467 m_requests.push_back(req);
473 req.type = RT_WAKEUP;
475 m_requests.push_back(req);
479 // Handle a request from some other thread
480 // E.g. new fetch; clear fetches for one caller; wake up
481 void processRequest(const Request &req)
483 if (req.type == RT_FETCH) {
484 // New fetch, queue until there are less
485 // than m_parallel_limit ongoing fetches
486 m_queued_fetches.push_back(req.fetch_request);
488 // see processQueued() for what happens next
491 else if (req.type == RT_CLEAR) {
492 unsigned long caller = req.fetch_request.caller;
494 // Abort all ongoing fetches for the caller
495 for (std::vector<HTTPFetchOngoing*>::iterator
496 it = m_all_ongoing.begin();
497 it != m_all_ongoing.end();) {
498 if ((*it)->getRequest().caller == caller) {
500 it = m_all_ongoing.erase(it);
506 // Also abort all queued fetches for the caller
507 for (std::list<HTTPFetchRequest>::iterator
508 it = m_queued_fetches.begin();
509 it != m_queued_fetches.end();) {
510 if ((*it).caller == caller)
511 it = m_queued_fetches.erase(it);
516 else if (req.type == RT_WAKEUP) {
517 // Wakeup: Nothing to do, thread is awake at this point
520 if (req.event != NULL)
524 // Start new ongoing fetches if m_parallel_limit allows
525 void processQueued(CurlHandlePool *pool)
527 while (m_all_ongoing.size() < m_parallel_limit &&
528 !m_queued_fetches.empty()) {
529 HTTPFetchRequest request = m_queued_fetches.front();
530 m_queued_fetches.pop_front();
532 // Create ongoing fetch data and make a cURL handle
533 // Set cURL options based on HTTPFetchRequest
534 HTTPFetchOngoing *ongoing =
535 new HTTPFetchOngoing(request, pool);
537 // Initiate the connection (curl_multi_add_handle)
538 CURLcode res = ongoing->start(m_multi);
539 if (res == CURLE_OK) {
540 m_all_ongoing.push_back(ongoing);
543 httpfetch_deliver_result(*ongoing->complete(res));
549 // Process CURLMsg (indicates completion of a fetch)
550 void processCurlMessage(CURLMsg *msg)
552 // Determine which ongoing fetch the message pertains to
555 for (i = 0; i < m_all_ongoing.size(); ++i) {
556 if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
561 if (msg->msg == CURLMSG_DONE && found) {
562 // m_all_ongoing[i] succeeded or failed.
563 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
564 httpfetch_deliver_result(*ongoing->complete(msg->data.result));
566 m_all_ongoing.erase(m_all_ongoing.begin() + i);
570 // Wait for a request from another thread, or timeout elapses
571 void waitForRequest(long timeout)
573 if (m_queued_fetches.empty()) {
575 Request req = m_requests.pop_front(timeout);
578 catch (ItemNotFoundException &e) {}
582 // Wait until some IO happens, or timeout elapses
583 void waitForIO(long timeout)
589 long select_timeout = -1;
590 struct timeval select_tv;
593 FD_ZERO(&read_fd_set);
594 FD_ZERO(&write_fd_set);
595 FD_ZERO(&exc_fd_set);
597 mres = curl_multi_fdset(m_multi, &read_fd_set,
598 &write_fd_set, &exc_fd_set, &max_fd);
599 if (mres != CURLM_OK) {
600 errorstream<<"curl_multi_fdset"
601 <<" returned error code "<<mres
606 mres = curl_multi_timeout(m_multi, &select_timeout);
607 if (mres != CURLM_OK) {
608 errorstream<<"curl_multi_timeout"
609 <<" returned error code "<<mres
614 // Limit timeout so new requests get through
615 if (select_timeout < 0 || select_timeout > timeout)
616 select_timeout = timeout;
618 if (select_timeout > 0) {
619 // in Winsock it is forbidden to pass three empty
620 // fd_sets to select(), so in that case use sleep_ms
622 select_tv.tv_sec = select_timeout / 1000;
623 select_tv.tv_usec = (select_timeout % 1000) * 1000;
624 int retval = select(max_fd + 1, &read_fd_set,
625 &write_fd_set, &exc_fd_set,
629 errorstream<<"select returned error code "
630 <<WSAGetLastError()<<std::endl;
632 errorstream<<"select returned error code "
638 sleep_ms(select_timeout);
647 m_multi = curl_multi_init();
648 if (m_multi == NULL) {
649 errorstream<<"curl_multi_init returned NULL\n";
653 FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
655 while (!stopRequested()) {
656 BEGIN_DEBUG_EXCEPTION_HANDLER
659 Handle new async requests
662 while (!m_requests.empty()) {
663 Request req = m_requests.pop_frontNoEx();
666 processQueued(&pool);
669 Handle ongoing async requests
672 int still_ongoing = 0;
673 while (curl_multi_perform(m_multi, &still_ongoing) ==
674 CURLM_CALL_MULTI_PERFORM)
678 Handle completed async requests
680 if (still_ongoing < (int) m_all_ongoing.size()) {
683 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
684 while (msg != NULL) {
685 processCurlMessage(msg);
686 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
691 If there are ongoing requests, wait for data
692 (with a timeout of 100ms so that new requests
695 If no ongoing requests, wait for a new request.
696 (Possibly an empty request that signals
697 that the thread should be stopped.)
699 if (m_all_ongoing.empty())
700 waitForRequest(100000000);
704 END_DEBUG_EXCEPTION_HANDLER
707 // Call curl_multi_remove_handle and cleanup easy handles
708 for (HTTPFetchOngoing *i : m_all_ongoing) {
711 m_all_ongoing.clear();
713 m_queued_fetches.clear();
715 CURLMcode mres = curl_multi_cleanup(m_multi);
716 if (mres != CURLM_OK) {
717 errorstream<<"curl_multi_cleanup"
718 <<" returned error code "<<mres
726 CurlFetchThread *g_httpfetch_thread = NULL;
728 void httpfetch_init(int parallel_limit)
730 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
733 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
734 FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
736 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
738 // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
740 porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
741 g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
744 void httpfetch_cleanup()
746 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
748 g_httpfetch_thread->stop();
749 g_httpfetch_thread->requestWakeUp();
750 g_httpfetch_thread->wait();
751 delete g_httpfetch_thread;
753 curl_global_cleanup();
756 void httpfetch_async(const HTTPFetchRequest &fetch_request)
758 g_httpfetch_thread->requestFetch(fetch_request);
759 if (!g_httpfetch_thread->isRunning())
760 g_httpfetch_thread->start();
763 static void httpfetch_request_clear(unsigned long caller)
765 if (g_httpfetch_thread->isRunning()) {
767 g_httpfetch_thread->requestClear(caller, &event);
770 g_httpfetch_thread->requestClear(caller, NULL);
774 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
775 HTTPFetchResult &fetch_result)
777 // Create ongoing fetch data and make a cURL handle
778 // Set cURL options based on HTTPFetchRequest
780 HTTPFetchOngoing ongoing(fetch_request, &pool);
781 // Do the fetch (curl_easy_perform)
782 CURLcode res = ongoing.start(NULL);
783 // Update fetch result
784 fetch_result = *ongoing.complete(res);
792 Dummy httpfetch implementation that always returns an error.
795 void httpfetch_init(int parallel_limit)
799 void httpfetch_cleanup()
803 void httpfetch_async(const HTTPFetchRequest &fetch_request)
805 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
806 << " because USE_CURL=0" << std::endl;
808 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
809 httpfetch_deliver_result(fetch_result);
812 static void httpfetch_request_clear(unsigned long caller)
816 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
817 HTTPFetchResult &fetch_result)
819 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
820 << " because USE_CURL=0" << std::endl;
822 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.