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(), secure_rand_fill_buf()
22 #include "httpfetch.h"
28 #include "threading/event.h"
30 #include "exceptions.h"
33 #include "util/container.h"
34 #include "util/thread.h"
39 Mutex g_httpfetch_mutex;
40 std::map<unsigned long, std::queue<HTTPFetchResult> > g_httpfetch_results;
41 PcgRandom g_callerid_randomness;
43 HTTPFetchRequest::HTTPFetchRequest()
46 caller = HTTPFETCH_DISCARD;
48 timeout = g_settings->getS32("curl_timeout");
49 connect_timeout = timeout;
52 useragent = std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")";
56 static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
58 unsigned long caller = fetch_result.caller;
59 if (caller != HTTPFETCH_DISCARD) {
60 MutexAutoLock lock(g_httpfetch_mutex);
61 g_httpfetch_results[caller].push(fetch_result);
65 static void httpfetch_request_clear(unsigned long caller);
67 unsigned long httpfetch_caller_alloc()
69 MutexAutoLock lock(g_httpfetch_mutex);
71 // Check each caller ID except HTTPFETCH_DISCARD
72 const unsigned long discard = HTTPFETCH_DISCARD;
73 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
74 std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
75 it = g_httpfetch_results.find(caller);
76 if (it == g_httpfetch_results.end()) {
77 verbosestream << "httpfetch_caller_alloc: allocating "
78 << caller << std::endl;
79 // Access element to create it
80 g_httpfetch_results[caller];
85 FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
89 unsigned long httpfetch_caller_alloc_secure()
91 MutexAutoLock lock(g_httpfetch_mutex);
93 // Generate random caller IDs and make sure they're not
94 // already used or equal to HTTPFETCH_DISCARD
95 // Give up after 100 tries to prevent infinite loop
100 caller = (((u64) g_callerid_randomness.next()) << 32) |
101 g_callerid_randomness.next();
104 FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs");
105 return HTTPFETCH_DISCARD;
107 } while (g_httpfetch_results.find(caller) != g_httpfetch_results.end());
109 verbosestream << "httpfetch_caller_alloc_secure: allocating "
110 << caller << std::endl;
112 // Access element to create it
113 g_httpfetch_results[caller];
117 void httpfetch_caller_free(unsigned long caller)
119 verbosestream<<"httpfetch_caller_free: freeing "
122 httpfetch_request_clear(caller);
123 if (caller != HTTPFETCH_DISCARD) {
124 MutexAutoLock lock(g_httpfetch_mutex);
125 g_httpfetch_results.erase(caller);
129 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result)
131 MutexAutoLock lock(g_httpfetch_mutex);
133 // Check that caller exists
134 std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
135 it = g_httpfetch_results.find(caller);
136 if (it == g_httpfetch_results.end())
139 // Check that result queue is nonempty
140 std::queue<HTTPFetchResult> &caller_results = it->second;
141 if (caller_results.empty())
145 fetch_result = caller_results.front();
146 caller_results.pop();
151 #include <curl/curl.h>
154 USE_CURL is on: use cURL based httpfetch implementation
157 static size_t httpfetch_writefunction(
158 char *ptr, size_t size, size_t nmemb, void *userdata)
160 std::ostringstream *stream = (std::ostringstream*)userdata;
161 size_t count = size * nmemb;
162 stream->write(ptr, count);
166 static size_t httpfetch_discardfunction(
167 char *ptr, size_t size, size_t nmemb, void *userdata)
174 std::list<CURL*> handles;
180 for (std::list<CURL*>::iterator it = handles.begin();
181 it != handles.end(); ++it) {
182 curl_easy_cleanup(*it);
188 if (handles.empty()) {
189 curl = curl_easy_init();
191 errorstream<<"curl_easy_init returned NULL"<<std::endl;
195 curl = handles.front();
200 void free(CURL *handle)
203 handles.push_back(handle);
207 class HTTPFetchOngoing
210 HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool);
213 CURLcode start(CURLM *multi);
214 const HTTPFetchResult * complete(CURLcode res);
216 const HTTPFetchRequest &getRequest() const { return request; };
217 const CURL *getEasyHandle() const { return curl; };
220 CurlHandlePool *pool;
223 HTTPFetchRequest request;
224 HTTPFetchResult result;
225 std::ostringstream oss;
226 struct curl_slist *http_header;
231 HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
232 CurlHandlePool *pool_):
238 oss(std::ios::binary),
242 curl = pool->alloc();
247 // Set static cURL options
248 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
249 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
250 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
251 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
253 std::string bind_address = g_settings->get("bind_address");
254 if (!bind_address.empty()) {
255 curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
258 #if LIBCURL_VERSION_NUM >= 0x071304
259 // Restrict protocols so that curl vulnerabilities in
260 // other protocols don't affect us.
261 // These settings were introduced in curl 7.19.4.
267 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
268 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
271 // Set cURL options based on HTTPFetchRequest
272 curl_easy_setopt(curl, CURLOPT_URL,
273 request.url.c_str());
274 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
276 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
277 request.connect_timeout);
279 if (request.useragent != "")
280 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
282 // Set up a write callback that writes to the
283 // ostringstream ongoing->oss, unless the data
284 // is to be discarded
285 if (request.caller == HTTPFETCH_DISCARD) {
286 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
287 httpfetch_discardfunction);
288 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
290 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
291 httpfetch_writefunction);
292 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
295 // Set POST (or GET) data
296 if (request.post_fields.empty() && request.post_data.empty()) {
297 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
298 } else if (request.multipart) {
299 curl_httppost *last = NULL;
300 for (StringMap::iterator it = request.post_fields.begin();
301 it != request.post_fields.end(); ++it) {
302 curl_formadd(&post, &last,
303 CURLFORM_NAMELENGTH, it->first.size(),
304 CURLFORM_PTRNAME, it->first.c_str(),
305 CURLFORM_CONTENTSLENGTH, it->second.size(),
306 CURLFORM_PTRCONTENTS, it->second.c_str(),
309 curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
310 // request.post_fields must now *never* be
311 // modified until CURLOPT_HTTPPOST is cleared
312 } else if (request.post_data.empty()) {
313 curl_easy_setopt(curl, CURLOPT_POST, 1);
315 for (StringMap::iterator it = request.post_fields.begin();
316 it != request.post_fields.end(); ++it) {
319 str += urlencode(it->first);
321 str += urlencode(it->second);
323 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
325 curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
328 curl_easy_setopt(curl, CURLOPT_POST, 1);
329 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
330 request.post_data.size());
331 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
332 request.post_data.c_str());
333 // request.post_data must now *never* be
334 // modified until CURLOPT_POSTFIELDS is cleared
336 // Set additional HTTP headers
337 for (std::vector<std::string>::iterator it = request.extra_headers.begin();
338 it != request.extra_headers.end(); ++it) {
339 http_header = curl_slist_append(http_header, it->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);
650 DSTACK(FUNCTION_NAME);
654 m_multi = curl_multi_init();
655 if (m_multi == NULL) {
656 errorstream<<"curl_multi_init returned NULL\n";
660 FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
662 while (!stopRequested()) {
663 BEGIN_DEBUG_EXCEPTION_HANDLER
666 Handle new async requests
669 while (!m_requests.empty()) {
670 Request req = m_requests.pop_frontNoEx();
673 processQueued(&pool);
676 Handle ongoing async requests
679 int still_ongoing = 0;
680 while (curl_multi_perform(m_multi, &still_ongoing) ==
681 CURLM_CALL_MULTI_PERFORM)
685 Handle completed async requests
687 if (still_ongoing < (int) m_all_ongoing.size()) {
690 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
691 while (msg != NULL) {
692 processCurlMessage(msg);
693 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
698 If there are ongoing requests, wait for data
699 (with a timeout of 100ms so that new requests
702 If no ongoing requests, wait for a new request.
703 (Possibly an empty request that signals
704 that the thread should be stopped.)
706 if (m_all_ongoing.empty())
707 waitForRequest(100000000);
711 END_DEBUG_EXCEPTION_HANDLER
714 // Call curl_multi_remove_handle and cleanup easy handles
715 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
716 delete m_all_ongoing[i];
718 m_all_ongoing.clear();
720 m_queued_fetches.clear();
722 CURLMcode mres = curl_multi_cleanup(m_multi);
723 if (mres != CURLM_OK) {
724 errorstream<<"curl_multi_cleanup"
725 <<" returned error code "<<mres
733 CurlFetchThread *g_httpfetch_thread = NULL;
735 void httpfetch_init(int parallel_limit)
737 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
740 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
741 FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
743 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
745 // Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
747 porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
748 g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
751 void httpfetch_cleanup()
753 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
755 g_httpfetch_thread->stop();
756 g_httpfetch_thread->requestWakeUp();
757 g_httpfetch_thread->wait();
758 delete g_httpfetch_thread;
760 curl_global_cleanup();
763 void httpfetch_async(const HTTPFetchRequest &fetch_request)
765 g_httpfetch_thread->requestFetch(fetch_request);
766 if (!g_httpfetch_thread->isRunning())
767 g_httpfetch_thread->start();
770 static void httpfetch_request_clear(unsigned long caller)
772 if (g_httpfetch_thread->isRunning()) {
774 g_httpfetch_thread->requestClear(caller, &event);
777 g_httpfetch_thread->requestClear(caller, NULL);
781 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
782 HTTPFetchResult &fetch_result)
784 // Create ongoing fetch data and make a cURL handle
785 // Set cURL options based on HTTPFetchRequest
787 HTTPFetchOngoing ongoing(fetch_request, &pool);
788 // Do the fetch (curl_easy_perform)
789 CURLcode res = ongoing.start(NULL);
790 // Update fetch result
791 fetch_result = *ongoing.complete(res);
799 Dummy httpfetch implementation that always returns an error.
802 void httpfetch_init(int parallel_limit)
806 void httpfetch_cleanup()
810 void httpfetch_async(const HTTPFetchRequest &fetch_request)
812 errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
813 << " because USE_CURL=0" << std::endl;
815 HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
816 httpfetch_deliver_result(fetch_result);
819 static void httpfetch_request_clear(unsigned long caller)
823 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
824 HTTPFetchResult &fetch_result)
826 errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
827 << " because USE_CURL=0" << std::endl;
829 fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.