summaryrefslogtreecommitdiff
path: root/src/httpfetch.cpp
blob: cd66a80d51566969541966a69138cf6923893c80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "socket.h" // for select()
#include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf()
#include "httpfetch.h"
#include <iostream>
#include <sstream>
#include <list>
#include <map>
#include <errno.h>
#include <mutex>
#include "threading/event.h"
#include "config.h"
#include "exceptions.h"
#include "debug.h"
#include "log.h"
#include "util/container.h"
#include "util/thread.h"
#include "version.h"
#include "settings.h"
#include "noise.h"

std::mutex g_httpfetch_mutex;
std::map<unsigned long, std::queue<HTTPFetchResult> > g_httpfetch_results;
PcgRandom g_callerid_randomness;

HTTPFetchRequest::HTTPFetchRequest() :
	timeout(g_settings->getS32("curl_timeout")),
	connect_timeout(timeout),
	useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")")
{
}


static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result)
{
	unsigned long caller = fetch_result.caller;
	if (caller != HTTPFETCH_DISCARD) {
		MutexAutoLock lock(g_httpfetch_mutex);
		g_httpfetch_results[caller].push(fetch_result);
	}
}

static void httpfetch_request_clear(unsigned long caller);

unsigned long httpfetch_caller_alloc()
{
	MutexAutoLock lock(g_httpfetch_mutex);

	// Check each caller ID except HTTPFETCH_DISCARD
	const unsigned long discard = HTTPFETCH_DISCARD;
	for (unsigned long caller = discard + 1; caller != discard; ++caller) {
		std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
			it = g_httpfetch_results.find(caller);
		if (it == g_httpfetch_results.end()) {
			verbosestream << "httpfetch_caller_alloc: allocating "
					<< caller << std::endl;
			// Access element to create it
			g_httpfetch_results[caller];
			return caller;
		}
	}

	FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
	return discard;
}

unsigned long httpfetch_caller_alloc_secure()
{
	MutexAutoLock lock(g_httpfetch_mutex);

	// Generate random caller IDs and make sure they're not
	// already used or equal to HTTPFETCH_DISCARD
	// Give up after 100 tries to prevent infinite loop
	u8 tries = 100;
	unsigned long caller;

	do {
		caller = (((u64) g_callerid_randomness.next()) << 32) |
				g_callerid_randomness.next();

		if (--tries < 1) {
			FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs");
			return HTTPFETCH_DISCARD;
		}
	} while (g_httpfetch_results.find(caller) != g_httpfetch_results.end());

	verbosestream << "httpfetch_caller_alloc_secure: allocating "
		<< caller << std::endl;

	// Access element to create it
	g_httpfetch_results[caller];
	return caller;
}

void httpfetch_caller_free(unsigned long caller)
{
	verbosestream<<"httpfetch_caller_free: freeing "
			<<caller<<std::endl;

	httpfetch_request_clear(caller);
	if (caller != HTTPFETCH_DISCARD) {
		MutexAutoLock lock(g_httpfetch_mutex);
		g_httpfetch_results.erase(caller);
	}
}

bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result)
{
	MutexAutoLock lock(g_httpfetch_mutex);

	// Check that caller exists
	std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator
		it = g_httpfetch_results.find(caller);
	if (it == g_httpfetch_results.end())
		return false;

	// Check that result queue is nonempty
	std::queue<HTTPFetchResult> &caller_results = it->second;
	if (caller_results.empty())
		return false;

	// Pop first result
	fetch_result = caller_results.front();
	caller_results.pop();
	return true;
}

#if USE_CURL
#include <curl/curl.h>

/*
	USE_CURL is on: use cURL based httpfetch implementation
*/

static size_t httpfetch_writefunction(
		char *ptr, size_t size, size_t nmemb, void *userdata)
{
	std::ostringstream *stream = (std::ostringstream*)userdata;
	size_t count = size * nmemb;
	stream->write(ptr, count);
	return count;
}

static size_t httpfetch_discardfunction(
		char *ptr, size_t size, size_t nmemb, void *userdata)
{
	return size * nmemb;
}

class CurlHandlePool
{
	std::list<CURL*> handles;

public:
	CurlHandlePool() {}
	~CurlHandlePool()
	{
		for (std::list<CURL*>::iterator it = handles.begin();
				it != handles.end(); ++it) {
			curl_easy_cleanup(*it);
		}
	}
	CURL * alloc()
	{
		CURL *curl;
		if (handles.empty()) {
			curl = curl_easy_init();
			if (curl == NULL) {
				errorstream<<"curl_easy_init returned NULL"<<std::endl;
			}
		}
		else {
			curl = handles.front();
			handles.pop_front();
		}
		return curl;
	}
	void free(CURL *handle)
	{
		if (handle)
			handles.push_back(handle);
	}
};

class HTTPFetchOngoing
{
public:
	HTTPFetchOngoing(const HTTPFetchRequest &request, CurlHandlePool *pool);
	~HTTPFetchOngoing();

	CURLcode start(CURLM *multi);
	const HTTPFetchResult * complete(CURLcode res);

	const HTTPFetchRequest &getRequest()    const { return request; };
	const CURL             *getEasyHandle() const { return curl; };

private:
	CurlHandlePool *pool;
	CURL *curl;
	CURLM *multi;
	HTTPFetchRequest request;
	HTTPFetchResult result;
	std::ostringstream oss;
	struct curl_slist *http_header;
	curl_httppost *post;
};


HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
		CurlHandlePool *pool_):
	pool(pool_),
	curl(NULL),
	multi(NULL),
	request(request_),
	result(request_),
	oss(std::ios::binary),
	http_header(NULL),
	post(NULL)
{
	curl = pool->alloc();
	if (curl == NULL) {
		return;
	}

	// Set static cURL options
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 1);

	std::string bind_address = g_settings->get("bind_address");
	if (!bind_address.empty()) {
		curl_easy_setopt(curl, CURLOPT_INTERFACE, bind_address.c_str());
	}

#if LIBCURL_VERSION_NUM >= 0x071304
	// Restrict protocols so that curl vulnerabilities in
	// other protocols don't affect us.
	// These settings were introduced in curl 7.19.4.
	long protocols =
		CURLPROTO_HTTP |
		CURLPROTO_HTTPS |
		CURLPROTO_FTP |
		CURLPROTO_FTPS;
	curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
	curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
#endif

	// Set cURL options based on HTTPFetchRequest
	curl_easy_setopt(curl, CURLOPT_URL,
			request.url.c_str());
	curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
			request.timeout);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
			request.connect_timeout);

	if (request.useragent != "")
		curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());

	// Set up a write callback that writes to the
	// ostringstream ongoing->oss, unless the data
	// is to be discarded
	if (request.caller == HTTPFETCH_DISCARD) {
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
				httpfetch_discardfunction);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
	} else {
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
				httpfetch_writefunction);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
	}

	// Set POST (or GET) data
	if (request.post_fields.empty() && request.post_data.empty()) {
		curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
	} else if (request.multipart) {
		curl_httppost *last = NULL;
		for (StringMap::iterator it = request.post_fields.begin();
				it != request.post_fields.end(); ++it) {
			curl_formadd(&post, &last,
					CURLFORM_NAMELENGTH, it->first.size(),
					CURLFORM_PTRNAME, it->first.c_str(),
					CURLFORM_CONTENTSLENGTH, it->second.size(),
					CURLFORM_PTRCONTENTS, it->second.c_str(),
					CURLFORM_END);
		}
		curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
		// request.post_fields must now *never* be
		// modified until CURLOPT_HTTPPOST is cleared
	} else if (request.post_data.empty()) {
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		std::string str;
		for (StringMap::iterator it = request.post_fields.begin();
				it != request.post_fields.end(); ++it) {
			if (str != "")
				str += "&";
			str += urlencode(it->first);
			str += "=";
			str += urlencode(it->second);
		}
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
				str.size());
		curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS,
				str.c_str());
	} else {
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
				request.post_data.size());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
				request.post_data.c_str());
		// request.post_data must now *never* be
		// modified until CURLOPT_POSTFIELDS is cleared
	}
	// Set additional HTTP headers
	for (std::vector<std::string>::iterator it = request.extra_headers.begin();
			it != request.extra_headers.end(); ++it) {
		http_header = curl_slist_append(http_header, it->c_str());
	}
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);

	if (!g_settings->getBool("curl_verify_cert")) {
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
	}
}

CURLcode HTTPFetchOngoing::start(CURLM *multi_)
{
	if (!curl)
		return CURLE_FAILED_INIT;

	if (!multi_) {
		// Easy interface (sync)
		return curl_easy_perform(curl);
	}

	// Multi interface (async)
	CURLMcode mres = curl_multi_add_handle(multi_, curl);
	if (mres != CURLM_OK) {
		errorstream << "curl_multi_add_handle"
			<< " returned error code " << mres
			<< std::endl;
		return CURLE_FAILED_INIT;
	}
	multi = multi_; // store for curl_multi_remove_handle
	return CURLE_OK;
}

const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res)
{
	result.succeeded = (res == CURLE_OK);
	result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
	result.data = oss.str();

	// Get HTTP/FTP response code
	result.response_code = 0;
	if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
				&result.response_code) != CURLE_OK)) {
		// We failed to get a return code, make sure it is still 0
		result.response_code = 0;
	}

	if (res != CURLE_OK) {
		errorstream << request.url << " not found ("
			<< curl_easy_strerror(res) << ")"
			<< " (response code " << result.response_code << ")"
			<< std::endl;
	}

	return &result;
}

HTTPFetchOngoing::~HTTPFetchOngoing()
{
	if (multi) {
		CURLMcode mres = curl_multi_remove_handle(multi, curl);
		if (mres != CURLM_OK) {
			errorstream << "curl_multi_remove_handle"
				<< " returned error code " << mres
				<< std::endl;
		}
	}

	// Set safe options for the reusable cURL handle
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
			httpfetch_discardfunction);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
	if (http_header) {
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
		curl_slist_free_all(http_header);
	}
	if (post) {
		curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
		curl_formfree(post);
	}

	// Store the cURL handle for reuse
	pool->free(curl);
}


class CurlFetchThread : public Thread
{
protected:
	enum RequestType {
		RT_FETCH,
		RT_CLEAR,
		RT_WAKEUP,
	};

	struct Request {
		RequestType type;
		HTTPFetchRequest fetch_request;
		Event *event;
	};

	CURLM *m_multi;
	MutexedQueue<Request> m_requests;
	size_t m_parallel_limit;

	// Variables exclusively used within thread
	std::vector<HTTPFetchOngoing*> m_all_ongoing;
	std::list<HTTPFetchRequest> m_queued_fetches;

public:
	CurlFetchThread(int parallel_limit) :
		Thread("CurlFetch")
	{
		if (parallel_limit >= 1)
			m_parallel_limit = parallel_limit;
		else
			m_parallel_limit = 1;
	}

	void requestFetch(const HTTPFetchRequest &fetch_request)
	{
		Request req;
		req.type = RT_FETCH;
		req.fetch_request = fetch_request;
		req.event = NULL;
		m_requests.push_back(req);
	}

	void requestClear(unsigned long caller, Event *event)
	{
		Request req;
		req.type = RT_CLEAR;
		req.fetch_request.caller = caller;
		req.event = event;
		m_requests.push_back(req);
	}

	void requestWakeUp()
	{
		Request req;
		req.type = RT_WAKEUP;
		req.event = NULL;
		m_requests.push_back(req);
	}

protected:
	// Handle a request from some other thread
	// E.g. new fetch; clear fetches for one caller; wake up
	void processRequest(const Request &req)
	{
		if (req.type == RT_FETCH) {
			// New fetch, queue until there are less
			// than m_parallel_limit ongoing fetches
			m_queued_fetches.push_back(req.fetch_request);

			// see processQueued() for what happens next

		}
		else if (req.type == RT_CLEAR) {
			unsigned long caller = req.fetch_request.caller;

			// Abort all ongoing fetches for the caller
			for (std::vector<HTTPFetchOngoing*>::iterator
					it = m_all_ongoing.begin();
					it != m_all_ongoing.end();) {
				if ((*it)->getRequest().caller == caller) {
					delete (*it);
					it = m_all_ongoing.erase(it);
				} else {
					++it;
				}
			}

			// Also abort all queued fetches for the caller
			for (std::list<HTTPFetchRequest>::iterator
					it = m_queued_fetches.begin();
					it != m_queued_fetches.end();) {
				if ((*it).caller == caller)
					it = m_queued_fetches.erase(it);
				else
					++it;
			}
		}
		else if (req.type == RT_WAKEUP) {
			// Wakeup: Nothing to do, thread is awake at this point
		}

		if (req.event != NULL)
			req.event->signal();
	}

	// Start new ongoing fetches if m_parallel_limit allows
	void processQueued(CurlHandlePool *pool)
	{
		while (m_all_ongoing.size() < m_parallel_limit &&
				!m_queued_fetches.empty()) {
			HTTPFetchRequest request = m_queued_fetches.front();
			m_queued_fetches.pop_front();

			// Create ongoing fetch data and make a cURL handle
			// Set cURL options based on HTTPFetchRequest
			HTTPFetchOngoing *ongoing =
				new HTTPFetchOngoing(request, pool);

			// Initiate the connection (curl_multi_add_handle)
			CURLcode res = ongoing->start(m_multi);
			if (res == CURLE_OK) {
				m_all_ongoing.push_back(ongoing);
			}
			else {
				httpfetch_deliver_result(*ongoing->complete(res));
				delete ongoing;
			}
		}
	}

	// Process CURLMsg (indicates completion of a fetch)
	void processCurlMessage(CURLMsg *msg)
	{
		// Determine which ongoing fetch the message pertains to
		size_t i = 0;
		bool found = false;
		for (i = 0; i < m_all_ongoing.size(); ++i) {
			if (m_all_ongoing[i]->getEasyHandle() == msg->easy_handle) {
				found = true;
				break;
			}
		}
		if (msg->msg == CURLMSG_DONE && found) {
			// m_all_ongoing[i] succeeded or failed.
			HTTPFetchOngoing *ongoing = m_all_ongoing[i];
			httpfetch_deliver_result(*ongoing->complete(msg->data.result));
			delete ongoing;
			m_all_ongoing.erase(m_all_ongoing.begin() + i);
		}
	}

	// Wait for a request from another thread, or timeout elapses
	void waitForRequest(long timeout)
	{
		if (m_queued_fetches.empty()) {
			try {
				Request req = m_requests.pop_front(timeout);
				processRequest(req);
			}
			catch (ItemNotFoundException &e) {}
		}
	}

	// Wait until some IO happens, or timeout elapses
	void waitForIO(long timeout)
	{
		fd_set read_fd_set;
		fd_set write_fd_set;
		fd_set exc_fd_set;
		int max_fd;
		long select_timeout = -1;
		struct timeval select_tv;
		CURLMcode mres;

		FD_ZERO(&read_fd_set);
		FD_ZERO(&write_fd_set);
		FD_ZERO(&exc_fd_set);

		mres = curl_multi_fdset(m_multi, &read_fd_set,
				&write_fd_set, &exc_fd_set, &max_fd);
		if (mres != CURLM_OK) {
			errorstream<<"curl_multi_fdset"
				<<" returned error code "<<mres
				<<std::endl;
			select_timeout = 0;
		}

		mres = curl_multi_timeout(m_multi, &select_timeout);
		if (mres != CURLM_OK) {
			errorstream<<"curl_multi_timeout"
				<<" returned error code "<<mres
				<<std::endl;
			select_timeout = 0;
		}

		// Limit timeout so new requests get through
		if (select_timeout < 0 || select_timeout > timeout)
			select_timeout = timeout;

		if (select_timeout > 0) {
			// in Winsock it is forbidden to pass three empty
			// fd_sets to select(), so in that case use sleep_ms
			if (max_fd != -1) {
				select_tv.tv_sec = select_timeout / 1000;
				select_tv.tv_usec = (select_timeout % 1000) * 1000;
				int retval = select(max_fd + 1, &read_fd_set,
						&write_fd_set, &exc_fd_set,
						&select_tv);
				if (retval == -1) {
					#ifdef _WIN32
					errorstream<<"select returned error code "
						<<WSAGetLastError()<<std::endl;
					#else
					errorstream<<"select returned error code "
						<<errno<<std::endl;
					#endif
				}
			}
			else {
				sleep_ms(select_timeout);
			}
		}
	}

	void *run()
	{
		DSTACK(FUNCTION_NAME);

		CurlHandlePool pool;

		m_multi = curl_multi_init();
		if (m_multi == NULL) {
			errorstream<<"curl_multi_init returned NULL\n";
			return NULL;
		}

		FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");

		while (!stopRequested()) {
			BEGIN_DEBUG_EXCEPTION_HANDLER

			/*
				Handle new async requests
			*/

			while (!m_requests.empty()) {
				Request req = m_requests.pop_frontNoEx();
				processRequest(req);
			}
			processQueued(&pool);

			/*
				Handle ongoing async requests
			*/

			int still_ongoing = 0;
			while (curl_multi_perform(m_multi, &still_ongoing) ==
					CURLM_CALL_MULTI_PERFORM)
				/* noop */;

			/*
				Handle completed async requests
			*/
			if (still_ongoing < (int) m_all_ongoing.size()) {
				CURLMsg *msg;
				int msgs_in_queue;
				msg = curl_multi_info_read(m_multi, &msgs_in_queue);
				while (msg != NULL) {
					processCurlMessage(msg);
					msg = curl_multi_info_read(m_multi, &msgs_in_queue);
				}
			}

			/*
				If there are ongoing requests, wait for data
				(with a timeout of 100ms so that new requests
				can be processed).

				If no ongoing requests, wait for a new request.
				(Possibly an empty request that signals
				that the thread should be stopped.)
			*/
			if (m_all_ongoing.empty())
				waitForRequest(100000000);
			else
				waitForIO(100);

			END_DEBUG_EXCEPTION_HANDLER
		}

		// Call curl_multi_remove_handle and cleanup easy handles
		for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
			delete m_all_ongoing[i];
		}
		m_all_ongoing.clear();

		m_queued_fetches.clear();

		CURLMcode mres = curl_multi_cleanup(m_multi);
		if (mres != CURLM_OK) {
			errorstream<<"curl_multi_cleanup"
				<<" returned error code "<<mres
				<<std::endl;
		}

		return NULL;
	}
};

CurlFetchThread *g_httpfetch_thread = NULL;

void httpfetch_init(int parallel_limit)
{
	verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
			<<std::endl;

	CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
	FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");

	g_httpfetch_thread = new CurlFetchThread(parallel_limit);

	// Initialize g_callerid_randomness for httpfetch_caller_alloc_secure
	u64 randbuf[2];
	porting::secure_rand_fill_buf(randbuf, sizeof(u64) * 2);
	g_callerid_randomness = PcgRandom(randbuf[0], randbuf[1]);
}

void httpfetch_cleanup()
{
	verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;

	g_httpfetch_thread->stop();
	g_httpfetch_thread->requestWakeUp();
	g_httpfetch_thread->wait();
	delete g_httpfetch_thread;

	curl_global_cleanup();
}

void httpfetch_async(const HTTPFetchRequest &fetch_request)
{
	g_httpfetch_thread->requestFetch(fetch_request);
	if (!g_httpfetch_thread->isRunning())
		g_httpfetch_thread->start();
}

static void httpfetch_request_clear(unsigned long caller)
{
	if (g_httpfetch_thread->isRunning()) {
		Event event;
		g_httpfetch_thread->requestClear(caller, &event);
		event.wait();
	} else {
		g_httpfetch_thread->requestClear(caller, NULL);
	}
}

void httpfetch_sync(const HTTPFetchRequest &fetch_request,
		HTTPFetchResult &fetch_result)
{
	// Create ongoing fetch data and make a cURL handle
	// Set cURL options based on HTTPFetchRequest
	CurlHandlePool pool;
	HTTPFetchOngoing ongoing(fetch_request, &pool);
	// Do the fetch (curl_easy_perform)
	CURLcode res = ongoing.start(NULL);
	// Update fetch result
	fetch_result = *ongoing.complete(res);
}

#else  // USE_CURL

/*
	USE_CURL is off:

	Dummy httpfetch implementation that always returns an error.
*/

void httpfetch_init(int parallel_limit)
{
}

void httpfetch_cleanup()
{
}

void httpfetch_async(const HTTPFetchRequest &fetch_request)
{
	errorstream << "httpfetch_async: unable to fetch " << fetch_request.url
			<< " because USE_CURL=0" << std::endl;

	HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc.
	httpfetch_deliver_result(fetch_result);
}

static void httpfetch_request_clear(unsigned long caller)
{
}

void httpfetch_sync(const HTTPFetchRequest &fetch_request,
		HTTPFetchResult &fetch_result)
{
	errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url
			<< " because USE_CURL=0" << std::endl;

	fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc.
}

#endif  // USE_CURL
>"NodeTimer interval"); gettext("Length of time between NodeTimer execution cycles"); gettext("Ignore world errors"); gettext("If enabled, invalid world data won't cause the server to shut down.\nOnly enable this if you know what you are doing."); gettext("Liquid loop max"); gettext("Max liquids processed per step."); gettext("Liquid queue purge time"); gettext("The time (in seconds) that the liquids queue may grow beyond processing\ncapacity until an attempt is made to decrease its size by dumping old queue\nitems. A value of 0 disables the functionality."); gettext("Liquid update tick"); gettext("Liquid update interval in seconds."); gettext("block send optimize distance"); gettext("At this distance the server will aggressively optimize which blocks are sent to clients.\nSmall values potentially improve performance a lot, at the expense of visible rendering glitches.\n(some blocks will not be rendered under water and in caves, as well as sometimes on land)\nSetting this to a value greater than max_block_send_distance disables this optimization.\nStated in mapblocks (16 nodes)"); gettext("Mapgen"); gettext("Mapgen name"); gettext("Name of map generator to be used when creating a new world.\nCreating a world in the main menu will override this."); gettext("Water level"); gettext("Water surface level of the world."); gettext("Max block generate distance"); gettext("From how far blocks are generated for clients, stated in mapblocks (16 nodes)."); gettext("Map generation limit"); gettext("Where the map generator stops.\nPlease note:\n- Limited to 31000 (setting above has no effect)\n- The map generator works in groups of 80x80x80 nodes (5x5x5 MapBlocks).\n- Those groups have an offset of -32, -32 nodes from the origin.\n- Only groups which are within the map_generation_limit are generated"); gettext("Mapgen flags"); gettext("Global map generation attributes.\nIn Mapgen v6 the 'decorations' flag controls all decorations except trees\nand junglegrass, in all other mapgens this flag controls all decorations.\nFlags that are not specified in the flag string are not modified from the default.\nFlags starting with 'no' are used to explicitly disable them."); gettext("Advanced"); gettext("Chunk size"); gettext("Size of chunks to be generated at once by mapgen, stated in mapblocks (16 nodes)."); gettext("Mapgen debug"); gettext("Dump the mapgen debug infos."); gettext("Absolute limit of emerge queues"); gettext("Maximum number of blocks that can be queued for loading."); gettext("Limit of emerge queues on disk"); gettext("Maximum number of blocks to be queued that are to be loaded from file.\nSet to blank for an appropriate amount to be chosen automatically."); gettext("Limit of emerge queues to generate"); gettext("Maximum number of blocks to be queued that are to be generated.\nSet to blank for an appropriate amount to be chosen automatically."); gettext("Number of emerge threads"); gettext("Number of emerge threads to use. Make this field blank, or increase this number\nto use multiple threads. On multiprocessor systems, this will improve mapgen speed greatly\nat the cost of slightly buggy caves."); gettext("Mapgen biome heat noise parameters"); gettext("Noise parameters for biome API temperature, humidity and biome blend."); gettext("Mapgen heat blend noise parameters"); gettext("Mapgen biome humidity noise parameters"); gettext("Mapgen biome humidity blend noise parameters"); gettext("Mapgen v5"); gettext("Mapgen v5 cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Mapgen v5 filler depth noise parameters"); gettext("Mapgen v5 factor noise parameters"); gettext("Mapgen v5 height noise parameters"); gettext("Mapgen v5 cave1 noise parameters"); gettext("Mapgen v5 cave2 noise parameters"); gettext("Mapgen v6"); gettext("Mapgen v6 flags"); gettext("Map generation attributes specific to Mapgen v6.\nWhen snowbiomes are enabled jungles are automatically enabled, the 'jungles' flag is ignored.\nFlags that are not specified in the flag string are not modified from the default.\nFlags starting with 'no' are used to explicitly disable them."); gettext("Mapgen v6 desert frequency"); gettext("Controls size of deserts and beaches in Mapgen v6.\nWhen snowbiomes are enabled 'mgv6_freq_desert' is ignored."); gettext("Mapgen v6 beach frequency"); gettext("Mapgen v6 terrain base noise parameters"); gettext("Mapgen v6 terrain altitude noise parameters"); gettext("Mapgen v6 steepness noise parameters"); gettext("Mapgen v6 height select noise parameters"); gettext("Mapgen v6 mud noise parameters"); gettext("Mapgen v6 beach noise parameters"); gettext("Mapgen v6 biome noise parameters"); gettext("Mapgen v6 cave noise parameters"); gettext("Mapgen v6 humidity noise parameters"); gettext("Mapgen v6 trees noise parameters"); gettext("Mapgen v6 apple trees noise parameters"); gettext("Mapgen v7"); gettext("Mapgen v7 flags"); gettext("Map generation attributes specific to Mapgen v7.\nThe 'ridges' flag enables the rivers.\nFloatlands are currently experimental and subject to change.\nFlags that are not specified in the flag string are not modified from the default.\nFlags starting with 'no' are used to explicitly disable them."); gettext("Mapgen v7 cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Mapgen v7 floatland mountain density"); gettext("Controls the density of floatland mountain terrain.\nIs an offset added to the 'np_mountain' noise value."); gettext("Mapgen v7 floatland mountain height"); gettext("Typical maximum height, above and below midpoint, of floatland mountain terrain."); gettext("Mapgen v7 floatland level"); gettext("Y-level of floatland midpoint and lake surface."); gettext("Mapgen v7 shadow limit"); gettext("Y-level to which floatland shadows extend."); gettext("Mapgen v7 terrain base noise parameters"); gettext("Mapgen v7 terrain altitude noise parameters"); gettext("Mapgen v7 terrain persistation noise parameters"); gettext("Mapgen v7 height select noise parameters"); gettext("Mapgen v7 filler depth noise parameters"); gettext("Mapgen v7 mount height noise parameters"); gettext("Mapgen v7 river course noise parameters"); gettext("Mapgen v7 floatland base terrain noise parameters"); gettext("Mapgen v7 floatland base terrain height noise parameters"); gettext("Mapgen v7 mountain noise parameters"); gettext("Mapgen v7 river channel wall noise parameters"); gettext("Mapgen v7 cave1 noise parameters"); gettext("Mapgen v7 cave2 noise parameters"); gettext("Mapgen flat"); gettext("Mapgen flat flags"); gettext("Map generation attributes specific to Mapgen flat.\nOccasional lakes and hills can be added to the flat world.\nFlags that are not specified in the flag string are not modified from the default.\nFlags starting with 'no' are used to explicitly disable them."); gettext("Mapgen flat ground level"); gettext("Y of flat ground."); gettext("Mapgen flat large cave depth"); gettext("Y of upper limit of large pseudorandom caves."); gettext("Mapgen flat cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Mapgen flat lake threshold"); gettext("Terrain noise threshold for lakes.\nControls proportion of world area covered by lakes.\nAdjust towards 0.0 for a larger proportion."); gettext("Mapgen flat lake steepness"); gettext("Controls steepness/depth of lake depressions."); gettext("Mapgen flat hill threshold"); gettext("Terrain noise threshold for hills.\nControls proportion of world area covered by hills.\nAdjust towards 0.0 for a larger proportion."); gettext("Mapgen flat hill steepness"); gettext("Controls steepness/height of hills."); gettext("Mapgen flat terrain noise parameters"); gettext("Determines terrain shape.\nThe 3 numbers in brackets control the scale of the\nterrain, the 3 numbers should be identical."); gettext("Mapgen flat filler depth noise parameters"); gettext("Mapgen flat cave1 noise parameters"); gettext("Mapgen flat cave2 noise parameters"); gettext("Mapgen fractal"); gettext("Mapgen fractal cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Mapgen fractal fractal"); gettext("Choice of 18 fractals from 9 formulas.\n1 = 4D \"Roundy\" mandelbrot set.\n2 = 4D \"Roundy\" julia set.\n3 = 4D \"Squarry\" mandelbrot set.\n4 = 4D \"Squarry\" julia set.\n5 = 4D \"Mandy Cousin\" mandelbrot set.\n6 = 4D \"Mandy Cousin\" julia set.\n7 = 4D \"Variation\" mandelbrot set.\n8 = 4D \"Variation\" julia set.\n9 = 3D \"Mandelbrot/Mandelbar\" mandelbrot set.\n10 = 3D \"Mandelbrot/Mandelbar\" julia set.\n11 = 3D \"Christmas Tree\" mandelbrot set.\n12 = 3D \"Christmas Tree\" julia set.\n13 = 3D \"Mandelbulb\" mandelbrot set.\n14 = 3D \"Mandelbulb\" julia set.\n15 = 3D \"Cosine Mandelbulb\" mandelbrot set.\n16 = 3D \"Cosine Mandelbulb\" julia set.\n17 = 4D \"Mandelbulb\" mandelbrot set.\n18 = 4D \"Mandelbulb\" julia set."); gettext("Mapgen fractal iterations"); gettext("Iterations of the recursive function.\nControls the amount of fine detail."); gettext("Mapgen fractal scale"); gettext("Approximate (X,Y,Z) scale of fractal in nodes."); gettext("Mapgen fractal offset"); gettext("(X,Y,Z) offset of fractal from world centre in units of 'scale'.\nUsed to move a suitable spawn area of low land close to (0, 0).\nThe default is suitable for mandelbrot sets, it needs to be edited for julia sets.\nRange roughly -2 to 2. Multiply by 'scale' for offset in nodes."); gettext("Mapgen fractal slice w"); gettext("W co-ordinate of the generated 3D slice of a 4D fractal.\nDetermines which 3D slice of the 4D shape is generated.\nHas no effect on 3D fractals.\nRange roughly -2 to 2."); gettext("Mapgen fractal julia x"); gettext("Julia set only: X component of hypercomplex constant determining julia shape.\nRange roughly -2 to 2."); gettext("Mapgen fractal julia y"); gettext("Julia set only: Y component of hypercomplex constant determining julia shape.\nRange roughly -2 to 2."); gettext("Mapgen fractal julia z"); gettext("Julia set only: Z component of hypercomplex constant determining julia shape.\nRange roughly -2 to 2."); gettext("Mapgen fractal julia w"); gettext("Julia set only: W component of hypercomplex constant determining julia shape.\nHas no effect on 3D fractals.\nRange roughly -2 to 2."); gettext("Mapgen fractal seabed noise parameters"); gettext("Mapgen fractal filler depth noise parameters"); gettext("Mapgen fractal cave1 noise parameters"); gettext("Mapgen fractal cave2 noise parameters"); gettext("Mapgen Valleys"); gettext("General"); gettext("Valleys C Flags"); gettext("Map generation attributes specific to Mapgen Valleys.\n'altitude_chill' makes higher elevations colder, which may cause biome issues.\n'humid_rivers' modifies the humidity around rivers and in areas where water would tend to pool,\nit may interfere with delicately adjusted biomes.\nFlags that are not specified in the flag string are not modified from the default.\nFlags starting with 'no' are used to explicitly disable them."); gettext("Altitude Chill"); gettext("The altitude at which temperature drops by 20C"); gettext("Large cave depth"); gettext("Depth below which you'll find large caves."); gettext("Lava Features"); gettext("Creates unpredictable lava features in caves.\nThese can make mining difficult. Zero disables them. (0-10)"); gettext("Massive cave depth"); gettext("Depth below which you'll find massive caves."); gettext("River Depth"); gettext("How deep to make rivers"); gettext("River Size"); gettext("How wide to make rivers"); gettext("Water Features"); gettext("Creates unpredictable water features in caves.\nThese can make mining difficult. Zero disables them. (0-10)"); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Noises"); gettext("Cave noise #1"); gettext("Caves and tunnels form at the intersection of the two noises"); gettext("Cave noise #2"); gettext("Caves and tunnels form at the intersection of the two noises"); gettext("Filler Depth"); gettext("The depth of dirt or other filler"); gettext("Massive cave noise"); gettext("Massive caves form here."); gettext("River Noise"); gettext("River noise -- rivers occur close to zero"); gettext("Terrain Height"); gettext("Base terrain height"); gettext("Valley Depth"); gettext("Raises terrain to make valleys around the rivers"); gettext("Valley Fill"); gettext("Slope and fill work together to modify the heights"); gettext("Valley Profile"); gettext("Amplifies the valleys"); gettext("Valley Slope"); gettext("Slope and fill work together to modify the heights"); gettext("Security"); gettext("Enable mod security"); gettext("Prevent mods from doing insecure things like running shell commands."); gettext("Trusted mods"); gettext("Comma-separated list of trusted mods that are allowed to access insecure\nfunctions even when mod security is on (via request_insecure_environment())."); gettext("HTTP Mods"); gettext("Comma-separated list of mods that are allowed to access HTTP APIs, which\nallow them to upload and download data to/from the internet."); gettext("Advanced"); gettext("Profiling"); gettext("Load the game profiler"); gettext("Load the game profiler to collect game profiling data.\nProvides a /profiler command to access the compiled profile.\nUseful for mod developers and server operators."); gettext("Default report format"); gettext("The default format in which profiles are being saved,\nwhen calling `/profiler save [format]` without format."); gettext("Report path"); gettext("The file path relative to your worldpath in which profiles will be saved to.\n"); gettext("Instrumentation"); gettext("Entity methods"); gettext("Instrument the methods of entities on registration."); gettext("Active Block Modifiers"); gettext("Instrument the action function of Active Block Modifiers on registration."); gettext("Loading Block Modifiers"); gettext("Instrument the action function of Loading Block Modifiers on registration."); gettext("Chatcommands"); gettext("Instrument chatcommands on registration."); gettext("Global callbacks"); gettext("Instrument global callback functions on registration.\n(anything you pass to a minetest.register_*() function)"); gettext("Advanced"); gettext("Builtin"); gettext("Instrument builtin.\nThis is usually only needed by core/builtin contributors"); gettext("Profiler"); gettext("Have the profiler instrument itself:\n* Instrument an empty function.\nThis estimates the overhead, that instrumentation is adding (+1 function call).\n* Instrument the sampler being used to update the statistics."); gettext("Client and Server"); gettext("Player name"); gettext("Name of the player.\nWhen running a server, clients connecting with this name are admins.\nWhen starting from the main menu, this is overridden."); gettext("Language"); gettext("Set the language. Leave empty to use the system language.\nA restart is required after changing this."); gettext("Debug log level"); gettext("Level of logging to be written to debug.txt:\n- <nothing> (no logging)\n- none (messages with no level)\n- error\n- warning\n- action\n- info\n- verbose"); gettext("IPv6"); gettext("IPv6 support."); gettext("Advanced"); gettext("cURL timeout"); gettext("Default timeout for cURL, stated in milliseconds.\nOnly has an effect if compiled with cURL."); gettext("cURL parallel limit"); gettext("Limits number of parallel HTTP requests. Affects:\n- Media fetch if server uses remote_media setting.\n- Serverlist download and server announcement.\n- Downloads performed by main menu (e.g. mod manager).\nOnly has an effect if compiled with cURL."); gettext("cURL file download timeout"); gettext("Maximum time in ms a file download (e.g. a mod download) may take."); gettext("High-precision FPU"); gettext("Makes DirectX work with LuaJIT. Disable if it causes troubles."); gettext("Main menu script"); gettext("Replaces the default main menu with a custom one."); gettext("Main menu game manager"); gettext("Main menu mod manager"); gettext("Modstore download URL"); gettext("Modstore mods list URL"); gettext("Modstore details URL"); gettext("Engine profiling data print interval"); gettext("Print the engine's profiling data in regular intervals (in seconds). 0 = disable. Useful for developers."); }