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, 3);
249 curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
251 std::string bind_address = g_settings->get("bind_address");
252 if (!bind_address.empty()) {
253 curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
256 if (!g_settings->getBool("enable_ipv6")) {
257 curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
260 #if LIBCURL_VERSION_NUM >= 0x071304
261 // Restrict protocols so that curl vulnerabilities in
262 // other protocols don't affect us.
263 // These settings were introduced in curl 7.19.4.
269 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
270 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
273 // Set cURL options based on HTTPFetchRequest
274 curl_easy_setopt(curl, CURLOPT_URL,
275 request.url.c_str());
276 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
278 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
279 request.connect_timeout);
281 if (!request.useragent.empty())
282 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
284 // Set up a write callback that writes to the
285 // ostringstream ongoing->oss, unless the data
286 // is to be discarded
287 if (request.caller == HTTPFETCH_DISCARD) {
288 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
289 httpfetch_discardfunction);
290 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
292 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
293 httpfetch_writefunction);
294 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
297 // Set POST (or GET) data
298 if (request.post_fields.empty() && request.post_data.empty()) {
299 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
300 } else if (request.multipart) {
301 curl_httppost *last = NULL;
302 for (StringMap::iterator it = request.post_fields.begin();
303 it != request.post_fields.end(); ++it) {
304 curl_formadd(&post, &last,
305 CURLFORM_NAMELENGTH, it->first.size(),
306 CURLFORM_PTRNAME, it->first.c_str(),
307 CURLFORM_CONTENTSLENGTH, it->second.size(),
308 CURLFORM_PTRCONTENTS, it->second.c_str(),
311 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
312 // request.post_fields must now *never* be
313 // modified until CURLOPT_HTTPPOST is cleared
314 } else if (request.post_data.empty()) {
315 curl_easy_setopt(curl, CURLOPT_POST, 1);
317 for (auto &post_field : request.post_fields) {
320 str += urlencode(post_field.first);
322 str += urlencode(post_field.second);
324 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
326 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
329 curl_easy_setopt(curl, CURLOPT_POST, 1);
330 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
331 request.post_data.size());
332 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
333 request.post_data.c_str());
334 // request.post_data must now *never* be
335 // modified until CURLOPT_POSTFIELDS is cleared
337 // Set additional HTTP headers
338 for (const std::string &extra_header : request.extra_headers) {
339 http_header = curl_slist_append(http_header, extra_header.c_str());
341 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
343 if (!g_settings->getBool("curl_verify_cert")) {
344 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
348 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
351 return CURLE_FAILED_INIT;
354 // Easy interface (sync)
355 return curl_easy_perform(curl);
358 // Multi interface (async)
359 CURLMcode mres = curl_multi_add_handle(multi_, curl);
360 if (mres != CURLM_OK) {
361 errorstream << "curl_multi_add_handle"
362 << " returned error code " << mres
364 return CURLE_FAILED_INIT;
366 multi = multi_; // store for curl_multi_remove_handle
370 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
372 result.succeeded = (res == CURLE_OK);
373 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
374 result.data = oss.str();
376 // Get HTTP/FTP response code
377 result.response_code = 0;
378 if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
379 &result.response_code) != CURLE_OK)) {
380 // We failed to get a return code, make sure it is still 0
381 result.response_code = 0;
384 if (res != CURLE_OK) {
385 errorstream << request.url << " not found ("
386 << curl_easy_strerror(res) << ")"
387 << " (response code " << result.response_code << ")"
394 HTTPFetchOngoing::~HTTPFetchOngoing()
397 CURLMcode mres = curl_multi_remove_handle(multi, curl);
398 if (mres != CURLM_OK) {
399 errorstream << "curl_multi_remove_handle"
400 << " returned error code " << mres
405 // Set safe options for the reusable cURL handle
406 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
407 httpfetch_discardfunction);
408 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
409 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
411 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
412 curl_slist_free_all(http_header);
415 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
419 // Store the cURL handle for reuse
424 class CurlFetchThread : public Thread
435 HTTPFetchRequest fetch_request;
440 MutexedQueue<Request> m_requests;
441 size_t m_parallel_limit;
443 // Variables exclusively used within thread
444 std::vector<HTTPFetchOngoing*> m_all_ongoing;
445 std::list<HTTPFetchRequest> m_queued_fetches;
448 CurlFetchThread(int parallel_limit) :
451 if (parallel_limit >= 1)
452 m_parallel_limit = parallel_limit;
454 m_parallel_limit = 1;
457 void requestFetch(const HTTPFetchRequest &fetch_request)
461 req.fetch_request = fetch_request;
463 m_requests.push_back(req);
466 void requestClear(unsigned long caller, Event *event)
470 req.fetch_request.caller = caller;
472 m_requests.push_back(req);
478 req.type = RT_WAKEUP;
480 m_requests.push_back(req);
484 // Handle a request from some other thread
485 // E.g. new fetch; clear fetches for one caller; wake up
486 void processRequest(const Request &req)
488 if (req.type == RT_FETCH) {
489 // New fetch, queue until there are less
490 // than m_parallel_limit ongoing fetches
491 m_queued_fetches.push_back(req.fetch_request);
493 // see processQueued() for what happens next
496 else if (req.type == RT_CLEAR) {
497 unsigned long caller = req.fetch_request.caller;
499 // Abort all ongoing fetches for the caller
500 for (std::vector<HTTPFetchOngoing*>::iterator
501 it = m_all_ongoing.begin();
502 it != m_all_ongoing.end();) {
503 if ((*it)->getRequest().caller == caller) {
505 it = m_all_ongoing.erase(it);
511 // Also abort all queued fetches for the caller
512 for (std::list<HTTPFetchRequest>::iterator
513 it = m_queued_fetches.begin();
514 it != m_queued_fetches.end();) {
515 if ((*it).caller == caller)
516 it = m_queued_fetches.erase(it);
521 else if (req.type == RT_WAKEUP) {
522 // Wakeup: Nothing to do, thread is awake at this point
525 if (req.event != NULL)
529 // Start new ongoing fetches if m_parallel_limit allows
530 void processQueued(CurlHandlePool *pool)
532 while (m_all_ongoing.size() < m_parallel_limit &&
533 !m_queued_fetches.empty()) {
534 HTTPFetchRequest request = m_queued_fetches.front();
535 m_queued_fetches.pop_front();
537 // Create ongoing fetch data and make a cURL handle
538 // Set cURL options based on HTTPFetchRequest
539 HTTPFetchOngoing *ongoing =
540 new HTTPFetchOngoing(request, pool);
542 // Initiate the connection (curl_multi_add_handle)
543 CURLcode res = ongoing->start(m_multi);
544 if (res == CURLE_OK) {
545 m_all_ongoing.push_back(ongoing);
548 httpfetch_deliver_result(*ongoing->complete(res));
554 // Process CURLMsg (indicates completion of a fetch)
555 void processCurlMessage(CURLMsg *msg)
557 // Determine which ongoing fetch the message pertains to
560 for (i = 0; i < m_all_ongoing.size(); ++i) {
561 if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
566 if (msg->msg == CURLMSG_DONE && found) {
567 // m_all_ongoing[i] succeeded or failed.
568 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
569 httpfetch_deliver_result(*ongoing->complete(msg->data.result));
571 m_all_ongoing.erase(m_all_ongoing.begin() + i);
575 // Wait for a request from another thread, or timeout elapses
576 void waitForRequest(long timeout)
578 if (m_queued_fetches.empty()) {
580 Request req = m_requests.pop_front(timeout);
583 catch (ItemNotFoundException &e) {}
587 // Wait until some IO happens, or timeout elapses
588 void waitForIO(long timeout)
594 long select_timeout = -1;
595 struct timeval select_tv;
598 FD_ZERO(&read_fd_set);
599 FD_ZERO(&write_fd_set);
600 FD_ZERO(&exc_fd_set);
602 mres = curl_multi_fdset(m_multi, &read_fd_set,
603 &write_fd_set, &exc_fd_set, &max_fd);
604 if (mres != CURLM_OK) {
605 errorstream<<"curl_multi_fdset"
606 <<" returned error code "<<mres
611 mres = curl_multi_timeout(m_multi, &select_timeout);
612 if (mres != CURLM_OK) {
613 errorstream<<"curl_multi_timeout"
614 <<" returned error code "<<mres
619 // Limit timeout so new requests get through
620 if (select_timeout < 0 || select_timeout > timeout)
621 select_timeout = timeout;
623 if (select_timeout > 0) {
624 // in Winsock it is forbidden to pass three empty
625 // fd_sets to select(), so in that case use sleep_ms
627 select_tv.tv_sec = select_timeout / 1000;
628 select_tv.tv_usec = (select_timeout % 1000) * 1000;
629 int retval = select(max_fd + 1, &read_fd_set,
630 &write_fd_set, &exc_fd_set,
634 errorstream<<"select returned error code "
635 <<WSAGetLastError()<<std::endl;
637 errorstream<<"select returned error code "
643 sleep_ms(select_timeout);
652 m_multi = curl_multi_init();
653 if (m_multi == NULL) {
654 errorstream<<"curl_multi_init returned NULL\n";
658 FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
660 while (!stopRequested()) {
661 BEGIN_DEBUG_EXCEPTION_HANDLER
664 Handle new async requests
667 while (!m_requests.empty()) {
668 Request req = m_requests.pop_frontNoEx();
671 processQueued(&pool);
674 Handle ongoing async requests
677 int still_ongoing = 0;
678 while (curl_multi_perform(m_multi, &still_ongoing) ==
679 CURLM_CALL_MULTI_PERFORM)
683 Handle completed async requests
685 if (still_ongoing < (int) m_all_ongoing.size()) {
688 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
689 while (msg != NULL) {
690 processCurlMessage(msg);
691 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
696 If there are ongoing requests, wait for data
697 (with a timeout of 100ms so that new requests
700 If no ongoing requests, wait for a new request.
701 (Possibly an empty request that signals
702 that the thread should be stopped.)
704 if (m_all_ongoing.empty())
705 waitForRequest(100000000);
709 END_DEBUG_EXCEPTION_HANDLER
712 // Call curl_multi_remove_handle and cleanup easy handles
713 for (HTTPFetchOngoing *i : m_all_ongoing) {
716 m_all_ongoing.clear();
718 m_queued_fetches.clear();
720 CURLMcode mres = curl_multi_cleanup(m_multi);
721 if (mres != CURLM_OK) {
722 errorstream<<"curl_multi_cleanup"
723 <<" returned error code "<<mres
731 CurlFetchThread *g_httpfetch_thread = NULL;
733 void httpfetch_init(int parallel_limit)
735 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
738 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
739 FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
741 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
743 // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
745 porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
746 g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
749 void httpfetch_cleanup()
751 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
753 g_httpfetch_thread->stop();
754 g_httpfetch_thread->requestWakeUp();
755 g_httpfetch_thread->wait();
756 delete g_httpfetch_thread;
758 curl_global_cleanup();
761 void httpfetch_async(const HTTPFetchRequest &fetch_request)
763 g_httpfetch_thread->requestFetch(fetch_request);
764 if (!g_httpfetch_thread->isRunning())
765 g_httpfetch_thread->start();
768 static void httpfetch_request_clear(unsigned long caller)
770 if (g_httpfetch_thread->isRunning()) {
772 g_httpfetch_thread->requestClear(caller, &event);
775 g_httpfetch_thread->requestClear(caller, NULL);
779 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
780 HTTPFetchResult &fetch_result)
782 // Create ongoing fetch data and make a cURL handle
783 // Set cURL options based on HTTPFetchRequest
785 HTTPFetchOngoing ongoing(fetch_request, &pool);
786 // Do the fetch (curl_easy_perform)
787 CURLcode res = ongoing.start(NULL);
788 // Update fetch result
789 fetch_result = *ongoing.complete(res);
797 Dummy httpfetch implementation that always returns an error.
800 void httpfetch_init(int parallel_limit)
804 void httpfetch_cleanup()
808 void httpfetch_async(const HTTPFetchRequest &fetch_request)
810 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
811 << " because USE_CURL=0" << std::endl;
813 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
814 httpfetch_deliver_result(fetch_result);
817 static void httpfetch_request_clear(unsigned long caller)
821 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
822 HTTPFetchResult &fetch_result)
824 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
825 << " because USE_CURL=0" << std::endl;
827 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.