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.
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/>.
20 * @brief API for downloading JSON via CURL
21 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
22 * @author Christian Grothoff
26 #include <curl/curl.h>
27 #elif HAVE_GNURL_CURL_H
28 #include <gnurl/curl.h>
31 #include "gnunet_curl_lib.h"
35 * Log error related to CURL operations.
37 * @param type log level
38 * @param function which function failed to run
39 * @param code what was the curl error code
41 #define CURL_STRERROR(type, function, code) \
43 "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
44 function, __FILE__, __LINE__, curl_easy_strerror (code));
47 * Print JSON parsing related error information
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)
56 * Failsafe flag. Raised if our constructor fails to initialize
63 * @brief Buffer data structure we use to buffer the HTTP download
64 * before giving it to the JSON parser.
75 * The size of the download buffer
80 * Error code (based on libc errno) if we failed to download
81 * (i.e. response too large).
89 * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
91 struct GNUNET_CURL_Job
95 * We keep jobs in a DLL.
97 struct GNUNET_CURL_Job *next;
100 * We keep jobs in a DLL.
102 struct GNUNET_CURL_Job *prev;
105 * Easy handle of the job.
110 * Context this job runs in.
112 struct GNUNET_CURL_Context *ctx;
115 * Function to call upon completion.
117 GNUNET_CURL_JobCompletionCallback jcc;
120 * Closure for @e jcc.
125 * Buffer for response received from CURL.
127 struct DownloadBuffer db;
135 struct GNUNET_CURL_Context
148 * We keep jobs in a DLL.
150 struct GNUNET_CURL_Job *jobs_head;
153 * We keep jobs in a DLL.
155 struct GNUNET_CURL_Job *jobs_tail;
158 * HTTP header "application/json", created once and used
159 * for all requests that need it.
161 struct curl_slist *json_header;
164 * Function we need to call whenever the event loop's
165 * socket set changed.
167 GNUNET_CURL_RescheduleCallback cb;
177 * Initialise this library. This function should be called before using any of
178 * the following functions.
180 * @param cb function to call when rescheduling is required
181 * @param cb_cls closure for @a cb
182 * @return library context
184 struct GNUNET_CURL_Context *
185 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb,
188 struct GNUNET_CURL_Context *ctx;
194 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
195 "Curl was not initialised properly\n");
198 if (NULL == (multi = curl_multi_init ()))
200 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
201 "Failed to create a Curl multi handle\n");
204 if (NULL == (share = curl_share_init ()))
206 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
207 "Failed to create a Curl share handle\n");
210 ctx = GNUNET_new (struct GNUNET_CURL_Context);
212 ctx->cb_cls = cb_cls;
215 GNUNET_assert (NULL != (ctx->json_header =
216 curl_slist_append (NULL,
217 "Content-Type: application/json")));
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.
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
236 download_cb (char *bufptr,
241 struct DownloadBuffer *db = cls;
245 if (0 == size * nitems)
247 /* Nothing (left) to do */
250 msize = size * nitems;
251 if ( (msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
254 return 0; /* signals an error to curl */
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;
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.
270 * This function modifies the CURL handle to add the
271 * "Content-Type: application/json" header if @a add_json is set.
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!)
281 struct GNUNET_CURL_Job *
282 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
285 GNUNET_CURL_JobCompletionCallback jcc,
288 struct GNUNET_CURL_Job *job;
290 if (GNUNET_YES == add_json)
292 curl_easy_setopt (eh,
297 curl_easy_cleanup (eh);
301 job = GNUNET_new (struct GNUNET_CURL_Job);
303 curl_easy_setopt (eh,
307 curl_easy_setopt (eh,
308 CURLOPT_WRITEFUNCTION,
311 curl_easy_setopt (eh,
315 curl_easy_setopt (eh,
319 curl_multi_add_handle (ctx->multi,
324 curl_easy_cleanup (eh);
328 job->easy_handle = eh;
331 job->jcc_cls = jcc_cls;
332 GNUNET_CONTAINER_DLL_insert (ctx->jobs_head,
335 ctx->cb (ctx->cb_cls);
341 * Cancel a job. Must only be called before the job completion
342 * callback is called for the respective job.
344 * @param job job to cancel
347 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
349 struct GNUNET_CURL_Context *ctx = job->ctx;
351 GNUNET_CONTAINER_DLL_remove (ctx->jobs_head,
354 GNUNET_break (CURLM_OK ==
355 curl_multi_remove_handle (ctx->multi,
357 curl_easy_cleanup (job->easy_handle);
358 GNUNET_free_non_null (job->db.buf);
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.
371 * Calling this function also cleans up @a db.
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
382 download_get_result (struct DownloadBuffer *db,
390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
391 "Downloaded body: %.*s\n",
396 curl_easy_getinfo (eh,
397 CURLINFO_CONTENT_TYPE,
400 (0 != strcasecmp (ct,
401 "application/json")) )
403 /* No content type or explicitly not JSON, refuse to parse
404 (but keep response code) */
406 curl_easy_getinfo (eh,
407 CURLINFO_RESPONSE_CODE,
410 /* unexpected error... */
414 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
415 "Did NOT detect response as JSON\n");
421 json = json_loadb (db->buf,
423 JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
431 GNUNET_free_non_null (db->buf);
437 curl_easy_getinfo (eh,
438 CURLINFO_RESPONSE_CODE,
441 /* unexpected error... */
451 * Run the main event loop for the Taler interaction.
453 * @param ctx the library context
456 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
459 struct GNUNET_CURL_Job *job;
465 (void) curl_multi_perform (ctx->multi,
467 while (NULL != (cmsg = curl_multi_info_read (ctx->multi,
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,
476 GNUNET_assert (job->ctx == ctx);
478 j = download_get_result (&job->db,
481 job->jcc (job->jcc_cls,
485 GNUNET_CURL_job_cancel (job);
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().
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.
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
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().
519 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
521 fd_set *write_fd_set,
522 fd_set *except_fd_set,
530 GNUNET_assert (CURLM_OK ==
531 curl_multi_fdset (ctx->multi,
537 *max_fd = GNUNET_MAX (m, *max_fd);
538 GNUNET_assert (CURLM_OK ==
539 curl_multi_timeout (ctx->multi,
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) &&
547 if ( (-1 == (*timeout)) &&
548 (NULL != ctx->jobs_head) )
554 * Cleanup library initialisation resources. This function should be called
555 * after using this library to cleanup the resources occupied during library's
558 * @param ctx the library context
561 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
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);
573 * Initial global setup logic, specifically runs the Curl setup.
575 __attribute__ ((constructor))
577 GNUNET_CURL_constructor__ (void)
581 if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
583 CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR,
592 * Cleans up after us, specifically runs the Curl cleanup.
594 __attribute__ ((destructor))
596 GNUNET_CURL_destructor__ (void)
600 curl_global_cleanup ();