1 /*
2 httpfetch.cpp
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 */
5 
6 /*
7 This file is part of Freeminer.
8 
9 Freeminer is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13 
14 Freeminer  is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18 
19 You should have received a copy of the GNU General Public License
20 along with Freeminer.  If not, see <http://www.gnu.org/licenses/>.
21 */
22 
23 #include "socket.h" // for select()
24 #include "porting.h" // for sleep_ms(), get_sysinfo()
25 #include "httpfetch.h"
26 #include <iostream>
27 #include <sstream>
28 #include <list>
29 #include <map>
30 #include <errno.h>
31 #include "jthread/jevent.h"
32 #include "config.h"
33 #include "exceptions.h"
34 #include "debug.h"
35 #include "log.h"
36 #include "util/container.h"
37 #include "version.h"
38 #include "main.h"
39 #include "settings.h"
40 #include "util/thread_pool.h"
41 
42 JMutex g_httpfetch_mutex;
43 std::map<unsigned long, std::list<HTTPFetchResult> > g_httpfetch_results;
44 
HTTPFetchRequest()45 HTTPFetchRequest::HTTPFetchRequest()
46 {
47 	url = "";
48 	caller = HTTPFETCH_DISCARD;
49 	request_id = 0;
50 	timeout = g_settings->getS32("curl_timeout");
51 	connect_timeout = timeout;
52 	multipart = false;
53 
54 	useragent = std::string("Freeminer/") + minetest_version_hash + " (" + porting::get_sysinfo() + ")";
55 }
56 
57 
httpfetch_deliver_result(const HTTPFetchResult & fetch_result)58 static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
59 {
60 	unsigned long caller = fetch_result.caller;
61 	if (caller != HTTPFETCH_DISCARD) {
62 		JMutexAutoLock lock(g_httpfetch_mutex);
63 		g_httpfetch_results[caller].push_back(fetch_result);
64 	}
65 }
66 
67 static void httpfetch_request_clear(unsigned long caller);
68 
httpfetch_caller_alloc()69 unsigned long httpfetch_caller_alloc()
70 {
71 	JMutexAutoLock lock(g_httpfetch_mutex);
72 
73 	// Check each caller ID except HTTPFETCH_DISCARD
74 	const unsigned long discard = HTTPFETCH_DISCARD;
75 	for (unsigned long caller = discard + 1; caller != discard; ++caller) {
76 		std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
77 			it = g_httpfetch_results.find(caller);
78 		if (it == g_httpfetch_results.end()) {
79 			verbosestream<<"httpfetch_caller_alloc: allocating "
80 					<<caller<<std::endl;
81 			// Access element to create it
82 			g_httpfetch_results[caller];
83 			return caller;
84 		}
85 	}
86 
87 	assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
88 	return discard;
89 }
90 
httpfetch_caller_free(unsigned long caller)91 void httpfetch_caller_free(unsigned long caller)
92 {
93 	verbosestream<<"httpfetch_caller_free: freeing "
94 			<<caller<<std::endl;
95 
96 	httpfetch_request_clear(caller);
97 	if (caller != HTTPFETCH_DISCARD) {
98 		JMutexAutoLock lock(g_httpfetch_mutex);
99 		g_httpfetch_results.erase(caller);
100 	}
101 }
102 
httpfetch_async_get(unsigned long caller,HTTPFetchResult & fetch_result)103 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result)
104 {
105 	JMutexAutoLock lock(g_httpfetch_mutex);
106 
107 	// Check that caller exists
108 	std::map<unsigned long, std::list<HTTPFetchResult> >::iterator
109 		it = g_httpfetch_results.find(caller);
110 	if (it == g_httpfetch_results.end())
111 		return false;
112 
113 	// Check that result queue is nonempty
114 	std::list<HTTPFetchResult> &caller_results = it->second;
115 	if (caller_results.empty())
116 		return false;
117 
118 	// Pop first result
119 	fetch_result = caller_results.front();
120 	caller_results.pop_front();
121 	return true;
122 }
123 
124 #if USE_CURL
125 #include <curl/curl.h>
126 #ifndef _WIN32
127 #include <sys/utsname.h>
128 #endif
129 
130 /*
131 	USE_CURL is on: use cURL based httpfetch implementation
132 */
133 
httpfetch_writefunction(char * ptr,size_t size,size_t nmemb,void * userdata)134 static size_t httpfetch_writefunction(
135 		char *ptr, size_t size, size_t nmemb, void *userdata)
136 {
137 	std::ostringstream *stream = (std::ostringstream*)userdata;
138 	size_t count = size * nmemb;
139 	stream->write(ptr, count);
140 	return count;
141 }
142 
httpfetch_discardfunction(char * ptr,size_t size,size_t nmemb,void * userdata)143 static size_t httpfetch_discardfunction(
144 		char *ptr, size_t size, size_t nmemb, void *userdata)
145 {
146 	return size * nmemb;
147 }
148 
149 class CurlHandlePool
150 {
151 	std::list<CURL*> handles;
152 
153 public:
CurlHandlePool()154 	CurlHandlePool() {}
~CurlHandlePool()155 	~CurlHandlePool()
156 	{
157 		for (std::list<CURL*>::iterator it = handles.begin();
158 				it != handles.end(); ++it) {
159 			curl_easy_cleanup(*it);
160 		}
161 	}
alloc()162 	CURL * alloc()
163 	{
164 		CURL *curl;
165 		if (handles.empty()) {
166 			curl = curl_easy_init();
167 			if (curl == NULL) {
168 				errorstream<<"curl_easy_init returned NULL"<<std::endl;
169 			}
170 		}
171 		else {
172 			curl = handles.front();
173 			handles.pop_front();
174 		}
175 		return curl;
176 	}
free(CURL * handle)177 	void free(CURL *handle)
178 	{
179 		if (handle)
180 			handles.push_back(handle);
181 	}
182 };
183 
184 class HTTPFetchOngoing
185 {
186 public:
187 	HTTPFetchOngoing(HTTPFetchRequest request, CurlHandlePool *pool);
188 	~HTTPFetchOngoing();
189 
190 	CURLcode start(CURLM *multi);
191 	const HTTPFetchResult * complete(CURLcode res);
192 
getRequest() const193 	const HTTPFetchRequest &getRequest()    const { return request; };
getEasyHandle() const194 	const CURL             *getEasyHandle() const { return curl; };
195 
196 private:
197 	CurlHandlePool *pool;
198 	CURL *curl;
199 	CURLM *multi;
200 	HTTPFetchRequest request;
201 	HTTPFetchResult result;
202 	std::ostringstream oss;
203 	//char *post_fields;
204 	struct curl_slist *http_header;
205 	curl_httppost *post;
206 };
207 
208 
HTTPFetchOngoing(HTTPFetchRequest request_,CurlHandlePool * pool_)209 HTTPFetchOngoing::HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
210 	pool(pool_),
211 	curl(NULL),
212 	multi(NULL),
213 	request(request_),
214 	result(request_),
215 	oss(std::ios::binary),
216 	http_header(NULL),
217 	post(NULL)
218 {
219 	curl = pool->alloc();
220 	if (curl == NULL) {
221 		return;
222 	}
223 
224 	// Set static cURL options
225 	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
226 	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
227 	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
228 	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);
229 
230 	std::string bind_address = g_settings->get("bind_address");
231 	if (!bind_address.empty()) {
232 		curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
233 	}
234 
235 #if LIBCURL_VERSION_NUM >= 0x071304
236 	// Restrict protocols so that curl vulnerabilities in
237 	// other protocols don't affect us.
238 	// These settings were introduced in curl 7.19.4.
239 	long protocols =
240 		CURLPROTO_HTTP |
241 		CURLPROTO_HTTPS |
242 		CURLPROTO_FTP |
243 		CURLPROTO_FTPS;
244 	curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
245 	curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
246 #endif
247 
248 	// Set cURL options based on HTTPFetchRequest
249 	curl_easy_setopt(curl, CURLOPT_URL,
250 			request.url.c_str());
251 	curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
252 			request.timeout);
253 	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
254 			request.connect_timeout);
255 
256 	if (request.useragent != "")
257 		curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
258 	else {
259 		std::string useragent = std::string("Freeminer ") + minetest_version_hash;
260 #ifdef _WIN32
261 		useragent += "Windows";
262 #else
263 		struct utsname osinfo;
264 		uname(&osinfo);
265 		useragent += std::string(" (") + osinfo.sysname + "; " + osinfo.release + "; " + osinfo.machine + ")";
266 #endif
267 		curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent.c_str());
268 	}
269 
270 	// Set up a write callback that writes to the
271 	// ostringstream ongoing->oss, unless the data
272 	// is to be discarded
273 	if (request.caller == HTTPFETCH_DISCARD) {
274 		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
275 				httpfetch_discardfunction);
276 		curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
277 	} else {
278 		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
279 				httpfetch_writefunction);
280 		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
281 	}
282 
283 	// Set POST (or GET) data
284 	if (request.post_fields.empty()) {
285 		curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
286 	} else if (request.multipart) {
287 		curl_httppost *last = NULL;
288 		for (std::map<std::string, std::string>::iterator it =
289 					request.post_fields.begin();
290 				it != request.post_fields.end(); ++it) {
291 			curl_formadd(&post, &last,
292 					CURLFORM_NAMELENGTH, it->first.size(),
293 					CURLFORM_PTRNAME, it->first.c_str(),
294 					CURLFORM_CONTENTSLENGTH, it->second.size(),
295 					CURLFORM_PTRCONTENTS, it->second.c_str(),
296 					CURLFORM_END);
297 		}
298 		curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
299 		// request.post_fields must now *never* be
300 		// modified until CURLOPT_HTTPPOST is cleared
301 	} else if (request.post_data.empty()) {
302 		curl_easy_setopt(curl, CURLOPT_POST, 1);
303 		std::string str;
304 		for (std::map<std::string, std::string>::iterator it =
305 					request.post_fields.begin();
306 				it != request.post_fields.end();
307 				++it) {
308 			if (str != "")
309 				str += "&";
310 			str += urlencode(it->first);
311 			str += "=";
312 			str += urlencode(it->second);
313 		}
314 		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
315 				str.size());
316 		curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
317 				str.c_str());
318 	} else {
319 		curl_easy_setopt(curl, CURLOPT_POST, 1);
320 		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
321 				request.post_data.size());
322 		curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
323 				request.post_data.c_str());
324 		// request.post_data must now *never* be
325 		// modified until CURLOPT_POSTFIELDS is cleared
326 	}
327 	// Set additional HTTP headers
328 	for (std::vector<std::string>::iterator it = request.extra_headers.begin();
329 			it != request.extra_headers.end(); ++it) {
330 		http_header = curl_slist_append(http_header, it->c_str());
331 	}
332 	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
333 
334 	if (!g_settings->getBool("curl_verify_cert")) {
335 		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
336 	}
337 }
338 
start(CURLM * multi_)339 CURLcode HTTPFetchOngoing::start(CURLM *multi_)
340 {
341 	if (!curl)
342 		return CURLE_FAILED_INIT;
343 
344 	if (!multi_) {
345 		// Easy interface (sync)
346 		return curl_easy_perform(curl);
347 	}
348 
349 	// Multi interface (async)
350 	CURLMcode mres = curl_multi_add_handle(multi_, curl);
351 	if (mres != CURLM_OK) {
352 		errorstream << "curl_multi_add_handle"
353 			<< " returned error code " << mres
354 			<< std::endl;
355 		return CURLE_FAILED_INIT;
356 	}
357 	multi = multi_; // store for curl_multi_remove_handle
358 	return CURLE_OK;
359 }
360 
complete(CURLcode res)361 const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
362 {
363 	result.succeeded = (res == CURLE_OK);
364 	result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
365 	result.data = oss.str();
366 
367 	// Get HTTP/FTP response code
368 	result.response_code = 0;
369 	if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
370 				&result.response_code) != CURLE_OK)) {
371 		// We failed to get a return code, make sure it is still 0
372 		result.response_code = 0;
373 	}
374 
375 	if (res != CURLE_OK) {
376 		errorstream << request.url << " not found ("
377 			<< curl_easy_strerror(res) << ")"
378 			<< " (response code " << result.response_code << ")"
379 			<< std::endl;
380 	}
381 
382 	return &result;
383 }
384 
~HTTPFetchOngoing()385 HTTPFetchOngoing::~HTTPFetchOngoing()
386 {
387 	if (multi) {
388 		CURLMcode mres = curl_multi_remove_handle(multi, curl);
389 		if (mres != CURLM_OK) {
390 			errorstream << "curl_multi_remove_handle"
391 				<< " returned error code " << mres
392 				<< std::endl;
393 		}
394 	}
395 
396 	// Set safe options for the reusable cURL handle
397 	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
398 			httpfetch_discardfunction);
399 	curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
400 	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
401 	if (http_header) {
402 		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
403 		curl_slist_free_all(http_header);
404 	}
405 	if (post) {
406 		curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
407 		curl_formfree(post);
408 	}
409 
410 	// Store the cURL handle for reuse
411 	pool->free(curl);
412 }
413 
414 
415 class CurlFetchThread : public thread_pool
416 {
417 protected:
418 	enum RequestType {
419 		RT_FETCH,
420 		RT_CLEAR,
421 		RT_WAKEUP,
422 	};
423 
424 	struct Request {
425 		RequestType type;
426 		HTTPFetchRequest fetch_request;
427 		Event *event;
428 	};
429 
430 	CURLM *m_multi;
431 	MutexedQueue<Request> m_requests;
432 	size_t m_parallel_limit;
433 
434 	// Variables exclusively used within thread
435 	std::vector<HTTPFetchOngoing*> m_all_ongoing;
436 	std::list<HTTPFetchRequest> m_queued_fetches;
437 
438 public:
CurlFetchThread(int parallel_limit)439 	CurlFetchThread(int parallel_limit)
440 	{
441 		if (parallel_limit >= 1)
442 			m_parallel_limit = parallel_limit;
443 		else
444 			m_parallel_limit = 1;
445 	}
446 
requestFetch(const HTTPFetchRequest & fetch_request)447 	void requestFetch(const HTTPFetchRequest &fetch_request)
448 	{
449 		Request req;
450 		req.type = RT_FETCH;
451 		req.fetch_request = fetch_request;
452 		req.event = NULL;
453 		m_requests.push_back(req);
454 	}
455 
requestClear(unsigned long caller,Event * event)456 	void requestClear(unsigned long caller, Event *event)
457 	{
458 		Request req;
459 		req.type = RT_CLEAR;
460 		req.fetch_request.caller = caller;
461 		req.event = event;
462 		m_requests.push_back(req);
463 	}
464 
requestWakeUp()465 	void requestWakeUp()
466 	{
467 		Request req;
468 		req.type = RT_WAKEUP;
469 		req.event = NULL;
470 		m_requests.push_back(req);
471 	}
472 
473 protected:
474 	// Handle a request from some other thread
475 	// E.g. new fetch; clear fetches for one caller; wake up
processRequest(const Request & req)476 	void processRequest(const Request &req)
477 	{
478 		if (req.type == RT_FETCH) {
479 			// New fetch, queue until there are less
480 			// than m_parallel_limit ongoing fetches
481 			m_queued_fetches.push_back(req.fetch_request);
482 
483 			// see processQueued() for what happens next
484 
485 		}
486 		else if (req.type == RT_CLEAR) {
487 			unsigned long caller = req.fetch_request.caller;
488 
489 			// Abort all ongoing fetches for the caller
490 			for (std::vector<HTTPFetchOngoing*>::iterator
491 					it = m_all_ongoing.begin();
492 					it != m_all_ongoing.end();) {
493 				if ((*it)->getRequest().caller == caller) {
494 					delete (*it);
495 					it = m_all_ongoing.erase(it);
496 				} else {
497 					++it;
498 				}
499 			}
500 
501 			// Also abort all queued fetches for the caller
502 			for (std::list<HTTPFetchRequest>::iterator
503 					it = m_queued_fetches.begin();
504 					it != m_queued_fetches.end();) {
505 				if ((*it).caller == caller)
506 					it = m_queued_fetches.erase(it);
507 				else
508 					++it;
509 			}
510 		}
511 		else if (req.type == RT_WAKEUP) {
512 			// Wakeup: Nothing to do, thread is awake at this point
513 		}
514 
515 		if (req.event != NULL)
516 			req.event->signal();
517 	}
518 
519 	// Start new ongoing fetches if m_parallel_limit allows
processQueued(CurlHandlePool * pool)520 	void processQueued(CurlHandlePool *pool)
521 	{
522 		while (m_all_ongoing.size() < m_parallel_limit &&
523 				!m_queued_fetches.empty()) {
524 			HTTPFetchRequest request = m_queued_fetches.front();
525 			m_queued_fetches.pop_front();
526 
527 			// Create ongoing fetch data and make a cURL handle
528 			// Set cURL options based on HTTPFetchRequest
529 			HTTPFetchOngoing *ongoing =
530 				new HTTPFetchOngoing(request, pool);
531 
532 			// Initiate the connection (curl_multi_add_handle)
533 			CURLcode res = ongoing->start(m_multi);
534 			if (res == CURLE_OK) {
535 				m_all_ongoing.push_back(ongoing);
536 			}
537 			else {
538 				httpfetch_deliver_result(*ongoing->complete(res));
539 				delete ongoing;
540 			}
541 		}
542 	}
543 
544 	// Process CURLMsg (indicates completion of a fetch)
processCurlMessage(CURLMsg * msg)545 	void processCurlMessage(CURLMsg *msg)
546 	{
547 		// Determine which ongoing fetch the message pertains to
548 		size_t i = 0;
549 		bool found = false;
550 		for (i = 0; i < m_all_ongoing.size(); ++i) {
551 			if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
552 				found = true;
553 				break;
554 			}
555 		}
556 		if (msg->msg == CURLMSG_DONE && found) {
557 			// m_all_ongoing[i] succeeded or failed.
558 			HTTPFetchOngoing *ongoing = m_all_ongoing[i];
559 			httpfetch_deliver_result(*ongoing->complete(msg->data.result));
560 			delete ongoing;
561 			m_all_ongoing.erase(m_all_ongoing.begin() + i);
562 		}
563 	}
564 
565 	// Wait for a request from another thread, or timeout elapses
waitForRequest(long timeout)566 	void waitForRequest(long timeout)
567 	{
568 		if (m_queued_fetches.empty()) {
569 			try {
570 				Request req = m_requests.pop_front(timeout);
571 				processRequest(req);
572 			}
573 			catch (ItemNotFoundException &e) {}
574 		}
575 	}
576 
577 	// Wait until some IO happens, or timeout elapses
waitForIO(long timeout)578 	void waitForIO(long timeout)
579 	{
580 		fd_set read_fd_set;
581 		fd_set write_fd_set;
582 		fd_set exc_fd_set;
583 		int max_fd;
584 		long select_timeout = -1;
585 		struct timeval select_tv;
586 		CURLMcode mres;
587 
588 		FD_ZERO(&read_fd_set);
589 		FD_ZERO(&write_fd_set);
590 		FD_ZERO(&exc_fd_set);
591 
592 		mres = curl_multi_fdset(m_multi, &read_fd_set,
593 				&write_fd_set, &exc_fd_set, &max_fd);
594 		if (mres != CURLM_OK) {
595 			errorstream<<"curl_multi_fdset"
596 				<<" returned error code "<<mres
597 				<<std::endl;
598 			select_timeout = 0;
599 		}
600 
601 		mres = curl_multi_timeout(m_multi, &select_timeout);
602 		if (mres != CURLM_OK) {
603 			errorstream<<"curl_multi_timeout"
604 				<<" returned error code "<<mres
605 				<<std::endl;
606 			select_timeout = 0;
607 		}
608 
609 		// Limit timeout so new requests get through
610 		if (select_timeout < 0 || select_timeout > timeout)
611 			select_timeout = timeout;
612 
613 		if (select_timeout > 0) {
614 			// in Winsock it is forbidden to pass three empty
615 			// fd_sets to select(), so in that case use sleep_ms
616 			if (max_fd != -1) {
617 				select_tv.tv_sec = select_timeout / 1000;
618 				select_tv.tv_usec = (select_timeout % 1000) * 1000;
619 				int retval = select(max_fd + 1, &read_fd_set,
620 						&write_fd_set, &exc_fd_set,
621 						&select_tv);
622 				if (retval == -1) {
623 					#ifdef _WIN32
624 					errorstream<<"select returned error code "
625 						<<WSAGetLastError()<<std::endl;
626 					#else
627 					errorstream<<"select returned error code "
628 						<<errno<<std::endl;
629 					#endif
630 				}
631 			}
632 			else {
633 				sleep_ms(select_timeout);
634 			}
635 		}
636 	}
637 
Thread()638 	void * Thread()
639 	{
640 		ThreadStarted();
641 		log_register_thread("CurlFetchThread");
642 		DSTACK(__FUNCTION_NAME);
643 
644 		porting::setThreadName("CurlFetchThread");
645 
646 		CurlHandlePool pool;
647 
648 		m_multi = curl_multi_init();
649 		if (m_multi == NULL) {
650 			errorstream<<"curl_multi_init returned NULL\n";
651 			return NULL;
652 		}
653 
654 		assert(m_all_ongoing.empty());
655 
656 		while (!StopRequested()) {
657 			BEGIN_DEBUG_EXCEPTION_HANDLER
658 
659 			/*
660 				Handle new async requests
661 			*/
662 
663 			while (!m_requests.empty()) {
664 				Request req = m_requests.pop_frontNoEx();
665 				processRequest(req);
666 			}
667 			processQueued(&pool);
668 
669 			/*
670 				Handle ongoing async requests
671 			*/
672 
673 			int still_ongoing = 0;
674 			while (curl_multi_perform(m_multi, &still_ongoing) ==
675 					CURLM_CALL_MULTI_PERFORM)
676 				/* noop */;
677 
678 			/*
679 				Handle completed async requests
680 			*/
681 			if (still_ongoing < (int) m_all_ongoing.size()) {
682 				CURLMsg *msg;
683 				int msgs_in_queue;
684 				msg = curl_multi_info_read(m_multi, &msgs_in_queue);
685 				while (msg != NULL) {
686 					processCurlMessage(msg);
687 					msg = curl_multi_info_read(m_multi, &msgs_in_queue);
688 				}
689 			}
690 
691 			/*
692 				If there are ongoing requests, wait for data
693 				(with a timeout of 100ms so that new requests
694 				can be processed).
695 
696 				If no ongoing requests, wait for a new request.
697 				(Possibly an empty request that signals
698 				that the thread should be stopped.)
699 			*/
700 			if (m_all_ongoing.empty())
701 				waitForRequest(100000000);
702 			else
703 				waitForIO(100);
704 
705 			END_DEBUG_EXCEPTION_HANDLER(errorstream)
706 		}
707 
708 		// Call curl_multi_remove_handle and cleanup easy handles
709 		for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
710 			delete m_all_ongoing[i];
711 		}
712 		m_all_ongoing.clear();
713 
714 		m_queued_fetches.clear();
715 
716 		CURLMcode mres = curl_multi_cleanup(m_multi);
717 		if (mres != CURLM_OK) {
718 			errorstream<<"curl_multi_cleanup"
719 				<<" returned error code "<<mres
720 				<<std::endl;
721 		}
722 
723 		return NULL;
724 	}
725 };
726 
727 CurlFetchThread *g_httpfetch_thread = NULL;
728 
httpfetch_init(int parallel_limit)729 void httpfetch_init(int parallel_limit)
730 {
731 	verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
732 			<<std::endl;
733 
734 	CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
735 	assert(res == CURLE_OK);
736 
737 	g_httpfetch_thread = new CurlFetchThread(parallel_limit);
738 }
739 
httpfetch_cleanup()740 void httpfetch_cleanup()
741 {
742 	verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
743 
744 	g_httpfetch_thread->Stop();
745 	g_httpfetch_thread->requestWakeUp();
746 	g_httpfetch_thread->Wait();
747 	delete g_httpfetch_thread;
748 
749 	curl_global_cleanup();
750 }
751 
httpfetch_async(const HTTPFetchRequest & fetch_request)752 void httpfetch_async(const HTTPFetchRequest &fetch_request)
753 {
754 	g_httpfetch_thread->requestFetch(fetch_request);
755 	if (!g_httpfetch_thread->IsRunning())
756 		g_httpfetch_thread->Start();
757 }
758 
httpfetch_request_clear(unsigned long caller)759 static void httpfetch_request_clear(unsigned long caller)
760 {
761 	if (g_httpfetch_thread->IsRunning()) {
762 		Event event;
763 		g_httpfetch_thread->requestClear(caller, &event);
764 		event.wait();
765 	}
766 	else {
767 		g_httpfetch_thread->requestClear(caller, NULL);
768 	}
769 }
770 
httpfetch_sync(const HTTPFetchRequest & fetch_request,HTTPFetchResult & fetch_result)771 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
772 		HTTPFetchResult &fetch_result)
773 {
774 	// Create ongoing fetch data and make a cURL handle
775 	// Set cURL options based on HTTPFetchRequest
776 	CurlHandlePool pool;
777 	HTTPFetchOngoing ongoing(fetch_request, &pool);
778 	// Do the fetch (curl_easy_perform)
779 	CURLcode res = ongoing.start(NULL);
780 	// Update fetch result
781 	fetch_result = *ongoing.complete(res);
782 }
783 
784 #else  // USE_CURL
785 
786 /*
787 	USE_CURL is off:
788 
789 	Dummy httpfetch implementation that always returns an error.
790 */
791 
httpfetch_init(int parallel_limit)792 void httpfetch_init(int parallel_limit)
793 {
794 }
795 
httpfetch_cleanup()796 void httpfetch_cleanup()
797 {
798 }
799 
httpfetch_async(const HTTPFetchRequest & fetch_request)800 void httpfetch_async(const HTTPFetchRequest &fetch_request)
801 {
802 	errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
803 			<< " because USE_CURL=0" << std::endl;
804 
805 	HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
806 	httpfetch_deliver_result(fetch_result);
807 }
808 
httpfetch_request_clear(unsigned long caller)809 static void httpfetch_request_clear(unsigned long caller)
810 {
811 }
812 
httpfetch_sync(const HTTPFetchRequest & fetch_request,HTTPFetchResult & fetch_result)813 void httpfetch_sync(const HTTPFetchRequest &fetch_request,
814 		HTTPFetchResult &fetch_result)
815 {
816 	errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
817 			<< " because USE_CURL=0" << std::endl;
818 
819 	fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.
820 }
821 
822 #endif  // USE_CURL
823