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