]> git.lizzy.rs Git - dragonfireclient.git/blob - src/httpfetch.cpp
Implement urlencode and urldecode
[dragonfireclient.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                         // Set up a write callback that writes to the
210                         // ostringstream ongoing->oss, unless the data
211                         // is to be discarded
212                         if (request.caller == HTTPFETCH_DISCARD) {
213                                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
214                                                 httpfetch_discardfunction);
215                                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
216                         }
217                         else {
218                                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
219                                                 httpfetch_writefunction);
220                                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss);
221                         }
222                         // Set POST (or GET) data
223                         if (request.post_fields.empty()) {
224                                 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
225                         }
226                         else {
227                                 curl_easy_setopt(curl, CURLOPT_POST, 1);
228                                 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
229                                                 request.post_fields.size());
230                                 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
231                                                 request.post_fields.c_str());
232                                 // request.post_fields must now *never* be
233                                 // modified until CURLOPT_POSTFIELDS is cleared
234                         }
235                         // Set additional HTTP headers
236                         for (size_t i = 0; i < request.extra_headers.size(); ++i) {
237                                 httpheader = curl_slist_append(
238                                         httpheader,
239                                         request.extra_headers[i].c_str());
240                         }
241                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, httpheader);
242                 }
243         }
244
245         CURLcode start(CURLM *multi_)
246         {
247                 if (curl == NULL)
248                         return CURLE_FAILED_INIT;
249
250                 if (multi_) {
251                         // Multi interface (async)
252                         CURLMcode mres = curl_multi_add_handle(multi_, curl);
253                         if (mres != CURLM_OK) {
254                                 errorstream<<"curl_multi_add_handle"
255                                         <<" returned error code "<<mres
256                                         <<std::endl;
257                                 return CURLE_FAILED_INIT;
258                         }
259                         multi = multi_; // store for curl_multi_remove_handle
260                         return CURLE_OK;
261                 }
262                 else {
263                         // Easy interface (sync)
264                         return curl_easy_perform(curl);
265                 }
266         }
267
268         void complete(CURLcode res)
269         {
270                 result.succeeded = (res == CURLE_OK);
271                 result.timeout = (res == CURLE_OPERATION_TIMEDOUT);
272                 result.data = oss.str();
273
274                 // Get HTTP/FTP response code
275                 result.response_code = 0;
276                 if (curl != NULL) {
277                         if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
278                                         &result.response_code) != CURLE_OK) {
279                                 result.response_code = 0;
280                         }
281                 }
282
283                 if (res != CURLE_OK) {
284                         infostream<<request.url<<" not found ("
285                                 <<curl_easy_strerror(res)<<")"
286                                 <<" (response code "<<result.response_code<<")"
287                                 <<std::endl;
288                 }
289         }
290
291         ~HTTPFetchOngoing()
292         {
293                 if (multi != NULL) {
294                         CURLMcode mres = curl_multi_remove_handle(multi, curl);
295                         if (mres != CURLM_OK) {
296                                 errorstream<<"curl_multi_remove_handle"
297                                         <<" returned error code "<<mres
298                                         <<std::endl;
299                         }
300                 }
301
302                 // Set safe options for the reusable cURL handle
303                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
304                                 httpfetch_discardfunction);
305                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
306                 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
307                 if (httpheader != NULL) {
308                         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
309                         curl_slist_free_all(httpheader);
310                 }
311
312                 // Store the cURL handle for reuse
313                 pool->free(curl);
314         }
315 };
316
317 class CurlFetchThread : public SimpleThread
318 {
319 protected:
320         enum RequestType {
321                 RT_FETCH,
322                 RT_CLEAR,
323                 RT_WAKEUP,
324         };
325
326         struct Request {
327                 RequestType type;
328                 HTTPFetchRequest fetchrequest;
329                 Event *event;
330         };
331
332         CURLM *m_multi;
333         MutexedQueue<Request> m_requests;
334         size_t m_parallel_limit;
335
336         // Variables exclusively used within thread
337         std::vector<HTTPFetchOngoing*> m_all_ongoing;
338         std::list<HTTPFetchRequest> m_queued_fetches;
339
340 public:
341         CurlFetchThread(int parallel_limit)
342         {
343                 if (parallel_limit >= 1)
344                         m_parallel_limit = parallel_limit;
345                 else
346                         m_parallel_limit = 1;
347         }
348
349         void requestFetch(const HTTPFetchRequest &fetchrequest)
350         {
351                 Request req;
352                 req.type = RT_FETCH;
353                 req.fetchrequest = fetchrequest;
354                 req.event = NULL;
355                 m_requests.push_back(req);
356         }
357
358         void requestClear(unsigned long caller, Event *event)
359         {
360                 Request req;
361                 req.type = RT_CLEAR;
362                 req.fetchrequest.caller = caller;
363                 req.event = event;
364                 m_requests.push_back(req);
365         }
366
367         void requestWakeUp()
368         {
369                 Request req;
370                 req.type = RT_WAKEUP;
371                 req.event = NULL;
372                 m_requests.push_back(req);
373         }
374
375 protected:
376         // Handle a request from some other thread
377         // E.g. new fetch; clear fetches for one caller; wake up
378         void processRequest(const Request &req)
379         {
380                 if (req.type == RT_FETCH) {
381                         // New fetch, queue until there are less
382                         // than m_parallel_limit ongoing fetches
383                         m_queued_fetches.push_back(req.fetchrequest);
384
385                         // see processQueued() for what happens next
386
387                 }
388                 else if (req.type == RT_CLEAR) {
389                         unsigned long caller = req.fetchrequest.caller;
390
391                         // Abort all ongoing fetches for the caller
392                         for (std::vector<HTTPFetchOngoing*>::iterator
393                                         it = m_all_ongoing.begin();
394                                         it != m_all_ongoing.end();) {
395                                 if ((*it)->request.caller == caller) {
396                                         delete (*it);
397                                         it = m_all_ongoing.erase(it);
398                                 }
399                                 else
400                                         ++it;
401                         }
402
403                         // Also abort all queued fetches for the caller
404                         for (std::list<HTTPFetchRequest>::iterator
405                                         it = m_queued_fetches.begin();
406                                         it != m_queued_fetches.end();) {
407                                 if ((*it).caller == caller)
408                                         it = m_queued_fetches.erase(it);
409                                 else
410                                         ++it;
411                         }
412                 }
413                 else if (req.type == RT_WAKEUP) {
414                         // Wakeup: Nothing to do, thread is awake at this point
415                 }
416
417                 if (req.event != NULL)
418                         req.event->signal();
419         }
420
421         // Start new ongoing fetches if m_parallel_limit allows
422         void processQueued(CurlHandlePool *pool)
423         {
424                 while (m_all_ongoing.size() < m_parallel_limit &&
425                                 !m_queued_fetches.empty()) {
426                         HTTPFetchRequest request = m_queued_fetches.front();
427                         m_queued_fetches.pop_front();
428
429                         // Create ongoing fetch data and make a cURL handle
430                         // Set cURL options based on HTTPFetchRequest
431                         HTTPFetchOngoing *ongoing =
432                                 new HTTPFetchOngoing(request, pool);
433
434                         // Initiate the connection (curl_multi_add_handle)
435                         CURLcode res = ongoing->start(m_multi);
436                         if (res == CURLE_OK) {
437                                 m_all_ongoing.push_back(ongoing);
438                         }
439                         else {
440                                 ongoing->complete(res);
441                                 httpfetch_deliver_result(ongoing->result);
442                                 delete ongoing;
443                         }
444                 }
445         }
446
447         // Process CURLMsg (indicates completion of a fetch)
448         void processCurlMessage(CURLMsg *msg)
449         {
450                 // Determine which ongoing fetch the message pertains to
451                 size_t i = 0;
452                 bool found = false;
453                 for (i = 0; i < m_all_ongoing.size(); ++i) {
454                         if (m_all_ongoing[i]->curl == msg->easy_handle) {
455                                 found = true;
456                                 break;
457                         }
458                 }
459                 if (msg->msg == CURLMSG_DONE && found) {
460                         // m_all_ongoing[i] succeeded or failed.
461                         HTTPFetchOngoing *ongoing = m_all_ongoing[i];
462                         ongoing->complete(msg->data.result);
463                         httpfetch_deliver_result(ongoing->result);
464                         delete ongoing;
465                         m_all_ongoing.erase(m_all_ongoing.begin() + i);
466                 }
467         }
468
469         // Wait for a request from another thread, or timeout elapses
470         void waitForRequest(long timeout)
471         {
472                 if (m_queued_fetches.empty()) {
473                         try {
474                                 Request req = m_requests.pop_front(timeout);
475                                 processRequest(req);
476                         }
477                         catch (ItemNotFoundException &e) {}
478                 }
479         }
480
481         // Wait until some IO happens, or timeout elapses
482         void waitForIO(long timeout)
483         {
484                 fd_set read_fd_set;
485                 fd_set write_fd_set;
486                 fd_set exc_fd_set;
487                 int max_fd;
488                 long select_timeout = -1;
489                 struct timeval select_tv;
490                 CURLMcode mres;
491
492                 FD_ZERO(&read_fd_set);
493                 FD_ZERO(&write_fd_set);
494                 FD_ZERO(&exc_fd_set);
495
496                 mres = curl_multi_fdset(m_multi, &read_fd_set,
497                                 &write_fd_set, &exc_fd_set, &max_fd);
498                 if (mres != CURLM_OK) {
499                         errorstream<<"curl_multi_fdset"
500                                 <<" returned error code "<<mres
501                                 <<std::endl;
502                         select_timeout = 0;
503                 }
504
505                 mres = curl_multi_timeout(m_multi, &select_timeout);
506                 if (mres != CURLM_OK) {
507                         errorstream<<"curl_multi_timeout"
508                                 <<" returned error code "<<mres
509                                 <<std::endl;
510                         select_timeout = 0;
511                 }
512
513                 // Limit timeout so new requests get through
514                 if (select_timeout < 0 || select_timeout > timeout)
515                         select_timeout = timeout;
516
517                 if (select_timeout > 0) {
518                         select_tv.tv_sec = select_timeout / 1000;
519                         select_tv.tv_usec = (select_timeout % 1000) * 1000;
520                         int retval = select(max_fd + 1, &read_fd_set,
521                                         &write_fd_set, &exc_fd_set,
522                                         &select_tv);
523                         if (retval == -1) {
524                                 #ifdef _WIN32
525                                 errorstream<<"select returned error code "
526                                         <<WSAGetLastError()<<std::endl;
527                                 #else
528                                 errorstream<<"select returned error code "
529                                         <<errno<<std::endl;
530                                 #endif
531                         }
532                 }
533         }
534
535         void * Thread()
536         {
537                 ThreadStarted();
538                 log_register_thread("CurlFetchThread");
539                 DSTACK(__FUNCTION_NAME);
540
541                 CurlHandlePool pool;
542
543                 m_multi = curl_multi_init();
544                 if (m_multi == NULL) {
545                         errorstream<<"curl_multi_init returned NULL\n";
546                         return NULL;
547                 }
548
549                 assert(m_all_ongoing.empty());
550
551                 while (getRun()) {
552                         BEGIN_DEBUG_EXCEPTION_HANDLER
553
554                         /*
555                                 Handle new async requests
556                         */
557
558                         while (!m_requests.empty()) {
559                                 Request req = m_requests.pop_front();
560                                 processRequest(req);
561                         }
562                         processQueued(&pool);
563
564                         /*
565                                 Handle ongoing async requests
566                         */
567
568                         int still_ongoing = 0;
569                         while (curl_multi_perform(m_multi, &still_ongoing) ==
570                                         CURLM_CALL_MULTI_PERFORM)
571                                 /* noop */;
572
573                         /*
574                                 Handle completed async requests
575                         */
576                         if (still_ongoing < (int) m_all_ongoing.size()) {
577                                 CURLMsg *msg;
578                                 int msgs_in_queue;
579                                 msg = curl_multi_info_read(m_multi, &msgs_in_queue);
580                                 while (msg != NULL) {
581                                         processCurlMessage(msg);
582                                         msg = curl_multi_info_read(m_multi, &msgs_in_queue);
583                                 }
584                         }
585
586                         /*
587                                 If there are ongoing requests, wait for data
588                                 (with a timeout of 100ms so that new requests
589                                 can be processed).
590
591                                 If no ongoing requests, wait for a new request.
592                                 (Possibly an empty request that signals
593                                 that the thread should be stopped.)
594                         */
595                         if (m_all_ongoing.empty())
596                                 waitForRequest(100000000);
597                         else
598                                 waitForIO(100);
599
600                         END_DEBUG_EXCEPTION_HANDLER(errorstream)
601                 }
602
603                 // Call curl_multi_remove_handle and cleanup easy handles
604                 for (size_t i = 0; i < m_all_ongoing.size(); ++i) {
605                         delete m_all_ongoing[i];
606                 }
607                 m_all_ongoing.clear();
608
609                 m_queued_fetches.clear();
610
611                 CURLMcode mres = curl_multi_cleanup(m_multi);
612                 if (mres != CURLM_OK) {
613                         errorstream<<"curl_multi_cleanup"
614                                 <<" returned error code "<<mres
615                                 <<std::endl;
616                 }
617
618                 return NULL;
619         }
620 };
621
622 CurlFetchThread *g_httpfetch_thread = NULL;
623
624 void httpfetch_init(int parallel_limit)
625 {
626         verbosestream<<"httpfetch_init: parallel_limit="<<parallel_limit
627                         <<std::endl;
628
629         CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
630         assert(res == CURLE_OK);
631
632         g_httpfetch_thread = new CurlFetchThread(parallel_limit);
633 }
634
635 void httpfetch_cleanup()
636 {
637         verbosestream<<"httpfetch_cleanup: cleaning up"<<std::endl;
638
639         g_httpfetch_thread->setRun(false);
640         g_httpfetch_thread->requestWakeUp();
641         g_httpfetch_thread->stop();
642         delete g_httpfetch_thread;
643
644         curl_global_cleanup();
645 }
646
647 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
648 {
649         g_httpfetch_thread->requestFetch(fetchrequest);
650         if (!g_httpfetch_thread->IsRunning())
651                 g_httpfetch_thread->Start();
652 }
653
654 static void httpfetch_request_clear(unsigned long caller)
655 {
656         if (g_httpfetch_thread->IsRunning()) {
657                 Event event;
658                 g_httpfetch_thread->requestClear(caller, &event);
659                 event.wait();
660         }
661         else {
662                 g_httpfetch_thread->requestClear(caller, NULL);
663         }
664 }
665
666 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
667                 HTTPFetchResult &fetchresult)
668 {
669         // Create ongoing fetch data and make a cURL handle
670         // Set cURL options based on HTTPFetchRequest
671         CurlHandlePool pool;
672         HTTPFetchOngoing ongoing(fetchrequest, &pool);
673         // Do the fetch (curl_easy_perform)
674         CURLcode res = ongoing.start(NULL);
675         // Update fetchresult
676         ongoing.complete(res);
677         fetchresult = ongoing.result;
678 }
679
680 #else  // USE_CURL
681
682 /*
683         USE_CURL is off:
684
685         Dummy httpfetch implementation that always returns an error.
686 */
687
688 void httpfetch_init(int parallel_limit)
689 {
690 }
691
692 void httpfetch_cleanup()
693 {
694 }
695
696 void httpfetch_async(const HTTPFetchRequest &fetchrequest)
697 {
698         errorstream<<"httpfetch_async: unable to fetch "<<fetchrequest.url
699                         <<" because USE_CURL=0"<<std::endl;
700
701         HTTPFetchResult fetchresult(fetchrequest); // sets succeeded = false etc.
702         httpfetch_deliver_result(fetchresult);
703 }
704
705 static void httpfetch_request_clear(unsigned long caller)
706 {
707 }
708
709 void httpfetch_sync(const HTTPFetchRequest &fetchrequest,
710                 HTTPFetchResult &fetchresult)
711 {
712         errorstream<<"httpfetch_sync: unable to fetch "<<fetchrequest.url
713                         <<" because USE_CURL=0"<<std::endl;
714
715         fetchresult = HTTPFetchResult(fetchrequest); // sets succeeded = false etc.
716 }
717
718 #endif  // USE_CURL