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"
26 #include "jthread/jevent.h"
28 #include "exceptions.h"
31 #include "util/container.h"
32 #include "util/thread.h"
33 #include "socket.h" // for select()
35 JMutex g_httpfetch_mutex;
36 std::map<unsigned long, std::list<HTTPFetchResult> > g_httpfetch_results;
38 static void httpfetch_deliver_result(const HTTPFetchResult &fetchresult)
40 unsigned long caller = fetchresult.caller;
41 if (caller != HTTPFETCH_DISCARD) {
42 JMutexAutoLock lock(g_httpfetch_mutex);
43 g_httpfetch_results[caller].push_back(fetchresult);
47 static void httpfetch_request_clear(unsigned long caller);
49 unsigned long httpfetch_caller_alloc()
51 JMutexAutoLock lock(g_httpfetch_mutex);
53 // Check each caller ID except HTTPFETCH_DISCARD
54 const unsigned long discard = HTTPFETCH_DISCARD;
55 for (unsigned long caller = discard + 1; caller != discard; ++caller) {
56 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
57 it = g_httpfetch_results.find(caller);
58 if (it == g_httpfetch_results.end()) {
59 verbosestream<<"httpfetch_caller_alloc: allocating "
61 // Access element to create it
62 g_httpfetch_results[caller];
67 assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
71 void httpfetch_caller_free(unsigned long caller)
73 verbosestream<<"httpfetch_caller_free: freeing "
76 httpfetch_request_clear(caller);
77 if (caller != HTTPFETCH_DISCARD) {
78 JMutexAutoLock lock(g_httpfetch_mutex);
79 g_httpfetch_results.erase(caller);
83 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetchresult)
85 JMutexAutoLock lock(g_httpfetch_mutex);
87 // Check that caller exists
88 std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
89 it = g_httpfetch_results.find(caller);
90 if (it == g_httpfetch_results.end())
93 // Check that result queue is nonempty
94 std::list<HTTPFetchResult> &callerresults = it->second;
95 if (callerresults.empty())
99 fetchresult = callerresults.front();
100 callerresults.pop_front();
105 #include <curl/curl.h>
108 USE_CURL is on: use cURL based httpfetch implementation
111 static size_t httpfetch_writefunction(
112 char *ptr, size_t size, size_t nmemb, void *userdata)
114 std::ostringstream *stream = (std::ostringstream*)userdata;
115 size_t count = size * nmemb;
116 stream->write(ptr, count);
120 static size_t httpfetch_discardfunction(
121 char *ptr, size_t size, size_t nmemb, void *userdata)
128 std::list<CURL*> handles;
134 for (std::list<CURL*>::iterator it = handles.begin();
135 it != handles.end(); ++it) {
136 curl_easy_cleanup(*it);
142 if (handles.empty()) {
143 curl = curl_easy_init();
145 errorstream<<"curl_easy_init returned NULL"<<std::endl;
149 curl = handles.front();
154 void free(CURL *handle)
157 handles.push_back(handle);
161 struct HTTPFetchOngoing
163 CurlHandlePool *pool;
166 HTTPFetchRequest request;
167 HTTPFetchResult result;
168 std::ostringstream oss;
170 struct curl_slist *httpheader;
172 HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
178 oss(std::ios::binary),
181 curl = pool->alloc();
183 // Set static cURL options
184 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
185 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
186 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
187 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
189 #if LIBCURL_VERSION_NUM >= 0x071304
190 // Restrict protocols so that curl vulnerabilities in
191 // other protocols don't affect us.
192 // These settings were introduced in curl 7.19.4.
198 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
199 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
202 // Set cURL options based on HTTPFetchRequest
203 curl_easy_setopt(curl, CURLOPT_URL,
204 request.url.c_str());
205 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
207 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
208 request.connect_timeout);
210 if (request.useragent != "")
211 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
213 // Set up a write callback that writes to the
214 // ostringstream ongoing->oss, unless the data
215 // is to be discarded
216 if (request.caller == HTTPFETCH_DISCARD) {
217 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
218 httpfetch_discardfunction);
219 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
222 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
223 httpfetch_writefunction);
224 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
226 // Set POST (or GET) data
227 if (request.post_fields.empty()) {
228 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
231 curl_easy_setopt(curl, CURLOPT_POST, 1);
232 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
233 request.post_fields.size());
234 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
235 request.post_fields.c_str());
236 // request.post_fields must now *never* be
237 // modified until CURLOPT_POSTFIELDS is cleared
239 // Set additional HTTP headers
240 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
241 httpheader = curl_slist_append(
243 request.extra_headers[i].c_str());
245 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
249 CURLcode start(CURLM *multi_)
252 return CURLE_FAILED_INIT;
255 // Multi interface (async)
256 CURLMcode mres = curl_multi_add_handle(multi_, curl);
257 if (mres != CURLM_OK) {
258 errorstream<<"curl_multi_add_handle"
259 <<" returned error code "<<mres
261 return CURLE_FAILED_INIT;
263 multi = multi_; // store for curl_multi_remove_handle
267 // Easy interface (sync)
268 return curl_easy_perform(curl);
272 void complete(CURLcode res)
274 result.succeeded = (res == CURLE_OK);
275 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
276 result.data = oss.str();
278 // Get HTTP/FTP response code
279 result.response_code = 0;
281 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
282 &result.response_code) != CURLE_OK) {
283 result.response_code = 0;
287 if (res != CURLE_OK) {
288 infostream<<request.url<<" not found ("
289 <<curl_easy_strerror(res)<<")"
290 <<" (response code "<<result.response_code<<")"
298 CURLMcode mres = curl_multi_remove_handle(multi, curl);
299 if (mres != CURLM_OK) {
300 errorstream<<"curl_multi_remove_handle"
301 <<" returned error code "<<mres
306 // Set safe options for the reusable cURL handle
307 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
308 httpfetch_discardfunction);
309 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
310 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
311 if (httpheader != NULL) {
312 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
313 curl_slist_free_all(httpheader);
316 // Store the cURL handle for reuse
321 class CurlFetchThread : public SimpleThread
332 HTTPFetchRequest fetchrequest;
337 MutexedQueue<Request> m_requests;
338 size_t m_parallel_limit;
340 // Variables exclusively used within thread
341 std::vector<HTTPFetchOngoing*> m_all_ongoing;
342 std::list<HTTPFetchRequest> m_queued_fetches;
345 CurlFetchThread(int parallel_limit)
347 if (parallel_limit >= 1)
348 m_parallel_limit = parallel_limit;
350 m_parallel_limit = 1;
353 void requestFetch(const HTTPFetchRequest &fetchrequest)
357 req.fetchrequest = fetchrequest;
359 m_requests.push_back(req);
362 void requestClear(unsigned long caller, Event *event)
366 req.fetchrequest.caller = caller;
368 m_requests.push_back(req);
374 req.type = RT_WAKEUP;
376 m_requests.push_back(req);
380 // Handle a request from some other thread
381 // E.g. new fetch; clear fetches for one caller; wake up
382 void processRequest(const Request &req)
384 if (req.type == RT_FETCH) {
385 // New fetch, queue until there are less
386 // than m_parallel_limit ongoing fetches
387 m_queued_fetches.push_back(req.fetchrequest);
389 // see processQueued() for what happens next
392 else if (req.type == RT_CLEAR) {
393 unsigned long caller = req.fetchrequest.caller;
395 // Abort all ongoing fetches for the caller
396 for (std::vector<HTTPFetchOngoing*>::iterator
397 it = m_all_ongoing.begin();
398 it != m_all_ongoing.end();) {
399 if ((*it)->request.caller == caller) {
401 it = m_all_ongoing.erase(it);
407 // Also abort all queued fetches for the caller
408 for (std::list<HTTPFetchRequest>::iterator
409 it = m_queued_fetches.begin();
410 it != m_queued_fetches.end();) {
411 if ((*it).caller == caller)
412 it = m_queued_fetches.erase(it);
417 else if (req.type == RT_WAKEUP) {
418 // Wakeup: Nothing to do, thread is awake at this point
421 if (req.event != NULL)
425 // Start new ongoing fetches if m_parallel_limit allows
426 void processQueued(CurlHandlePool *pool)
428 while (m_all_ongoing.size() < m_parallel_limit &&
429 !m_queued_fetches.empty()) {
430 HTTPFetchRequest request = m_queued_fetches.front();
431 m_queued_fetches.pop_front();
433 // Create ongoing fetch data and make a cURL handle
434 // Set cURL options based on HTTPFetchRequest
435 HTTPFetchOngoing *ongoing =
436 new HTTPFetchOngoing(request, pool);
438 // Initiate the connection (curl_multi_add_handle)
439 CURLcode res = ongoing->start(m_multi);
440 if (res == CURLE_OK) {
441 m_all_ongoing.push_back(ongoing);
444 ongoing->complete(res);
445 httpfetch_deliver_result(ongoing->result);
451 // Process CURLMsg (indicates completion of a fetch)
452 void processCurlMessage(CURLMsg *msg)
454 // Determine which ongoing fetch the message pertains to
457 for (i = 0; i < m_all_ongoing.size(); ++i) {
458 if (m_all_ongoing[i]->curl == msg->easy_handle) {
463 if (msg->msg == CURLMSG_DONE && found) {
464 // m_all_ongoing[i] succeeded or failed.
465 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
466 ongoing->complete(msg->data.result);
467 httpfetch_deliver_result(ongoing->result);
469 m_all_ongoing.erase(m_all_ongoing.begin() + i);
473 // Wait for a request from another thread, or timeout elapses
474 void waitForRequest(long timeout)
476 if (m_queued_fetches.empty()) {
478 Request req = m_requests.pop_front(timeout);
481 catch (ItemNotFoundException &e) {}
485 // Wait until some IO happens, or timeout elapses
486 void waitForIO(long timeout)
492 long select_timeout = -1;
493 struct timeval select_tv;
496 FD_ZERO(&read_fd_set);
497 FD_ZERO(&write_fd_set);
498 FD_ZERO(&exc_fd_set);
500 mres = curl_multi_fdset(m_multi, &read_fd_set,
501 &write_fd_set, &exc_fd_set, &max_fd);
502 if (mres != CURLM_OK) {
503 errorstream<<"curl_multi_fdset"
504 <<" returned error code "<<mres
509 mres = curl_multi_timeout(m_multi, &select_timeout);
510 if (mres != CURLM_OK) {
511 errorstream<<"curl_multi_timeout"
512 <<" returned error code "<<mres
517 // Limit timeout so new requests get through
518 if (select_timeout < 0 || select_timeout > timeout)
519 select_timeout = timeout;
521 if (select_timeout > 0) {
522 select_tv.tv_sec = select_timeout / 1000;
523 select_tv.tv_usec = (select_timeout % 1000) * 1000;
524 int retval = select(max_fd + 1, &read_fd_set,
525 &write_fd_set, &exc_fd_set,
529 errorstream<<"select returned error code "
530 <<WSAGetLastError()<<std::endl;
532 errorstream<<"select returned error code "
542 log_register_thread("CurlFetchThread");
543 DSTACK(__FUNCTION_NAME);
547 m_multi = curl_multi_init();
548 if (m_multi == NULL) {
549 errorstream<<"curl_multi_init returned NULL\n";
553 assert(m_all_ongoing.empty());
556 BEGIN_DEBUG_EXCEPTION_HANDLER
559 Handle new async requests
562 while (!m_requests.empty()) {
563 Request req = m_requests.pop_front();
566 processQueued(&pool);
569 Handle ongoing async requests
572 int still_ongoing = 0;
573 while (curl_multi_perform(m_multi, &still_ongoing) ==
574 CURLM_CALL_MULTI_PERFORM)
578 Handle completed async requests
580 if (still_ongoing < (int) m_all_ongoing.size()) {
583 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
584 while (msg != NULL) {
585 processCurlMessage(msg);
586 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
591 If there are ongoing requests, wait for data
592 (with a timeout of 100ms so that new requests
595 If no ongoing requests, wait for a new request.
596 (Possibly an empty request that signals
597 that the thread should be stopped.)
599 if (m_all_ongoing.empty())
600 waitForRequest(100000000);
604 END_DEBUG_EXCEPTION_HANDLER(errorstream)
607 // Call curl_multi_remove_handle and cleanup easy handles
608 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
609 delete m_all_ongoing[i];
611 m_all_ongoing.clear();
613 m_queued_fetches.clear();
615 CURLMcode mres = curl_multi_cleanup(m_multi);
616 if (mres != CURLM_OK) {
617 errorstream<<"curl_multi_cleanup"
618 <<" returned error code "<<mres
626 CurlFetchThread *g_httpfetch_thread = NULL;
628 void httpfetch_init(int parallel_limit)
630 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
633 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
634 assert(res == CURLE_OK);
636 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
639 void httpfetch_cleanup()
641 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
643 g_httpfetch_thread->setRun(false);
644 g_httpfetch_thread->requestWakeUp();
645 g_httpfetch_thread->stop();
646 delete g_httpfetch_thread;
648 curl_global_cleanup();
651 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
653 g_httpfetch_thread->requestFetch(fetchrequest);
654 if (!g_httpfetch_thread->IsRunning())
655 g_httpfetch_thread->Start();
658 static void httpfetch_request_clear(unsigned long caller)
660 if (g_httpfetch_thread->IsRunning()) {
662 g_httpfetch_thread->requestClear(caller, &event);
666 g_httpfetch_thread->requestClear(caller, NULL);
670 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
671 HTTPFetchResult &fetchresult)
673 // Create ongoing fetch data and make a cURL handle
674 // Set cURL options based on HTTPFetchRequest
676 HTTPFetchOngoing ongoing(fetchrequest, &pool);
677 // Do the fetch (curl_easy_perform)
678 CURLcode res = ongoing.start(NULL);
679 // Update fetchresult
680 ongoing.complete(res);
681 fetchresult = ongoing.result;
689 Dummy httpfetch implementation that always returns an error.
692 void httpfetch_init(int parallel_limit)
696 void httpfetch_cleanup()
700 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
702 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
703 <<" because USE_CURL=0"<<std::endl;
705 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
706 httpfetch_deliver_result(fetchresult);
709 static void httpfetch_request_clear(unsigned long caller)
713 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
714 HTTPFetchResult &fetchresult)
716 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
717 <<" because USE_CURL=0"<<std::endl;
719 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.