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);
209 // Set up a write callback that writes to the
210 // ostringstream ongoing->oss, unless the data
211 // is to be discarded
212 if (request.caller == HTTPFETCH_DISCARD) {
213 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
214 httpfetch_discardfunction);
215 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
218 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
219 httpfetch_writefunction);
220 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
222 // Set POST (or GET) data
223 if (request.post_fields.empty()) {
224 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
227 curl_easy_setopt(curl, CURLOPT_POST, 1);
228 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
229 request.post_fields.size());
230 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
231 request.post_fields.c_str());
232 // request.post_fields must now *never* be
233 // modified until CURLOPT_POSTFIELDS is cleared
235 // Set additional HTTP headers
236 for (size_t i = 0; i < request.extra_headers.size(); ++i) {
237 httpheader = curl_slist_append(
239 request.extra_headers[i].c_str());
241 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
245 CURLcode start(CURLM *multi_)
248 return CURLE_FAILED_INIT;
251 // Multi interface (async)
252 CURLMcode mres = curl_multi_add_handle(multi_, curl);
253 if (mres != CURLM_OK) {
254 errorstream<<"curl_multi_add_handle"
255 <<" returned error code "<<mres
257 return CURLE_FAILED_INIT;
259 multi = multi_; // store for curl_multi_remove_handle
263 // Easy interface (sync)
264 return curl_easy_perform(curl);
268 void complete(CURLcode res)
270 result.succeeded = (res == CURLE_OK);
271 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
272 result.data = oss.str();
274 // Get HTTP/FTP response code
275 result.response_code = 0;
277 if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
278 &result.response_code) != CURLE_OK) {
279 result.response_code = 0;
283 if (res != CURLE_OK) {
284 infostream<<request.url<<" not found ("
285 <<curl_easy_strerror(res)<<")"
286 <<" (response code "<<result.response_code<<")"
294 CURLMcode mres = curl_multi_remove_handle(multi, curl);
295 if (mres != CURLM_OK) {
296 errorstream<<"curl_multi_remove_handle"
297 <<" returned error code "<<mres
302 // Set safe options for the reusable cURL handle
303 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
304 httpfetch_discardfunction);
305 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
306 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
307 if (httpheader != NULL) {
308 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
309 curl_slist_free_all(httpheader);
312 // Store the cURL handle for reuse
317 class CurlFetchThread : public SimpleThread
328 HTTPFetchRequest fetchrequest;
333 MutexedQueue<Request> m_requests;
334 size_t m_parallel_limit;
336 // Variables exclusively used within thread
337 std::vector<HTTPFetchOngoing*> m_all_ongoing;
338 std::list<HTTPFetchRequest> m_queued_fetches;
341 CurlFetchThread(int parallel_limit)
343 if (parallel_limit >= 1)
344 m_parallel_limit = parallel_limit;
346 m_parallel_limit = 1;
349 void requestFetch(const HTTPFetchRequest &fetchrequest)
353 req.fetchrequest = fetchrequest;
355 m_requests.push_back(req);
358 void requestClear(unsigned long caller, Event *event)
362 req.fetchrequest.caller = caller;
364 m_requests.push_back(req);
370 req.type = RT_WAKEUP;
372 m_requests.push_back(req);
376 // Handle a request from some other thread
377 // E.g. new fetch; clear fetches for one caller; wake up
378 void processRequest(const Request &req)
380 if (req.type == RT_FETCH) {
381 // New fetch, queue until there are less
382 // than m_parallel_limit ongoing fetches
383 m_queued_fetches.push_back(req.fetchrequest);
385 // see processQueued() for what happens next
388 else if (req.type == RT_CLEAR) {
389 unsigned long caller = req.fetchrequest.caller;
391 // Abort all ongoing fetches for the caller
392 for (std::vector<HTTPFetchOngoing*>::iterator
393 it = m_all_ongoing.begin();
394 it != m_all_ongoing.end();) {
395 if ((*it)->request.caller == caller) {
397 it = m_all_ongoing.erase(it);
403 // Also abort all queued fetches for the caller
404 for (std::list<HTTPFetchRequest>::iterator
405 it = m_queued_fetches.begin();
406 it != m_queued_fetches.end();) {
407 if ((*it).caller == caller)
408 it = m_queued_fetches.erase(it);
413 else if (req.type == RT_WAKEUP) {
414 // Wakeup: Nothing to do, thread is awake at this point
417 if (req.event != NULL)
421 // Start new ongoing fetches if m_parallel_limit allows
422 void processQueued(CurlHandlePool *pool)
424 while (m_all_ongoing.size() < m_parallel_limit &&
425 !m_queued_fetches.empty()) {
426 HTTPFetchRequest request = m_queued_fetches.front();
427 m_queued_fetches.pop_front();
429 // Create ongoing fetch data and make a cURL handle
430 // Set cURL options based on HTTPFetchRequest
431 HTTPFetchOngoing *ongoing =
432 new HTTPFetchOngoing(request, pool);
434 // Initiate the connection (curl_multi_add_handle)
435 CURLcode res = ongoing->start(m_multi);
436 if (res == CURLE_OK) {
437 m_all_ongoing.push_back(ongoing);
440 ongoing->complete(res);
441 httpfetch_deliver_result(ongoing->result);
447 // Process CURLMsg (indicates completion of a fetch)
448 void processCurlMessage(CURLMsg *msg)
450 // Determine which ongoing fetch the message pertains to
453 for (i = 0; i < m_all_ongoing.size(); ++i) {
454 if (m_all_ongoing[i]->curl == msg->easy_handle) {
459 if (msg->msg == CURLMSG_DONE && found) {
460 // m_all_ongoing[i] succeeded or failed.
461 HTTPFetchOngoing *ongoing = m_all_ongoing[i];
462 ongoing->complete(msg->data.result);
463 httpfetch_deliver_result(ongoing->result);
465 m_all_ongoing.erase(m_all_ongoing.begin() + i);
469 // Wait for a request from another thread, or timeout elapses
470 void waitForRequest(long timeout)
472 if (m_queued_fetches.empty()) {
474 Request req = m_requests.pop_front(timeout);
477 catch (ItemNotFoundException &e) {}
481 // Wait until some IO happens, or timeout elapses
482 void waitForIO(long timeout)
488 long select_timeout = -1;
489 struct timeval select_tv;
492 FD_ZERO(&read_fd_set);
493 FD_ZERO(&write_fd_set);
494 FD_ZERO(&exc_fd_set);
496 mres = curl_multi_fdset(m_multi, &read_fd_set,
497 &write_fd_set, &exc_fd_set, &max_fd);
498 if (mres != CURLM_OK) {
499 errorstream<<"curl_multi_fdset"
500 <<" returned error code "<<mres
505 mres = curl_multi_timeout(m_multi, &select_timeout);
506 if (mres != CURLM_OK) {
507 errorstream<<"curl_multi_timeout"
508 <<" returned error code "<<mres
513 // Limit timeout so new requests get through
514 if (select_timeout < 0 || select_timeout > timeout)
515 select_timeout = timeout;
517 if (select_timeout > 0) {
518 select_tv.tv_sec = select_timeout / 1000;
519 select_tv.tv_usec = (select_timeout % 1000) * 1000;
520 int retval = select(max_fd + 1, &read_fd_set,
521 &write_fd_set, &exc_fd_set,
525 errorstream<<"select returned error code "
526 <<WSAGetLastError()<<std::endl;
528 errorstream<<"select returned error code "
538 log_register_thread("CurlFetchThread");
539 DSTACK(__FUNCTION_NAME);
543 m_multi = curl_multi_init();
544 if (m_multi == NULL) {
545 errorstream<<"curl_multi_init returned NULL\n";
549 assert(m_all_ongoing.empty());
552 BEGIN_DEBUG_EXCEPTION_HANDLER
555 Handle new async requests
558 while (!m_requests.empty()) {
559 Request req = m_requests.pop_front();
562 processQueued(&pool);
565 Handle ongoing async requests
568 int still_ongoing = 0;
569 while (curl_multi_perform(m_multi, &still_ongoing) ==
570 CURLM_CALL_MULTI_PERFORM)
574 Handle completed async requests
576 if (still_ongoing < (int) m_all_ongoing.size()) {
579 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
580 while (msg != NULL) {
581 processCurlMessage(msg);
582 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
587 If there are ongoing requests, wait for data
588 (with a timeout of 100ms so that new requests
591 If no ongoing requests, wait for a new request.
592 (Possibly an empty request that signals
593 that the thread should be stopped.)
595 if (m_all_ongoing.empty())
596 waitForRequest(100000000);
600 END_DEBUG_EXCEPTION_HANDLER(errorstream)
603 // Call curl_multi_remove_handle and cleanup easy handles
604 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
605 delete m_all_ongoing[i];
607 m_all_ongoing.clear();
609 m_queued_fetches.clear();
611 CURLMcode mres = curl_multi_cleanup(m_multi);
612 if (mres != CURLM_OK) {
613 errorstream<<"curl_multi_cleanup"
614 <<" returned error code "<<mres
622 CurlFetchThread *g_httpfetch_thread = NULL;
624 void httpfetch_init(int parallel_limit)
626 verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
629 CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
630 assert(res == CURLE_OK);
632 g_httpfetch_thread = new CurlFetchThread(parallel_limit);
635 void httpfetch_cleanup()
637 verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
639 g_httpfetch_thread->setRun(false);
640 g_httpfetch_thread->requestWakeUp();
641 g_httpfetch_thread->stop();
642 delete g_httpfetch_thread;
644 curl_global_cleanup();
647 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
649 g_httpfetch_thread->requestFetch(fetchrequest);
650 if (!g_httpfetch_thread->IsRunning())
651 g_httpfetch_thread->Start();
654 static void httpfetch_request_clear(unsigned long caller)
656 if (g_httpfetch_thread->IsRunning()) {
658 g_httpfetch_thread->requestClear(caller, &event);
662 g_httpfetch_thread->requestClear(caller, NULL);
666 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
667 HTTPFetchResult &fetchresult)
669 // Create ongoing fetch data and make a cURL handle
670 // Set cURL options based on HTTPFetchRequest
672 HTTPFetchOngoing ongoing(fetchrequest, &pool);
673 // Do the fetch (curl_easy_perform)
674 CURLcode res = ongoing.start(NULL);
675 // Update fetchresult
676 ongoing.complete(res);
677 fetchresult = ongoing.result;
685 Dummy httpfetch implementation that always returns an error.
688 void httpfetch_init(int parallel_limit)
692 void httpfetch_cleanup()
696 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
698 errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
699 <<" because USE_CURL=0"<<std::endl;
701 HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
702 httpfetch_deliver_result(fetchresult);
705 static void httpfetch_request_clear(unsigned long caller)
709 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
710 HTTPFetchResult &fetchresult)
712 errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
713 <<" because USE_CURL=0"<<std::endl;
715 fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.