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