2 This file is part of GNUnet
3 Copyright (C) 2014, 2015, 2016 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3, or (at your option) any later version.
9 GNUnet is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License along with
14 GNUnet; see the file COPYING. If not, If not, see
15 <http://www.gnu.org/licenses/>
19 * @brief API for downloading JSON via CURL
20 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
21 * @author Christian Grothoff
25 #include <curl/curl.h>
26 #elif HAVE_GNURL_CURL_H
27 #include <gnurl/curl.h>
30 #include "gnunet_curl_lib.h"
34 * Log error related to CURL operations.
36 * @param type log level
37 * @param function which function failed to run
38 * @param code what was the curl error code
40 #define CURL_STRERROR(type, function, code) \
42 "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
43 function, __FILE__, __LINE__, curl_easy_strerror (code));
46 * Print JSON parsing related error information
48 #define JSON_WARN(error) \
49 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, \
50 "JSON parsing failed at %s:%u: %s (%s)\n", \
51 __FILE__, __LINE__, error.text, error.source)
55 * Failsafe flag. Raised if our constructor fails to initialize
62 * @brief Buffer data structure we use to buffer the HTTP download
63 * before giving it to the JSON parser.
74 * The size of the download buffer
79 * Error code (based on libc errno) if we failed to download
80 * (i.e. response too large).
88 * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
90 struct GNUNET_CURL_Job
94 * We keep jobs in a DLL.
96 struct GNUNET_CURL_Job *next;
99 * We keep jobs in a DLL.
101 struct GNUNET_CURL_Job *prev;
104 * Easy handle of the job.
109 * Context this job runs in.
111 struct GNUNET_CURL_Context *ctx;
114 * Function to call upon completion.
116 GNUNET_CURL_JobCompletionCallback jcc;
119 * Closure for @e jcc.
124 * Buffer for response received from CURL.
126 struct DownloadBuffer db;
134 struct GNUNET_CURL_Context
147 * We keep jobs in a DLL.
149 struct GNUNET_CURL_Job *jobs_head;
152 * We keep jobs in a DLL.
154 struct GNUNET_CURL_Job *jobs_tail;
157 * HTTP header "application/json", created once and used
158 * for all requests that need it.
160 struct curl_slist *json_header;
163 * Function we need to call whenever the event loop's
164 * socket set changed.
166 GNUNET_CURL_RescheduleCallback cb;
176 * Initialise this library. This function should be called before using any of
177 * the following functions.
179 * @param cb function to call when rescheduling is required
180 * @param cb_cls closure for @a cb
181 * @return library context
183 struct GNUNET_CURL_Context *
184 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb,
187 struct GNUNET_CURL_Context *ctx;
193 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
194 "Curl was not initialised properly\n");
197 if (NULL == (multi = curl_multi_init ()))
199 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
200 "Failed to create a Curl multi handle\n");
203 if (NULL == (share = curl_share_init ()))
205 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
206 "Failed to create a Curl share handle\n");
209 ctx = GNUNET_new (struct GNUNET_CURL_Context);
211 ctx->cb_cls = cb_cls;
214 GNUNET_assert (NULL != (ctx->json_header =
215 curl_slist_append (NULL,
216 "Content-Type: application/json")));
222 * Callback used when downloading the reply to an HTTP request.
223 * Just appends all of the data to the `buf` in the
224 * `struct DownloadBuffer` for further processing. The size of
225 * the download is limited to #GNUNET_MAX_MALLOC_CHECKED, if
226 * the download exceeds this size, we abort with an error.
228 * @param bufptr data downloaded via HTTP
229 * @param size size of an item in @a bufptr
230 * @param nitems number of items in @a bufptr
231 * @param cls the `struct DownloadBuffer`
232 * @return number of bytes processed from @a bufptr
235 download_cb (char *bufptr,
240 struct DownloadBuffer *db = cls;
244 if (0 == size * nitems)
246 /* Nothing (left) to do */
249 msize = size * nitems;
250 if ( (msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
253 return 0; /* signals an error to curl */
255 db->buf = GNUNET_realloc (db->buf,
256 db->buf_size + msize);
257 buf = db->buf + db->buf_size;
258 memcpy (buf, bufptr, msize);
259 db->buf_size += msize;
265 * Schedule a CURL request to be executed and call the given @a jcc
266 * upon its completion. Note that the context will make use of the
267 * CURLOPT_PRIVATE facility of the CURL @a eh.
269 * This function modifies the CURL handle to add the
270 * "Content-Type: application/json" header if @a add_json is set.
272 * @param ctx context to execute the job in
273 * @param eh curl easy handle for the request, will
274 * be executed AND cleaned up
275 * @param add_json add "application/json" content type header
276 * @param jcc callback to invoke upon completion
277 * @param jcc_cls closure for @a jcc
278 * @return NULL on error (in this case, @eh is still released!)
280 struct GNUNET_CURL_Job *
281 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
284 GNUNET_CURL_JobCompletionCallback jcc,
287 struct GNUNET_CURL_Job *job;
289 if (GNUNET_YES == add_json)
291 curl_easy_setopt (eh,
296 curl_easy_cleanup (eh);
300 job = GNUNET_new (struct GNUNET_CURL_Job);
302 curl_easy_setopt (eh,
306 curl_easy_setopt (eh,
307 CURLOPT_WRITEFUNCTION,
310 curl_easy_setopt (eh,
314 curl_easy_setopt (eh,
318 curl_multi_add_handle (ctx->multi,
323 curl_easy_cleanup (eh);
327 job->easy_handle = eh;
330 job->jcc_cls = jcc_cls;
331 GNUNET_CONTAINER_DLL_insert (ctx->jobs_head,
334 ctx->cb (ctx->cb_cls);
340 * Cancel a job. Must only be called before the job completion
341 * callback is called for the respective job.
343 * @param job job to cancel
346 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
348 struct GNUNET_CURL_Context *ctx = job->ctx;
350 GNUNET_CONTAINER_DLL_remove (ctx->jobs_head,
353 GNUNET_break (CURLM_OK ==
354 curl_multi_remove_handle (ctx->multi,
356 curl_easy_cleanup (job->easy_handle);
357 GNUNET_free_non_null (job->db.buf);
363 * Obtain information about the final result about the
364 * HTTP download. If the download was successful, parses
365 * the JSON in the @a db and returns it. Also returns
366 * the HTTP @a response_code. If the download failed,
367 * the return value is NULL. The response code is set
368 * in any case, on download errors to zero.
370 * Calling this function also cleans up @a db.
372 * @param db download buffer
373 * @param eh CURL handle (to get the response code)
374 * @param[out] response_code set to the HTTP response code
375 * (or zero if we aborted the download, i.e.
376 * because the response was too big, or if
377 * the JSON we received was malformed).
378 * @return NULL if downloading a JSON reply failed
381 download_get_result (struct DownloadBuffer *db,
390 curl_easy_getinfo (eh,
391 CURLINFO_CONTENT_TYPE,
394 (0 != strcasecmp (ct,
395 "application/json")) )
397 /* No content type or explicitly not JSON, refuse to parse
398 (but keep response code) */
400 curl_easy_getinfo (eh,
401 CURLINFO_RESPONSE_CODE,
404 /* unexpected error... */
414 json = json_loadb (db->buf,
416 JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
424 GNUNET_free_non_null (db->buf);
430 curl_easy_getinfo (eh,
431 CURLINFO_RESPONSE_CODE,
434 /* unexpected error... */
444 * Run the main event loop for the Taler interaction.
446 * @param ctx the library context
449 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
452 struct GNUNET_CURL_Job *job;
458 (void) curl_multi_perform (ctx->multi,
460 while (NULL != (cmsg = curl_multi_info_read (ctx->multi,
463 /* Only documented return value is CURLMSG_DONE */
464 GNUNET_break (CURLMSG_DONE == cmsg->msg);
465 GNUNET_assert (CURLE_OK ==
466 curl_easy_getinfo (cmsg->easy_handle,
469 GNUNET_assert (job->ctx == ctx);
470 j = download_get_result (&job->db,
473 job->jcc (job->jcc_cls,
477 GNUNET_CURL_job_cancel (job);
483 * Obtain the information for a select() call to wait until
484 * #GNUNET_CURL_perform() is ready again. Note that calling
485 * any other GNUNET_CURL-API may also imply that the library
486 * is again ready for #GNUNET_CURL_perform().
488 * Basically, a client should use this API to prepare for select(),
489 * then block on select(), then call #GNUNET_CURL_perform() and then
490 * start again until the work with the context is done.
492 * This function will NOT zero out the sets and assumes that @a max_fd
493 * and @a timeout are already set to minimal applicable values. It is
494 * safe to give this API FD-sets and @a max_fd and @a timeout that are
495 * already initialized to some other descriptors that need to go into
498 * @param ctx context to get the event loop information for
499 * @param read_fd_set will be set for any pending read operations
500 * @param write_fd_set will be set for any pending write operations
501 * @param except_fd_set is here because curl_multi_fdset() has this argument
502 * @param max_fd set to the highest FD included in any set;
503 * if the existing sets have no FDs in it, the initial
504 * value should be "-1". (Note that `max_fd + 1` will need
505 * to be passed to select().)
506 * @param timeout set to the timeout in milliseconds (!); -1 means
507 * no timeout (NULL, blocking forever is OK), 0 means to
508 * proceed immediately with #GNUNET_CURL_perform().
511 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
513 fd_set *write_fd_set,
514 fd_set *except_fd_set,
522 GNUNET_assert (CURLM_OK ==
523 curl_multi_fdset (ctx->multi,
529 *max_fd = GNUNET_MAX (m, *max_fd);
530 GNUNET_assert (CURLM_OK ==
531 curl_multi_timeout (ctx->multi,
534 /* Only if what we got back from curl is smaller than what we
535 already had (-1 == infinity!), then update timeout */
536 if ( (to < *timeout) &&
539 if ( (-1 == (*timeout)) &&
540 (NULL != ctx->jobs_head) )
546 * Cleanup library initialisation resources. This function should be called
547 * after using this library to cleanup the resources occupied during library's
550 * @param ctx the library context
553 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
555 /* all jobs must have been cancelled at this time, assert this */
556 GNUNET_assert (NULL == ctx->jobs_head);
557 curl_share_cleanup (ctx->share);
558 curl_multi_cleanup (ctx->multi);
559 curl_slist_free_all (ctx->json_header);
565 * Initial global setup logic, specifically runs the Curl setup.
567 __attribute__ ((constructor))
569 GNUNET_CURL_constructor__ (void)
573 if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
575 CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR,
584 * Cleans up after us, specifically runs the Curl cleanup.
586 __attribute__ ((destructor))
588 GNUNET_CURL_destructor__ (void)
592 curl_global_cleanup ();