25474c725bee6721f99dc2240562842d7b068fdd
[oweals/minetest.git] / src / httpfetch.cpp
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 <iostream>
22 #include <sstream>
23 #include <list>
24 #include <map>
25 #include <errno.h>
26 #include "jthread/jevent.h"
27 #include "config.h"
28 #include "exceptions.h"
29 #include "debug.h"
30 #include "log.h"
31 #include "util/container.h"
32 #include "util/thread.h"
33 #include "socket.h" // for select()
34
35 JMutex g_httpfetch_mutex;
36 std::map<unsigned long, std::list<HTTPFetchResult> > g_httpfetch_results;
37
38 static void httpfetch_deliver_result(const HTTPFetchResult &fetchresult)
39 {
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);
44         }
45 }
46
47 static void httpfetch_request_clear(unsigned long caller);
48
49 unsigned long httpfetch_caller_alloc()
50 {
51         JMutexAutoLock lock(g_httpfetch_mutex);
52
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 "
60                                         <<caller<<std::endl;
61                         // Access element to create it
62                         g_httpfetch_results[caller];
63                         return caller;
64                 }
65         }
66
67         assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
68         return discard;
69 }
70
71 void httpfetch_caller_free(unsigned long caller)
72 {
73         verbosestream<<"httpfetch_caller_free: freeing "
74                         <<caller<<std::endl;
75
76         httpfetch_request_clear(caller);
77         if (caller != HTTPFETCH_DISCARD) {
78                 JMutexAutoLock lock(g_httpfetch_mutex);
79                 g_httpfetch_results.erase(caller);
80         }
81 }
82
83 bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetchresult)
84 {
85         JMutexAutoLock lock(g_httpfetch_mutex);
86
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())
91                 return false;
92
93         // Check that result queue is nonempty
94         std::list<HTTPFetchResult> &callerresults = it->second;
95         if (callerresults.empty())
96                 return false;
97
98         // Pop first result
99         fetchresult = callerresults.front();
100         callerresults.pop_front();
101         return true;
102 }
103
104 #if USE_CURL
105 #include <curl/curl.h>
106
107 /*
108         USE_CURL is on: use cURL based httpfetch implementation
109 */
110
111 static size_t httpfetch_writefunction(
112                 char *ptr, size_t size, size_t nmemb, void *userdata)
113 {
114         std::ostringstream *stream = (std::ostringstream*)userdata;
115         size_t count = size * nmemb;
116         stream->write(ptr, count);
117         return count;
118 }
119
120 static size_t httpfetch_discardfunction(
121                 char *ptr, size_t size, size_t nmemb, void *userdata)
122 {
123         return size * nmemb;
124 }
125
126 class CurlHandlePool
127 {
128         std::list<CURL*> handles;
129
130 public:
131         CurlHandlePool() {}
132         ~CurlHandlePool()
133         {
134                 for (std::list<CURL*>::iterator it = handles.begin();
135                                 it != handles.end(); ++it) {
136                         curl_easy_cleanup(*it);
137                 }
138         }
139         CURL * alloc()
140         {
141                 CURL *curl;
142                 if (handles.empty()) {
143                         curl = curl_easy_init();
144                         if (curl == NULL) {
145                                 errorstream<<"curl_easy_init returned NULL"<<std::endl;
146                         }
147                 }
148                 else {
149                         curl = handles.front();
150                         handles.pop_front();
151                 }
152                 return curl;
153         }
154         void free(CURL *handle)
155         {
156                 if (handle)
157                         handles.push_back(handle);
158         }
159 };
160
161 struct HTTPFetchOngoing
162 {
163         CurlHandlePool *pool;
164         CURL *curl;
165         CURLM *multi;
166         HTTPFetchRequest request;
167         HTTPFetchResult result;
168         std::ostringstream oss;
169         char *post_fields;
170         struct curl_slist *httpheader;
171
172         HTTPFetchOngoing(HTTPFetchRequest request_, CurlHandlePool *pool_):
173                 pool(pool_),
174                 curl(NULL),
175                 multi(NULL),
176                 request(request_),
177                 result(request_),
178                 oss(std::ios::binary),
179                 httpheader(NULL)
180         {
181                 curl = pool->alloc();
182                 if (curl != NULL) {
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);
188
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.
193                         long protocols =
194                                 CURLPROTO_HTTP |
195                                 CURLPROTO_HTTPS |
196                                 CURLPROTO_FTP |
197                                 CURLPROTO_FTPS;
198                         curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols);
199                         curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols);
200 #endif
201
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,
206                                         request.timeout);
207                         curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
208                                         request.connect_timeout);
209
210                         if (request.useragent != "")
211                                 curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
212
213                         // Set up a write callback that writes to the
214                         // ostringstream ongoing->oss, unless the data
215                         // is to be discarded
216                         if (request.caller == HTTPFETCH_DISCARD) {
217                                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
218                                                 httpfetch_discardfunction);
219                                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
220                         }
221                         else {
222                                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
223                                                 httpfetch_writefunction);
224                                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
225                         }
226                         // Set POST (or GET) data
227                         if (request.post_fields.empty()) {
228                                 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
229                         }
230                         else {
231                                 curl_easy_setopt(curl, CURLOPT_POST, 1);
232                                 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
233                                                 request.post_fields.size());
234                                 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
235                                                 request.post_fields.c_str());
236                                 // request.post_fields must now *never* be
237                                 // modified until CURLOPT_POSTFIELDS is cleared
238                         }
239                         // Set additional HTTP headers
240                         for (size_t i = 0; i < request.extra_headers.size(); ++i) {
241                                 httpheader = curl_slist_append(
242                                         httpheader,
243                                         request.extra_headers[i].c_str());
244                         }
245                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
246                 }
247         }
248
249         CURLcode start(CURLM *multi_)
250         {
251                 if (curl == NULL)
252                         return CURLE_FAILED_INIT;
253
254                 if (multi_) {
255                         // Multi interface (async)
256                         CURLMcode mres = curl_multi_add_handle(multi_, curl);
257                         if (mres != CURLM_OK) {
258                                 errorstream<<"curl_multi_add_handle"
259                                         <<" returned error code "<<mres
260                                         <<std::endl;
261                                 return CURLE_FAILED_INIT;
262                         }
263                         multi = multi_; // store for curl_multi_remove_handle
264                         return CURLE_OK;
265                 }
266                 else {
267                         // Easy interface (sync)
268                         return curl_easy_perform(curl);
269                 }
270         }
271
272         void complete(CURLcode res)
273         {
274                 result.succeeded = (res == CURLE_OK);
275                 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
276                 result.data = oss.str();
277
278                 // Get HTTP/FTP response code
279                 result.response_code = 0;
280                 if (curl != NULL) {
281                         if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
282                                         &result.response_code) != CURLE_OK) {
283                                 result.response_code = 0;
284                         }
285                 }
286
287                 if (res != CURLE_OK) {
288                         infostream<<request.url<<" not found ("
289                                 <<curl_easy_strerror(res)<<")"
290                                 <<" (response code "<<result.response_code<<")"
291                                 <<std::endl;
292                 }
293         }
294
295         ~HTTPFetchOngoing()
296         {
297                 if (multi != NULL) {
298                         CURLMcode mres = curl_multi_remove_handle(multi, curl);
299                         if (mres != CURLM_OK) {
300                                 errorstream<<"curl_multi_remove_handle"
301                                         <<" returned error code "<<mres
302                                         <<std::endl;
303                         }
304                 }
305
306                 // Set safe options for the reusable cURL handle
307                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
308                                 httpfetch_discardfunction);
309                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
310                 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
311                 if (httpheader != NULL) {
312                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
313                         curl_slist_free_all(httpheader);
314                 }
315
316                 // Store the cURL handle for reuse
317                 pool->free(curl);
318         }
319 };
320
321 class CurlFetchThread : public SimpleThread
322 {
323 protected:
324         enum RequestType {
325                 RT_FETCH,
326                 RT_CLEAR,
327                 RT_WAKEUP,
328         };
329
330         struct Request {
331                 RequestType type;
332                 HTTPFetchRequest fetchrequest;
333                 Event *event;
334         };
335
336         CURLM *m_multi;
337         MutexedQueue<Request> m_requests;
338         size_t m_parallel_limit;
339
340         // Variables exclusively used within thread
341         std::vector<HTTPFetchOngoing*> m_all_ongoing;
342         std::list<HTTPFetchRequest> m_queued_fetches;
343
344 public:
345         CurlFetchThread(int parallel_limit)
346         {
347                 if (parallel_limit >= 1)
348                         m_parallel_limit = parallel_limit;
349                 else
350                         m_parallel_limit = 1;
351         }
352
353         void requestFetch(const HTTPFetchRequest &fetchrequest)
354         {
355                 Request req;
356                 req.type = RT_FETCH;
357                 req.fetchrequest = fetchrequest;
358                 req.event = NULL;
359                 m_requests.push_back(req);
360         }
361
362         void requestClear(unsigned long caller, Event *event)
363         {
364                 Request req;
365                 req.type = RT_CLEAR;
366                 req.fetchrequest.caller = caller;
367                 req.event = event;
368                 m_requests.push_back(req);
369         }
370
371         void requestWakeUp()
372         {
373                 Request req;
374                 req.type = RT_WAKEUP;
375                 req.event = NULL;
376                 m_requests.push_back(req);
377         }
378
379 protected:
380         // Handle a request from some other thread
381         // E.g. new fetch; clear fetches for one caller; wake up
382         void processRequest(const Request &req)
383         {
384                 if (req.type == RT_FETCH) {
385                         // New fetch, queue until there are less
386                         // than m_parallel_limit ongoing fetches
387                         m_queued_fetches.push_back(req.fetchrequest);
388
389                         // see processQueued() for what happens next
390
391                 }
392                 else if (req.type == RT_CLEAR) {
393                         unsigned long caller = req.fetchrequest.caller;
394
395                         // Abort all ongoing fetches for the caller
396                         for (std::vector<HTTPFetchOngoing*>::iterator
397                                         it = m_all_ongoing.begin();
398                                         it != m_all_ongoing.end();) {
399                                 if ((*it)->request.caller == caller) {
400                                         delete (*it);
401                                         it = m_all_ongoing.erase(it);
402                                 }
403                                 else
404                                         ++it;
405                         }
406
407                         // Also abort all queued fetches for the caller
408                         for (std::list<HTTPFetchRequest>::iterator
409                                         it = m_queued_fetches.begin();
410                                         it != m_queued_fetches.end();) {
411                                 if ((*it).caller == caller)
412                                         it = m_queued_fetches.erase(it);
413                                 else
414                                         ++it;
415                         }
416                 }
417                 else if (req.type == RT_WAKEUP) {
418                         // Wakeup: Nothing to do, thread is awake at this point
419                 }
420
421                 if (req.event != NULL)
422                         req.event->signal();
423         }
424
425         // Start new ongoing fetches if m_parallel_limit allows
426         void processQueued(CurlHandlePool *pool)
427         {
428                 while (m_all_ongoing.size() < m_parallel_limit &&
429                                 !m_queued_fetches.empty()) {
430                         HTTPFetchRequest request = m_queued_fetches.front();
431                         m_queued_fetches.pop_front();
432
433                         // Create ongoing fetch data and make a cURL handle
434                         // Set cURL options based on HTTPFetchRequest
435                         HTTPFetchOngoing *ongoing =
436                                 new HTTPFetchOngoing(request, pool);
437
438                         // Initiate the connection (curl_multi_add_handle)
439                         CURLcode res = ongoing->start(m_multi);
440                         if (res == CURLE_OK) {
441                                 m_all_ongoing.push_back(ongoing);
442                         }
443                         else {
444                                 ongoing->complete(res);
445                                 httpfetch_deliver_result(ongoing->result);
446                                 delete ongoing;
447                         }
448                 }
449         }
450
451         // Process CURLMsg (indicates completion of a fetch)
452         void processCurlMessage(CURLMsg *msg)
453         {
454                 // Determine which ongoing fetch the message pertains to
455                 size_t i = 0;
456                 bool found = false;
457                 for (i = 0; i < m_all_ongoing.size(); ++i) {
458                         if (m_all_ongoing[i]->curl == msg->easy_handle) {
459                                 found = true;
460                                 break;
461                         }
462                 }
463                 if (msg->msg == CURLMSG_DONE && found) {
464                         // m_all_ongoing[i] succeeded or failed.
465                         HTTPFetchOngoing *ongoing = m_all_ongoing[i];
466                         ongoing->complete(msg->data.result);
467                         httpfetch_deliver_result(ongoing->result);
468                         delete ongoing;
469                         m_all_ongoing.erase(m_all_ongoing.begin() + i);
470                 }
471         }
472
473         // Wait for a request from another thread, or timeout elapses
474         void waitForRequest(long timeout)
475         {
476                 if (m_queued_fetches.empty()) {
477                         try {
478                                 Request req = m_requests.pop_front(timeout);
479                                 processRequest(req);
480                         }
481                         catch (ItemNotFoundException &e) {}
482                 }
483         }
484
485         // Wait until some IO happens, or timeout elapses
486         void waitForIO(long timeout)
487         {
488                 fd_set read_fd_set;
489                 fd_set write_fd_set;
490                 fd_set exc_fd_set;
491                 int max_fd;
492                 long select_timeout = -1;
493                 struct timeval select_tv;
494                 CURLMcode mres;
495
496                 FD_ZERO(&read_fd_set);
497                 FD_ZERO(&write_fd_set);
498                 FD_ZERO(&exc_fd_set);
499
500                 mres = curl_multi_fdset(m_multi, &read_fd_set,
501                                 &write_fd_set, &exc_fd_set, &max_fd);
502                 if (mres != CURLM_OK) {
503                         errorstream<<"curl_multi_fdset"
504                                 <<" returned error code "<<mres
505                                 <<std::endl;
506                         select_timeout = 0;
507                 }
508
509                 mres = curl_multi_timeout(m_multi, &select_timeout);
510                 if (mres != CURLM_OK) {
511                         errorstream<<"curl_multi_timeout"
512                                 <<" returned error code "<<mres
513                                 <<std::endl;
514                         select_timeout = 0;
515                 }
516
517                 // Limit timeout so new requests get through
518                 if (select_timeout < 0 || select_timeout > timeout)
519                         select_timeout = timeout;
520
521                 if (select_timeout > 0) {
522                         select_tv.tv_sec = select_timeout / 1000;
523                         select_tv.tv_usec = (select_timeout % 1000) * 1000;
524                         int retval = select(max_fd + 1, &read_fd_set,
525                                         &write_fd_set, &exc_fd_set,
526                                         &select_tv);
527                         if (retval == -1) {
528                                 #ifdef _WIN32
529                                 errorstream<<"select returned error code "
530                                         <<WSAGetLastError()<<std::endl;
531                                 #else
532                                 errorstream<<"select returned error code "
533                                         <<errno<<std::endl;
534                                 #endif
535                         }
536                 }
537         }
538
539         void * Thread()
540         {
541                 ThreadStarted();
542                 log_register_thread("CurlFetchThread");
543                 DSTACK(__FUNCTION_NAME);
544
545                 CurlHandlePool pool;
546
547                 m_multi = curl_multi_init();
548                 if (m_multi == NULL) {
549                         errorstream<<"curl_multi_init returned NULL\n";
550                         return NULL;
551                 }
552
553                 assert(m_all_ongoing.empty());
554
555                 while (getRun()) {
556                         BEGIN_DEBUG_EXCEPTION_HANDLER
557
558                         /*
559                                 Handle new async requests
560                         */
561
562                         while (!m_requests.empty()) {
563                                 Request req = m_requests.pop_front();
564                                 processRequest(req);
565                         }
566                         processQueued(&pool);
567
568                         /*
569                                 Handle ongoing async requests
570                         */
571
572                         int still_ongoing = 0;
573                         while (curl_multi_perform(m_multi, &still_ongoing) ==
574                                         CURLM_CALL_MULTI_PERFORM)
575                                 /* noop */;
576
577                         /*
578                                 Handle completed async requests
579                         */
580                         if (still_ongoing < (int) m_all_ongoing.size()) {
581                                 CURLMsg *msg;
582                                 int msgs_in_queue;
583                                 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
584                                 while (msg != NULL) {
585                                         processCurlMessage(msg);
586                                         msg = curl_multi_info_read(m_multi, &msgs_in_queue);
587                                 }
588                         }
589
590                         /*
591                                 If there are ongoing requests, wait for data
592                                 (with a timeout of 100ms so that new requests
593                                 can be processed).
594
595                                 If no ongoing requests, wait for a new request.
596                                 (Possibly an empty request that signals
597                                 that the thread should be stopped.)
598                         */
599                         if (m_all_ongoing.empty())
600                                 waitForRequest(100000000);
601                         else
602                                 waitForIO(100);
603
604                         END_DEBUG_EXCEPTION_HANDLER(errorstream)
605                 }
606
607                 // Call curl_multi_remove_handle and cleanup easy handles
608                 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
609                         delete m_all_ongoing[i];
610                 }
611                 m_all_ongoing.clear();
612
613                 m_queued_fetches.clear();
614
615                 CURLMcode mres = curl_multi_cleanup(m_multi);
616                 if (mres != CURLM_OK) {
617                         errorstream<<"curl_multi_cleanup"
618                                 <<" returned error code "<<mres
619                                 <<std::endl;
620                 }
621
622                 return NULL;
623         }
624 };
625
626 CurlFetchThread *g_httpfetch_thread = NULL;
627
628 void httpfetch_init(int parallel_limit)
629 {
630         verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
631                         <<std::endl;
632
633         CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
634         assert(res == CURLE_OK);
635
636         g_httpfetch_thread = new CurlFetchThread(parallel_limit);
637 }
638
639 void httpfetch_cleanup()
640 {
641         verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
642
643         g_httpfetch_thread->setRun(false);
644         g_httpfetch_thread->requestWakeUp();
645         g_httpfetch_thread->stop();
646         delete g_httpfetch_thread;
647
648         curl_global_cleanup();
649 }
650
651 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
652 {
653         g_httpfetch_thread->requestFetch(fetchrequest);
654         if (!g_httpfetch_thread->IsRunning())
655                 g_httpfetch_thread->Start();
656 }
657
658 static void httpfetch_request_clear(unsigned long caller)
659 {
660         if (g_httpfetch_thread->IsRunning()) {
661                 Event event;
662                 g_httpfetch_thread->requestClear(caller, &event);
663                 event.wait();
664         }
665         else {
666                 g_httpfetch_thread->requestClear(caller, NULL);
667         }
668 }
669
670 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
671                 HTTPFetchResult &fetchresult)
672 {
673         // Create ongoing fetch data and make a cURL handle
674         // Set cURL options based on HTTPFetchRequest
675         CurlHandlePool pool;
676         HTTPFetchOngoing ongoing(fetchrequest, &pool);
677         // Do the fetch (curl_easy_perform)
678         CURLcode res = ongoing.start(NULL);
679         // Update fetchresult
680         ongoing.complete(res);
681         fetchresult = ongoing.result;
682 }
683
684 #else  // USE_CURL
685
686 /*
687         USE_CURL is off:
688
689         Dummy httpfetch implementation that always returns an error.
690 */
691
692 void httpfetch_init(int parallel_limit)
693 {
694 }
695
696 void httpfetch_cleanup()
697 {
698 }
699
700 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
701 {
702         errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
703                         <<" because USE_CURL=0"<<std::endl;
704
705         HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
706         httpfetch_deliver_result(fetchresult);
707 }
708
709 static void httpfetch_request_clear(unsigned long caller)
710 {
711 }
712
713 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
714                 HTTPFetchResult &fetchresult)
715 {
716         errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
717                         <<" because USE_CURL=0"<<std::endl;
718
719         fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.
720 }
721
722 #endif  // USE_CURL