2 This file is part of GNUnet
3 Copyright (C) 2014, 2015, 2016, 2018 GNUnet e.V.
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.
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.
17 * @brief API for downloading JSON via CURL
18 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
19 * @author Christian Grothoff
23 #include <curl/curl.h>
24 #elif HAVE_GNURL_CURL_H
25 #include <gnurl/curl.h>
28 #include "gnunet_curl_lib.h"
32 * Log error related to CURL operations.
34 * @param type log level
35 * @param function which function failed to run
36 * @param code what was the curl error code
38 #define CURL_STRERROR(type, function, code) \
40 "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
41 function, __FILE__, __LINE__, curl_easy_strerror (code));
44 * Print JSON parsing related error information
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)
53 * Failsafe flag. Raised if our constructor fails to initialize
60 * @brief Buffer data structure we use to buffer the HTTP download
61 * before giving it to the JSON parser.
72 * The size of the download buffer
77 * Error code (based on libc errno) if we failed to download
78 * (i.e. response too large).
86 * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
88 struct GNUNET_CURL_Job
92 * We keep jobs in a DLL.
94 struct GNUNET_CURL_Job *next;
97 * We keep jobs in a DLL.
99 struct GNUNET_CURL_Job *prev;
102 * Easy handle of the job.
107 * Context this job runs in.
109 struct GNUNET_CURL_Context *ctx;
112 * Function to call upon completion.
114 GNUNET_CURL_JobCompletionCallback jcc;
117 * Closure for @e jcc.
122 * Buffer for response received from CURL.
124 struct DownloadBuffer db;
132 struct GNUNET_CURL_Context
145 * We keep jobs in a DLL.
147 struct GNUNET_CURL_Job *jobs_head;
150 * We keep jobs in a DLL.
152 struct GNUNET_CURL_Job *jobs_tail;
155 * HTTP header "application/json", created once and used
156 * for all requests that need it.
158 struct curl_slist *json_header;
161 * Function we need to call whenever the event loop's
162 * socket set changed.
164 GNUNET_CURL_RescheduleCallback cb;
174 * Initialise this library. This function should be called before using any of
175 * the following functions.
177 * @param cb function to call when rescheduling is required
178 * @param cb_cls closure for @a cb
179 * @return library context
181 struct GNUNET_CURL_Context *
182 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb,
185 struct GNUNET_CURL_Context *ctx;
191 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
192 "Curl was not initialised properly\n");
195 if (NULL == (multi = curl_multi_init ()))
197 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
198 "Failed to create a Curl multi handle\n");
201 if (NULL == (share = curl_share_init ()))
203 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
204 "Failed to create a Curl share handle\n");
207 ctx = GNUNET_new (struct GNUNET_CURL_Context);
209 ctx->cb_cls = cb_cls;
212 GNUNET_assert (NULL != (ctx->json_header =
213 curl_slist_append (NULL,
214 "Content-Type: application/json")));
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.
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
233 download_cb (char *bufptr,
238 struct DownloadBuffer *db = cls;
242 if (0 == size * nitems)
244 /* Nothing (left) to do */
247 msize = size * nitems;
248 if ( (msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
251 return 0; /* signals an error to curl */
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;
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.
267 * This function modifies the CURL handle to add the
268 * "Content-Type: application/json" header if @a add_json is set.
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!)
278 struct GNUNET_CURL_Job *
279 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
282 GNUNET_CURL_JobCompletionCallback jcc,
285 struct GNUNET_CURL_Job *job;
287 if (GNUNET_YES == add_json)
289 curl_easy_setopt (eh,
294 curl_easy_cleanup (eh);
298 job = GNUNET_new (struct GNUNET_CURL_Job);
300 curl_easy_setopt (eh,
304 curl_easy_setopt (eh,
305 CURLOPT_WRITEFUNCTION,
308 curl_easy_setopt (eh,
312 curl_easy_setopt (eh,
316 curl_multi_add_handle (ctx->multi,
321 curl_easy_cleanup (eh);
325 job->easy_handle = eh;
328 job->jcc_cls = jcc_cls;
329 GNUNET_CONTAINER_DLL_insert (ctx->jobs_head,
332 ctx->cb (ctx->cb_cls);
338 * Cancel a job. Must only be called before the job completion
339 * callback is called for the respective job.
341 * @param job job to cancel
344 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
346 struct GNUNET_CURL_Context *ctx = job->ctx;
348 GNUNET_CONTAINER_DLL_remove (ctx->jobs_head,
351 GNUNET_break (CURLM_OK ==
352 curl_multi_remove_handle (ctx->multi,
354 curl_easy_cleanup (job->easy_handle);
355 GNUNET_free_non_null (job->db.buf);
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.
368 * Calling this function also cleans up @a db.
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
379 download_get_result (struct DownloadBuffer *db,
387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
388 "Downloaded body: %.*s\n",
393 curl_easy_getinfo (eh,
394 CURLINFO_CONTENT_TYPE,
397 (0 != strcasecmp (ct,
398 "application/json")) )
400 /* No content type or explicitly not JSON, refuse to parse
401 (but keep response code) */
403 curl_easy_getinfo (eh,
404 CURLINFO_RESPONSE_CODE,
407 /* unexpected error... */
411 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
412 "Did NOT detect response as JSON\n");
418 json = json_loadb (db->buf,
420 JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
428 GNUNET_free_non_null (db->buf);
434 curl_easy_getinfo (eh,
435 CURLINFO_RESPONSE_CODE,
438 /* unexpected error... */
448 * Run the main event loop for the Taler interaction.
450 * @param ctx the library context
453 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
456 struct GNUNET_CURL_Job *job;
462 (void) curl_multi_perform (ctx->multi,
464 while (NULL != (cmsg = curl_multi_info_read (ctx->multi,
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,
473 GNUNET_assert (job->ctx == ctx);
475 j = download_get_result (&job->db,
478 job->jcc (job->jcc_cls,
482 GNUNET_CURL_job_cancel (job);
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().
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.
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
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().
516 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
518 fd_set *write_fd_set,
519 fd_set *except_fd_set,
527 GNUNET_assert (CURLM_OK ==
528 curl_multi_fdset (ctx->multi,
534 *max_fd = GNUNET_MAX (m, *max_fd);
535 GNUNET_assert (CURLM_OK ==
536 curl_multi_timeout (ctx->multi,
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) &&
544 if ( (-1 == (*timeout)) &&
545 (NULL != ctx->jobs_head) )
551 * Cleanup library initialisation resources. This function should be called
552 * after using this library to cleanup the resources occupied during library's
555 * @param ctx the library context
558 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
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);
570 * Initial global setup logic, specifically runs the Curl setup.
572 __attribute__ ((constructor))
574 GNUNET_CURL_constructor__ (void)
578 if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
580 CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR,
589 * Cleans up after us, specifically runs the Curl cleanup.
591 __attribute__ ((destructor))
593 GNUNET_CURL_destructor__ (void)
597 curl_global_cleanup ();