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()
25 #include <unordered_map>
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 static std::mutex g_httpfetch_mutex;
41 static std::unordered_map<unsigned long, std::queue<HTTPFetchResult>>
43 static PcgRandom g_callerid_randomness;
45 HTTPFetchRequest::HTTPFetchRequest() :
46 timeout(g_settings->getS32("curl_timeout")),
47 connect_timeout(10 * 1000),
48 useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")")
53 static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
55 unsigned long caller = fetch_result.caller;
56 if (caller != HTTPFETCH_DISCARD) {
57 MutexAutoLock lock(g_httpfetch_mutex);
58 g_httpfetch_results[caller].emplace(fetch_result);
62 static void httpfetch_request_clear(unsigned long caller);
64 unsigned long httpfetch_caller_alloc()
66 MutexAutoLock lock(g_httpfetch_mutex);
68 // Check each caller ID except HTTPFETCH_DISCARD
69 const unsigned long discard = HTTPFETCH_DISCARD;
70 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
71 auto 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 auto it = g_httpfetch_results.find(caller);
131 if (it == g_httpfetch_results.end())
134 // Check that result queue is nonempty
135 std::queue<HTTPFetchResult> &caller_results = it->second;
136 if (caller_results.empty())
140 fetch_result = std::move(caller_results.front());
141 caller_results.pop();
146 #include <curl/curl.h>
149 USE_CURL is on: use cURL based httpfetch implementation
152 static size_t httpfetch_writefunction(
153 char *ptr, size_t size, size_t nmemb, void *userdata)
155 std::ostringstream *stream = (std::ostringstream*)userdata;
156 size_t count = size * nmemb;
157 stream->write(ptr, count);
161 static size_t httpfetch_discardfunction(
162 char *ptr, size_t size, size_t nmemb, void *userdata)
169 std::list<CURL*> handles;
172 CurlHandlePool() = default;
176 for (std::list<CURL*>::iterator it = handles.begin();
177 it != handles.end(); ++it) {
178 curl_easy_cleanup(*it);
184 if (handles.empty()) {
185 curl = curl_easy_init();
187 errorstream<<"curl_easy_init returned NULL"<<std::endl;
191 curl = handles.front();
196 void free(CURL *handle)
199 handles.push_back(handle);
203 class HTTPFetchOngoing
206 HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool);
209 CURLcode start(CURLM *multi);
210 const HTTPFetchResult * complete(CURLcode res);
212 const HTTPFetchRequest &getRequest() const { return request; };
213 const CURL *getEasyHandle() const { return curl; };
216 CurlHandlePool *pool;
219 HTTPFetchRequest request;
220 HTTPFetchResult result;
221 std::ostringstream oss;
222 struct curl_slist *http_header;
227 HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
228 CurlHandlePool *pool_):
234 oss(std::ios::binary),
238 curl = pool->alloc();
243 // Set static cURL options
244 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
245 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
246 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
247 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3);
248 curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
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 (!g_settings->getBool("enable_ipv6")) {
256 curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
259 #if LIBCURL_VERSION_NUM >= 0x071304
260 // Restrict protocols so that curl vulnerabilities in
261 // other protocols don't affect us.
262 // These settings were introduced in curl 7.19.4.
268 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
269 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
272 // Set cURL options based on HTTPFetchRequest
273 curl_easy_setopt(curl, CURLOPT_URL,
274 request.url.c_str());
275 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
277 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
278 request.connect_timeout);
280 if (!request.useragent.empty())
281 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
283 // Set up a write callback that writes to the
284 // ostringstream ongoing->oss, unless the data
285 // is to be discarded
286 if (request.caller == HTTPFETCH_DISCARD) {
287 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
288 httpfetch_discardfunction);
289 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
291 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
292 httpfetch_writefunction);
293 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
296 // Set data from fields or raw_data
297 if (request.multipart) {
298 curl_httppost *last = NULL;
299 for (StringMap::iterator it = request.fields.begin();
300 it != request.fields.end(); ++it) {
301 curl_formadd(&post, &last,
302 CURLFORM_NAMELENGTH, it->first.size(),
303 CURLFORM_PTRNAME, it->first.c_str(),
304 CURLFORM_CONTENTSLENGTH, it->second.size(),
305 CURLFORM_PTRCONTENTS, it->second.c_str(),
308 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
309 // request.post_fields must now *never* be
310 // modified until CURLOPT_HTTPPOST is cleared
312 switch (request.method) {
314 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
317 curl_easy_setopt(curl, CURLOPT_POST, 1);
320 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
323 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
326 if (request.method != HTTP_GET) {
327 if (!request.raw_data.empty()) {
328 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
329 request.raw_data.size());
330 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
331 request.raw_data.c_str());
332 } else if (!request.fields.empty()) {
334 for (auto &field : request.fields) {
337 str += urlencode(field.first);
339 str += urlencode(field.second);
341 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
343 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
348 // Set additional HTTP headers
349 for (const std::string &extra_header : request.extra_headers) {
350 http_header = curl_slist_append(http_header, extra_header.c_str());
352 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
354 if (!g_settings->getBool("curl_verify_cert")) {
355 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
359 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
362 return CURLE_FAILED_INIT;
365 // Easy interface (sync)
366 return curl_easy_perform(curl);
369 // Multi interface (async)
370 CURLMcode mres = curl_multi_add_handle(multi_, curl);
371 if (mres != CURLM_OK) {
372 errorstream << "curl_multi_add_handle"
373 << " returned error code " << mres
375 return CURLE_FAILED_INIT;
377 multi = multi_; // store for curl_multi_remove_handle
381 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
383 result.succeeded = (res == CURLE_OK);
384 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
385 result.data = oss.str();
387 // Get HTTP/FTP response code
388 result.response_code = 0;
389 if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
390 &result.response_code) != CURLE_OK)) {
391 // We failed to get a return code, make sure it is still 0
392 result.response_code = 0;
395 if (res != CURLE_OK) {
396 errorstream << request.url << " not found ("
397 << curl_easy_strerror(res) << ")"
398 << " (response code " << result.response_code << ")"
405 HTTPFetchOngoing::~HTTPFetchOngoing()
408 CURLMcode mres = curl_multi_remove_handle(multi, curl);
409 if (mres != CURLM_OK) {
410 errorstream << "curl_multi_remove_handle"
411 << " returned error code " << mres
416 // Set safe options for the reusable cURL handle
417 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
418 httpfetch_discardfunction);
419 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
420 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
422 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
423 curl_slist_free_all(http_header);
426 curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
430 // Store the cURL handle for reuse
435 class CurlFetchThread : public Thread
446 HTTPFetchRequest fetch_request;
451 MutexedQueue<Request> m_requests;
452 size_t m_parallel_limit;
454 // Variables exclusively used within thread
455 std::vector<HTTPFetchOngoing*> m_all_ongoing;
456 std::list<HTTPFetchRequest> m_queued_fetches;
459 CurlFetchThread(int parallel_limit) :
462 if (parallel_limit >= 1)
463 m_parallel_limit = parallel_limit;
465 m_parallel_limit = 1;
468 void requestFetch(const HTTPFetchRequest &fetch_request)
472 req.fetch_request = fetch_request;
474 m_requests.push_back(req);
477 void requestClear(unsigned long caller, Event *event)
481 req.fetch_request.caller = caller;
483 m_requests.push_back(req);
489 req.type = RT_WAKEUP;
491 m_requests.push_back(req);
495 // Handle a request from some other thread
496 // E.g. new fetch; clear fetches for one caller; wake up
497 void processRequest(const Request &req)
499 if (req.type == RT_FETCH) {
500 // New fetch, queue until there are less
501 // than m_parallel_limit ongoing fetches
502 m_queued_fetches.push_back(req.fetch_request);
504 // see processQueued() for what happens next
507 else if (req.type == RT_CLEAR) {
508 unsigned long caller = req.fetch_request.caller;
510 // Abort all ongoing fetches for the caller
511 for (std::vector<HTTPFetchOngoing*>::iterator
512 it = m_all_ongoing.begin();
513 it != m_all_ongoing.end();) {
514 if ((*it)->getRequest().caller == caller) {
516 it = m_all_ongoing.erase(it);
522 // Also abort all queued fetches for the caller
523 for (std::list<HTTPFetchRequest>::iterator
524 it = m_queued_fetches.begin();
525 it != m_queued_fetches.end();) {
526 if ((*it).caller == caller)
527 it = m_queued_fetches.erase(it);
532 else if (req.type == RT_WAKEUP) {
533 // Wakeup: Nothing to do, thread is awake at this point
536 if (req.event != NULL)
540 // Start new ongoing fetches if m_parallel_limit allows
541 void processQueued(CurlHandlePool *pool)
543 while (m_all_ongoing.size() < m_parallel_limit &&
544 !m_queued_fetches.empty()) {
545 HTTPFetchRequest request = m_queued_fetches.front();
546 m_queued_fetches.pop_front();
548 // Create ongoing fetch data and make a cURL handle
549 // Set cURL options based on HTTPFetchRequest
550 HTTPFetchOngoing *ongoing =
551 new HTTPFetchOngoing(request, pool);
553 // Initiate the connection (curl_multi_add_handle)
554 CURLcode res = ongoing->start(m_multi);
555 if (res == CURLE_OK) {
556 m_all_ongoing.push_back(ongoing);
559 httpfetch_deliver_result(*ongoing->complete(res));
565 // Process CURLMsg (indicates completion of a fetch)
566 void processCurlMessage(CURLMsg *msg)
568 // Determine which ongoing fetch the message pertains to
571 for (i = 0; i < m_all_ongoing.size(); ++i) {
572 if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
577 if (msg->msg == CURLMSG_DONE && found) {
578 // m_all_ongoing[i] succeeded or failed.
579 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
580 httpfetch_deliver_result(*ongoing->complete(msg->data.result));
582 m_all_ongoing.erase(m_all_ongoing.begin() + i);
586 // Wait for a request from another thread, or timeout elapses
587 void waitForRequest(long timeout)
589 if (m_queued_fetches.empty()) {
591 Request req = m_requests.pop_front(timeout);
594 catch (ItemNotFoundException &e) {}
598 // Wait until some IO happens, or timeout elapses
599 void waitForIO(long timeout)
605 long select_timeout = -1;
606 struct timeval select_tv;
609 FD_ZERO(&read_fd_set);
610 FD_ZERO(&write_fd_set);
611 FD_ZERO(&exc_fd_set);
613 mres = curl_multi_fdset(m_multi, &read_fd_set,
614 &write_fd_set, &exc_fd_set, &max_fd);
615 if (mres != CURLM_OK) {
616 errorstream<<"curl_multi_fdset"
617 <<" returned error code "<<mres
622 mres = curl_multi_timeout(m_multi, &select_timeout);
623 if (mres != CURLM_OK) {
624 errorstream<<"curl_multi_timeout"
625 <<" returned error code "<<mres
630 // Limit timeout so new requests get through
631 if (select_timeout < 0 || select_timeout > timeout)
632 select_timeout = timeout;
634 if (select_timeout > 0) {
635 // in Winsock it is forbidden to pass three empty
636 // fd_sets to select(), so in that case use sleep_ms
638 select_tv.tv_sec = select_timeout / 1000;
639 select_tv.tv_usec = (select_timeout % 1000) * 1000;
640 int retval = select(max_fd + 1, &read_fd_set,
641 &write_fd_set, &exc_fd_set,
645 errorstream<<"select returned error code "
646 <<WSAGetLastError()<<std::endl;
648 errorstream<<"select returned error code "
654 sleep_ms(select_timeout);
663 m_multi = curl_multi_init();
664 if (m_multi == NULL) {
665 errorstream<<"curl_multi_init returned NULL\n";
669 FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
671 while (!stopRequested()) {
672 BEGIN_DEBUG_EXCEPTION_HANDLER
675 Handle new async requests
678 while (!m_requests.empty()) {
679 Request req = m_requests.pop_frontNoEx();
682 processQueued(&pool);
685 Handle ongoing async requests
688 int still_ongoing = 0;
689 while (curl_multi_perform(m_multi, &still_ongoing) ==
690 CURLM_CALL_MULTI_PERFORM)
694 Handle completed async requests
696 if (still_ongoing < (int) m_all_ongoing.size()) {
699 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
700 while (msg != NULL) {
701 processCurlMessage(msg);
702 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
707 If there are ongoing requests, wait for data
708 (with a timeout of 100ms so that new requests
711 If no ongoing requests, wait for a new request.
712 (Possibly an empty request that signals
713 that the thread should be stopped.)
715 if (m_all_ongoing.empty())
716 waitForRequest(100000000);
720 END_DEBUG_EXCEPTION_HANDLER
723 // Call curl_multi_remove_handle and cleanup easy handles
724 for (HTTPFetchOngoing *i : m_all_ongoing) {
727 m_all_ongoing.clear();
729 m_queued_fetches.clear();
731 CURLMcode mres = curl_multi_cleanup(m_multi);
732 if (mres != CURLM_OK) {
733 errorstream<<"curl_multi_cleanup"
734 <<" returned error code "<<mres
742 CurlFetchThread *g_httpfetch_thread = NULL;
744 void httpfetch_init(int parallel_limit)
746 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
749 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
750 FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
752 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
754 // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
756 porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
757 g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
760 void httpfetch_cleanup()
762 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
764 g_httpfetch_thread->stop();
765 g_httpfetch_thread->requestWakeUp();
766 g_httpfetch_thread->wait();
767 delete g_httpfetch_thread;
769 curl_global_cleanup();
772 void httpfetch_async(const HTTPFetchRequest &fetch_request)
774 g_httpfetch_thread->requestFetch(fetch_request);
775 if (!g_httpfetch_thread->isRunning())
776 g_httpfetch_thread->start();
779 static void httpfetch_request_clear(unsigned long caller)
781 if (g_httpfetch_thread->isRunning()) {
783 g_httpfetch_thread->requestClear(caller, &event);
786 g_httpfetch_thread->requestClear(caller, NULL);
790 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
791 HTTPFetchResult &fetch_result)
793 // Create ongoing fetch data and make a cURL handle
794 // Set cURL options based on HTTPFetchRequest
796 HTTPFetchOngoing ongoing(fetch_request, &pool);
797 // Do the fetch (curl_easy_perform)
798 CURLcode res = ongoing.start(NULL);
799 // Update fetch result
800 fetch_result = *ongoing.complete(res);
808 Dummy httpfetch implementation that always returns an error.
811 void httpfetch_init(int parallel_limit)
815 void httpfetch_cleanup()
819 void httpfetch_async(const HTTPFetchRequest &fetch_request)
821 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
822 << " because USE_CURL=0" << std::endl;
824 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
825 httpfetch_deliver_result(fetch_result);
828 static void httpfetch_request_clear(unsigned long caller)
832 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
833 HTTPFetchResult &fetch_result)
835 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
836 << " because USE_CURL=0" << std::endl;
838 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.