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