src: for every AGPL3.0 file, add SPDX identifier.
[oweals/gnunet.git] / src / curl / curl.c
1 /*
2   This file is part of GNUnet
3   Copyright (C) 2014, 2015, 2016, 2018 GNUnet e.V.
4
5   GNUnet is free software: you can redistribute it and/or modify it
6   under the terms of the GNU Affero General Public License as published
7   by the Free Software Foundation, either version 3 of the License,
8   or (at your option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   Affero General Public License for more details.
14
15   You should have received a copy of the GNU Affero General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20 /**
21  * @file curl/curl.c
22  * @brief API for downloading JSON via CURL
23  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #if HAVE_CURL_CURL_H
28 #include <curl/curl.h>
29 #elif HAVE_GNURL_CURL_H
30 #include <gnurl/curl.h>
31 #endif
32 #include <jansson.h>
33 #include "gnunet_curl_lib.h"
34
35 #if ENABLE_BENCHMARK
36 #include "../util/benchmark.h"
37 #endif
38
39
40 /**
41  * Log error related to CURL operations.
42  *
43  * @param type log level
44  * @param function which function failed to run
45  * @param code what was the curl error code
46  */
47 #define CURL_STRERROR(type, function, code)      \
48  GNUNET_log (type,                               \
49              "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
50              function, __FILE__, __LINE__, curl_easy_strerror (code));
51
52 /**
53  * Print JSON parsing related error information
54  */
55 #define JSON_WARN(error)                                                \
56     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,                              \
57                 "JSON parsing failed at %s:%u: %s (%s)\n",              \
58                 __FILE__, __LINE__, error.text, error.source)
59
60
61 /**
62  * Failsafe flag. Raised if our constructor fails to initialize
63  * the Curl library.
64  */
65 static int curl_fail;
66
67 /**
68  * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
69  */
70 struct GNUNET_CURL_Job
71 {
72
73   /**
74    * We keep jobs in a DLL.
75    */
76   struct GNUNET_CURL_Job *next;
77
78   /**
79    * We keep jobs in a DLL.
80    */
81   struct GNUNET_CURL_Job *prev;
82
83   /**
84    * Easy handle of the job.
85    */
86   CURL *easy_handle;
87
88   /**
89    * Context this job runs in.
90    */
91   struct GNUNET_CURL_Context *ctx;
92
93   /**
94    * Function to call upon completion.
95    */
96   GNUNET_CURL_JobCompletionCallback jcc;
97
98   /**
99    * Closure for @e jcc.
100    */
101   void *jcc_cls;
102
103   /**
104    * Buffer for response received from CURL.
105    */
106   struct GNUNET_CURL_DownloadBuffer db;
107
108 };
109
110
111 /**
112  * Context
113  */
114 struct GNUNET_CURL_Context
115 {
116   /**
117    * Curl multi handle
118    */
119   CURLM *multi;
120
121   /**
122    * Curl share handle
123    */
124   CURLSH *share;
125
126   /**
127    * We keep jobs in a DLL.
128    */
129   struct GNUNET_CURL_Job *jobs_head;
130
131   /**
132    * We keep jobs in a DLL.
133    */
134   struct GNUNET_CURL_Job *jobs_tail;
135
136   /**
137    * HTTP header "application/json", created once and used
138    * for all requests that need it.
139    */
140   struct curl_slist *json_header;
141
142   /**
143    * Function we need to call whenever the event loop's
144    * socket set changed.
145    */
146   GNUNET_CURL_RescheduleCallback cb;
147
148   /**
149    * Closure for @e cb.
150    */
151   void *cb_cls;
152 };
153
154
155 /**
156  * Initialise this library.  This function should be called before using any of
157  * the following functions.
158  *
159  * @param cb function to call when rescheduling is required
160  * @param cb_cls closure for @a cb
161  * @return library context
162  */
163 struct GNUNET_CURL_Context *
164 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb,
165                   void *cb_cls)
166 {
167   struct GNUNET_CURL_Context *ctx;
168   CURLM *multi;
169   CURLSH *share;
170
171   if (curl_fail)
172   {
173     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
174                 "Curl was not initialised properly\n");
175     return NULL;
176   }
177   if (NULL == (multi = curl_multi_init ()))
178   {
179     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
180                 "Failed to create a Curl multi handle\n");
181     return NULL;
182   }
183   if (NULL == (share = curl_share_init ()))
184   {
185     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
186                 "Failed to create a Curl share handle\n");
187     return NULL;
188   }
189   ctx = GNUNET_new (struct GNUNET_CURL_Context);
190   ctx->cb = cb;
191   ctx->cb_cls = cb_cls;
192   ctx->multi = multi;
193   ctx->share = share;
194   GNUNET_assert (NULL != (ctx->json_header =
195                           curl_slist_append (NULL,
196                                              "Content-Type: application/json")));
197   return ctx;
198 }
199
200
201 /**
202  * Callback used when downloading the reply to an HTTP request.
203  * Just appends all of the data to the `buf` in the
204  * `struct DownloadBuffer` for further processing. The size of
205  * the download is limited to #GNUNET_MAX_MALLOC_CHECKED, if
206  * the download exceeds this size, we abort with an error.
207  *
208  * @param bufptr data downloaded via HTTP
209  * @param size size of an item in @a bufptr
210  * @param nitems number of items in @a bufptr
211  * @param cls the `struct DownloadBuffer`
212  * @return number of bytes processed from @a bufptr
213  */
214 static size_t
215 download_cb (char *bufptr,
216              size_t size,
217              size_t nitems,
218              void *cls)
219 {
220   struct GNUNET_CURL_DownloadBuffer *db = cls;
221   size_t msize;
222   void *buf;
223
224   if (0 == size * nitems)
225   {
226     /* Nothing (left) to do */
227     return 0;
228   }
229   msize = size * nitems;
230   if ( (msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
231   {
232     db->eno = ENOMEM;
233     return 0; /* signals an error to curl */
234   }
235   db->buf = GNUNET_realloc (db->buf,
236                             db->buf_size + msize);
237   buf = db->buf + db->buf_size;
238   GNUNET_memcpy (buf, bufptr, msize);
239   db->buf_size += msize;
240   return msize;
241 }
242
243
244 /**
245  * Schedule a CURL request to be executed and call the given @a jcc
246  * upon its completion.  Note that the context will make use of the
247  * CURLOPT_PRIVATE facility of the CURL @a eh.
248  *
249  * This function modifies the CURL handle to add the
250  * "Content-Type: application/json" header if @a add_json is set.
251  *
252  * @param ctx context to execute the job in
253  * @param eh curl easy handle for the request, will
254  *           be executed AND cleaned up
255  * @param add_json add "application/json" content type header
256  * @param jcc callback to invoke upon completion
257  * @param jcc_cls closure for @a jcc
258  * @return NULL on error (in this case, @eh is still released!)
259  */
260 struct GNUNET_CURL_Job *
261 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
262                      CURL *eh,
263                      int add_json,
264                      GNUNET_CURL_JobCompletionCallback jcc,
265                      void *jcc_cls)
266 {
267   struct GNUNET_CURL_Job *job;
268
269   if (GNUNET_YES == add_json)
270     if (CURLE_OK !=
271         curl_easy_setopt (eh,
272                           CURLOPT_HTTPHEADER,
273                           ctx->json_header))
274     {
275       GNUNET_break (0);
276       curl_easy_cleanup (eh);
277       return NULL;
278     }
279
280   job = GNUNET_new (struct GNUNET_CURL_Job);
281   if ( (CURLE_OK !=
282         curl_easy_setopt (eh,
283                           CURLOPT_PRIVATE,
284                           job)) ||
285        (CURLE_OK !=
286         curl_easy_setopt (eh,
287                           CURLOPT_WRITEFUNCTION,
288                           &download_cb)) ||
289        (CURLE_OK !=
290         curl_easy_setopt (eh,
291                           CURLOPT_WRITEDATA,
292                           &job->db)) ||
293        (CURLE_OK !=
294         curl_easy_setopt (eh,
295                           CURLOPT_SHARE,
296                           ctx->share)) ||
297        (CURLM_OK !=
298         curl_multi_add_handle (ctx->multi,
299                                eh)) )
300   {
301     GNUNET_break (0);
302     GNUNET_free (job);
303     curl_easy_cleanup (eh);
304     return NULL;
305   }
306
307   job->easy_handle = eh;
308   job->ctx = ctx;
309   job->jcc = jcc;
310   job->jcc_cls = jcc_cls;
311   GNUNET_CONTAINER_DLL_insert (ctx->jobs_head,
312                                ctx->jobs_tail,
313                                job);
314   ctx->cb (ctx->cb_cls);
315   return job;
316 }
317
318
319 /**
320  * Cancel a job.  Must only be called before the job completion
321  * callback is called for the respective job.
322  *
323  * @param job job to cancel
324  */
325 void
326 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
327 {
328   struct GNUNET_CURL_Context *ctx = job->ctx;
329
330   GNUNET_CONTAINER_DLL_remove (ctx->jobs_head,
331                                ctx->jobs_tail,
332                                job);
333   GNUNET_break (CURLM_OK ==
334                 curl_multi_remove_handle (ctx->multi,
335                                           job->easy_handle));
336   curl_easy_cleanup (job->easy_handle);
337   GNUNET_free_non_null (job->db.buf);
338   GNUNET_free (job);
339 }
340
341
342 /**
343  * Obtain information about the final result about the
344  * HTTP download. If the download was successful, parses
345  * the JSON in the @a db and returns it. Also returns
346  * the HTTP @a response_code.  If the download failed,
347  * the return value is NULL.  The response code is set
348  * in any case, on download errors to zero.
349  *
350  * Calling this function also cleans up @a db.
351  *
352  * @param db download buffer
353  * @param eh CURL handle (to get the response code)
354  * @param[out] response_code set to the HTTP response code
355  *             (or zero if we aborted the download, i.e.
356  *              because the response was too big, or if
357  *              the JSON we received was malformed).
358  * @return NULL if downloading a JSON reply failed.
359  */
360 void *
361 download_get_result (struct GNUNET_CURL_DownloadBuffer *db,
362                      CURL *eh,
363                      long *response_code)
364 {
365   json_t *json;
366   json_error_t error;
367   char *ct;
368
369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
370               "Downloaded body: %.*s\n",
371               (int) db->buf_size,
372               (char *) db->buf);
373
374   if ( (CURLE_OK !=
375         curl_easy_getinfo (eh,
376                            CURLINFO_CONTENT_TYPE,
377                            &ct)) ||
378        (NULL == ct) ||
379        (0 != strcasecmp (ct,
380                          "application/json")) )
381   {
382     /* No content type or explicitly not JSON, refuse to parse
383        (but keep response code) */
384     if (CURLE_OK !=
385         curl_easy_getinfo (eh,
386                            CURLINFO_RESPONSE_CODE,
387                            response_code))
388     {
389       /* unexpected error... */
390       GNUNET_break (0);
391       *response_code = 0;
392     }
393     if (0 != db->buf_size)
394       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
395                   "Did NOT detect response as JSON\n");
396     return NULL;
397   }
398   json = NULL;
399   if (0 == db->eno)
400   {
401     json = json_loadb (db->buf,
402                        db->buf_size,
403                        JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
404                        &error);
405     if (NULL == json)
406     {
407       JSON_WARN (error);
408       *response_code = 0;
409     }
410   }
411   GNUNET_free_non_null (db->buf);
412   db->buf = NULL;
413   db->buf_size = 0;
414   if (NULL != json)
415   {
416     if (CURLE_OK !=
417         curl_easy_getinfo (eh,
418                            CURLINFO_RESPONSE_CODE,
419                            response_code))
420     {
421       /* unexpected error... */
422       GNUNET_break (0);
423       *response_code = 0;
424     }
425   }
426   return json;
427 }
428
429 /**
430  * Add custom request header.
431  *
432  * @param ctx cURL context.
433  * @param header header string; will be given to the context AS IS.
434  * @return #GNUNET_OK if no errors occurred, #GNUNET_SYSERR otherwise.
435  */
436 int
437 GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx,
438                            const char *header)
439 {
440   ctx->json_header = curl_slist_append (ctx->json_header,
441                                         header);
442   if (NULL == ctx->json_header)
443     return GNUNET_SYSERR;
444
445   return GNUNET_OK;
446 }
447
448 /**
449  * Run the main event loop for the Taler interaction.
450  *
451  * @param ctx the library context
452  * @param rp parses the raw response returned from
453  *        the Web server.
454  * @param rc cleans/frees the response
455  */
456 void
457 GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx,
458                       GNUNET_CURL_RawParser rp,
459                       GNUNET_CURL_ResponseCleaner rc)
460 {
461   CURLMsg *cmsg;
462   struct GNUNET_CURL_Job *job;
463   int n_running;
464   int n_completed;
465   long response_code;
466   void *response;
467
468   (void) curl_multi_perform (ctx->multi,
469                              &n_running);
470   while (NULL != (cmsg = curl_multi_info_read (ctx->multi,
471                                                &n_completed)))
472   {
473     /* Only documented return value is CURLMSG_DONE */
474     GNUNET_break (CURLMSG_DONE == cmsg->msg);
475     GNUNET_assert (CURLE_OK ==
476                    curl_easy_getinfo (cmsg->easy_handle,
477                                       CURLINFO_PRIVATE,
478                                       (char **) &job));
479     GNUNET_assert (job->ctx == ctx);
480     response_code = 0 ;
481     response = rp (&job->db,
482                    job->easy_handle,
483                    &response_code);
484 #if ENABLE_BENCHMARK
485   {
486     char *url = NULL;
487     double total_as_double = 0;
488     struct GNUNET_TIME_Relative total;
489     struct UrlRequestData *urd;
490     CURLcode res;
491     res = curl_easy_getinfo (cmsg->easy_handle, CURLINFO_TOTAL_TIME, &total_as_double);
492     GNUNET_break (CURLE_OK == res);
493     curl_easy_getinfo (cmsg->easy_handle, CURLINFO_EFFECTIVE_URL, &url);
494     total.rel_value_us = total_as_double * 1000 * 1000;
495     urd = get_url_benchmark_data (url, (unsigned int) response_code);
496     urd->count++;
497     urd->time = GNUNET_TIME_relative_add (urd->time, total);
498     urd->time_max = GNUNET_TIME_relative_max (total, urd->time_max);
499   }
500 #endif
501     job->jcc (job->jcc_cls,
502               response_code,
503               response);
504     rc (response);
505     GNUNET_CURL_job_cancel (job);
506   }
507 }
508
509
510 /**
511  * Run the main event loop for the Taler interaction.
512  *
513  * @param ctx the library context
514  */
515 void
516 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
517 {
518   
519   GNUNET_CURL_perform2 (ctx,
520                         download_get_result,
521                         (GNUNET_CURL_ResponseCleaner) &json_decref);
522 }
523
524
525 /**
526  * Obtain the information for a select() call to wait until
527  * #GNUNET_CURL_perform() is ready again.  Note that calling
528  * any other GNUNET_CURL-API may also imply that the library
529  * is again ready for #GNUNET_CURL_perform().
530  *
531  * Basically, a client should use this API to prepare for select(),
532  * then block on select(), then call #GNUNET_CURL_perform() and then
533  * start again until the work with the context is done.
534  *
535  * This function will NOT zero out the sets and assumes that @a max_fd
536  * and @a timeout are already set to minimal applicable values.  It is
537  * safe to give this API FD-sets and @a max_fd and @a timeout that are
538  * already initialized to some other descriptors that need to go into
539  * the select() call.
540  *
541  * @param ctx context to get the event loop information for
542  * @param read_fd_set will be set for any pending read operations
543  * @param write_fd_set will be set for any pending write operations
544  * @param except_fd_set is here because curl_multi_fdset() has this argument
545  * @param max_fd set to the highest FD included in any set;
546  *        if the existing sets have no FDs in it, the initial
547  *        value should be "-1". (Note that `max_fd + 1` will need
548  *        to be passed to select().)
549  * @param timeout set to the timeout in milliseconds (!); -1 means
550  *        no timeout (NULL, blocking forever is OK), 0 means to
551  *        proceed immediately with #GNUNET_CURL_perform().
552  */
553 void
554 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
555                              fd_set *read_fd_set,
556                              fd_set *write_fd_set,
557                              fd_set *except_fd_set,
558                              int *max_fd,
559                              long *timeout)
560 {
561   long to;
562   int m;
563
564   m = -1;
565   GNUNET_assert (CURLM_OK ==
566                  curl_multi_fdset (ctx->multi,
567                                    read_fd_set,
568                                    write_fd_set,
569                                    except_fd_set,
570                                    &m));
571   to = *timeout;
572   *max_fd = GNUNET_MAX (m, *max_fd);
573   GNUNET_assert (CURLM_OK ==
574                  curl_multi_timeout (ctx->multi,
575                                      &to));
576
577   /* Only if what we got back from curl is smaller than what we
578      already had (-1 == infinity!), then update timeout */
579   if ( (to < *timeout) &&
580        (-1 != to) )
581     *timeout = to;
582   if ( (-1 == (*timeout)) &&
583        (NULL != ctx->jobs_head) )
584     *timeout = to;
585 }
586
587
588 /**
589  * Cleanup library initialisation resources.  This function should be called
590  * after using this library to cleanup the resources occupied during library's
591  * initialisation.
592  *
593  * @param ctx the library context
594  */
595 void
596 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
597 {
598   /* all jobs must have been cancelled at this time, assert this */
599   GNUNET_assert (NULL == ctx->jobs_head);
600   curl_share_cleanup (ctx->share);
601   curl_multi_cleanup (ctx->multi);
602   curl_slist_free_all (ctx->json_header);
603   GNUNET_free (ctx);
604 }
605
606
607 /**
608  * Initial global setup logic, specifically runs the Curl setup.
609  */
610 __attribute__ ((constructor))
611 void
612 GNUNET_CURL_constructor__ (void)
613 {
614   CURLcode ret;
615
616   if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
617   {
618     CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR,
619                    "curl_global_init",
620                    ret);
621     curl_fail = 1;
622   }
623 }
624
625
626 /**
627  * Cleans up after us, specifically runs the Curl cleanup.
628  */
629 __attribute__ ((destructor))
630 void
631 GNUNET_CURL_destructor__ (void)
632 {
633   if (curl_fail)
634     return;
635   curl_global_cleanup ();
636 }
637
638 /* end of curl.c */