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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @brief API for downloading JSON via CURL
23 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
24 * @author Christian Grothoff
28 #include <curl/curl.h>
29 #elif HAVE_GNURL_CURL_H
30 #include <gnurl/curl.h>
33 #include "gnunet_curl_lib.h"
36 #include "../util/benchmark.h"
41 * Log error related to CURL operations.
43 * @param type log level
44 * @param function which function failed to run
45 * @param code what was the curl error code
47 #define CURL_STRERROR(type, function, code) \
49 "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
50 function, __FILE__, __LINE__, curl_easy_strerror (code));
53 * Print JSON parsing related error information
55 #define JSON_WARN(error) \
56 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, \
57 "JSON parsing failed at %s:%u: %s (%s)\n", \
58 __FILE__, __LINE__, error.text, error.source)
62 * Failsafe flag. Raised if our constructor fails to initialize
68 * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
70 struct GNUNET_CURL_Job
74 * We keep jobs in a DLL.
76 struct GNUNET_CURL_Job *next;
79 * We keep jobs in a DLL.
81 struct GNUNET_CURL_Job *prev;
84 * Easy handle of the job.
89 * Context this job runs in.
91 struct GNUNET_CURL_Context *ctx;
94 * Function to call upon completion.
96 GNUNET_CURL_JobCompletionCallback jcc;
104 * Buffer for response received from CURL.
106 struct GNUNET_CURL_DownloadBuffer db;
114 struct GNUNET_CURL_Context
127 * We keep jobs in a DLL.
129 struct GNUNET_CURL_Job *jobs_head;
132 * We keep jobs in a DLL.
134 struct GNUNET_CURL_Job *jobs_tail;
137 * HTTP header "application/json", created once and used
138 * for all requests that need it.
140 struct curl_slist *json_header;
143 * Function we need to call whenever the event loop's
144 * socket set changed.
146 GNUNET_CURL_RescheduleCallback cb;
156 * Initialise this library. This function should be called before using any of
157 * the following functions.
159 * @param cb function to call when rescheduling is required
160 * @param cb_cls closure for @a cb
161 * @return library context
163 struct GNUNET_CURL_Context *
164 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb,
167 struct GNUNET_CURL_Context *ctx;
173 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
174 "Curl was not initialised properly\n");
177 if (NULL == (multi = curl_multi_init ()))
179 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
180 "Failed to create a Curl multi handle\n");
183 if (NULL == (share = curl_share_init ()))
185 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
186 "Failed to create a Curl share handle\n");
189 ctx = GNUNET_new (struct GNUNET_CURL_Context);
191 ctx->cb_cls = cb_cls;
194 GNUNET_assert (NULL != (ctx->json_header =
195 curl_slist_append (NULL,
196 "Content-Type: application/json")));
202 * Callback used when downloading the reply to an HTTP request.
203 * Just appends all of the data to the `buf` in the
204 * `struct DownloadBuffer` for further processing. The size of
205 * the download is limited to #GNUNET_MAX_MALLOC_CHECKED, if
206 * the download exceeds this size, we abort with an error.
208 * @param bufptr data downloaded via HTTP
209 * @param size size of an item in @a bufptr
210 * @param nitems number of items in @a bufptr
211 * @param cls the `struct DownloadBuffer`
212 * @return number of bytes processed from @a bufptr
215 download_cb (char *bufptr,
220 struct GNUNET_CURL_DownloadBuffer *db = cls;
224 if (0 == size * nitems)
226 /* Nothing (left) to do */
229 msize = size * nitems;
230 if ( (msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
233 return 0; /* signals an error to curl */
235 db->buf = GNUNET_realloc (db->buf,
236 db->buf_size + msize);
237 buf = db->buf + db->buf_size;
238 GNUNET_memcpy (buf, bufptr, msize);
239 db->buf_size += msize;
245 * Schedule a CURL request to be executed and call the given @a jcc
246 * upon its completion. Note that the context will make use of the
247 * CURLOPT_PRIVATE facility of the CURL @a eh.
249 * This function modifies the CURL handle to add the
250 * "Content-Type: application/json" header if @a add_json is set.
252 * @param ctx context to execute the job in
253 * @param eh curl easy handle for the request, will
254 * be executed AND cleaned up
255 * @param add_json add "application/json" content type header
256 * @param jcc callback to invoke upon completion
257 * @param jcc_cls closure for @a jcc
258 * @return NULL on error (in this case, @eh is still released!)
260 struct GNUNET_CURL_Job *
261 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
264 GNUNET_CURL_JobCompletionCallback jcc,
267 struct GNUNET_CURL_Job *job;
269 if (GNUNET_YES == add_json)
271 curl_easy_setopt (eh,
276 curl_easy_cleanup (eh);
280 job = GNUNET_new (struct GNUNET_CURL_Job);
282 curl_easy_setopt (eh,
286 curl_easy_setopt (eh,
287 CURLOPT_WRITEFUNCTION,
290 curl_easy_setopt (eh,
294 curl_easy_setopt (eh,
298 curl_multi_add_handle (ctx->multi,
303 curl_easy_cleanup (eh);
307 job->easy_handle = eh;
310 job->jcc_cls = jcc_cls;
311 GNUNET_CONTAINER_DLL_insert (ctx->jobs_head,
314 ctx->cb (ctx->cb_cls);
320 * Cancel a job. Must only be called before the job completion
321 * callback is called for the respective job.
323 * @param job job to cancel
326 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
328 struct GNUNET_CURL_Context *ctx = job->ctx;
330 GNUNET_CONTAINER_DLL_remove (ctx->jobs_head,
333 GNUNET_break (CURLM_OK ==
334 curl_multi_remove_handle (ctx->multi,
336 curl_easy_cleanup (job->easy_handle);
337 GNUNET_free_non_null (job->db.buf);
343 * Obtain information about the final result about the
344 * HTTP download. If the download was successful, parses
345 * the JSON in the @a db and returns it. Also returns
346 * the HTTP @a response_code. If the download failed,
347 * the return value is NULL. The response code is set
348 * in any case, on download errors to zero.
350 * Calling this function also cleans up @a db.
352 * @param db download buffer
353 * @param eh CURL handle (to get the response code)
354 * @param[out] response_code set to the HTTP response code
355 * (or zero if we aborted the download, i.e.
356 * because the response was too big, or if
357 * the JSON we received was malformed).
358 * @return NULL if downloading a JSON reply failed.
361 download_get_result (struct GNUNET_CURL_DownloadBuffer *db,
369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
370 "Downloaded body: %.*s\n",
375 curl_easy_getinfo (eh,
376 CURLINFO_CONTENT_TYPE,
379 (0 != strcasecmp (ct,
380 "application/json")) )
382 /* No content type or explicitly not JSON, refuse to parse
383 (but keep response code) */
385 curl_easy_getinfo (eh,
386 CURLINFO_RESPONSE_CODE,
389 /* unexpected error... */
393 if (0 != db->buf_size)
394 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
395 "Did NOT detect response as JSON\n");
401 json = json_loadb (db->buf,
403 JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
411 GNUNET_free_non_null (db->buf);
417 curl_easy_getinfo (eh,
418 CURLINFO_RESPONSE_CODE,
421 /* unexpected error... */
430 * Add custom request header.
432 * @param ctx cURL context.
433 * @param header header string; will be given to the context AS IS.
434 * @return #GNUNET_OK if no errors occurred, #GNUNET_SYSERR otherwise.
437 GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx,
440 ctx->json_header = curl_slist_append (ctx->json_header,
442 if (NULL == ctx->json_header)
443 return GNUNET_SYSERR;
449 * Run the main event loop for the Taler interaction.
451 * @param ctx the library context
452 * @param rp parses the raw response returned from
454 * @param rc cleans/frees the response
457 GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx,
458 GNUNET_CURL_RawParser rp,
459 GNUNET_CURL_ResponseCleaner rc)
462 struct GNUNET_CURL_Job *job;
468 (void) curl_multi_perform (ctx->multi,
470 while (NULL != (cmsg = curl_multi_info_read (ctx->multi,
473 /* Only documented return value is CURLMSG_DONE */
474 GNUNET_break (CURLMSG_DONE == cmsg->msg);
475 GNUNET_assert (CURLE_OK ==
476 curl_easy_getinfo (cmsg->easy_handle,
479 GNUNET_assert (job->ctx == ctx);
481 response = rp (&job->db,
487 double total_as_double = 0;
488 struct GNUNET_TIME_Relative total;
489 struct UrlRequestData *urd;
491 res = curl_easy_getinfo (cmsg->easy_handle, CURLINFO_TOTAL_TIME, &total_as_double);
492 GNUNET_break (CURLE_OK == res);
493 curl_easy_getinfo (cmsg->easy_handle, CURLINFO_EFFECTIVE_URL, &url);
494 total.rel_value_us = total_as_double * 1000 * 1000;
495 urd = get_url_benchmark_data (url, (unsigned int) response_code);
497 urd->time = GNUNET_TIME_relative_add (urd->time, total);
498 urd->time_max = GNUNET_TIME_relative_max (total, urd->time_max);
501 job->jcc (job->jcc_cls,
505 GNUNET_CURL_job_cancel (job);
511 * Run the main event loop for the Taler interaction.
513 * @param ctx the library context
516 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
519 GNUNET_CURL_perform2 (ctx,
521 (GNUNET_CURL_ResponseCleaner) &json_decref);
526 * Obtain the information for a select() call to wait until
527 * #GNUNET_CURL_perform() is ready again. Note that calling
528 * any other GNUNET_CURL-API may also imply that the library
529 * is again ready for #GNUNET_CURL_perform().
531 * Basically, a client should use this API to prepare for select(),
532 * then block on select(), then call #GNUNET_CURL_perform() and then
533 * start again until the work with the context is done.
535 * This function will NOT zero out the sets and assumes that @a max_fd
536 * and @a timeout are already set to minimal applicable values. It is
537 * safe to give this API FD-sets and @a max_fd and @a timeout that are
538 * already initialized to some other descriptors that need to go into
541 * @param ctx context to get the event loop information for
542 * @param read_fd_set will be set for any pending read operations
543 * @param write_fd_set will be set for any pending write operations
544 * @param except_fd_set is here because curl_multi_fdset() has this argument
545 * @param max_fd set to the highest FD included in any set;
546 * if the existing sets have no FDs in it, the initial
547 * value should be "-1". (Note that `max_fd + 1` will need
548 * to be passed to select().)
549 * @param timeout set to the timeout in milliseconds (!); -1 means
550 * no timeout (NULL, blocking forever is OK), 0 means to
551 * proceed immediately with #GNUNET_CURL_perform().
554 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
556 fd_set *write_fd_set,
557 fd_set *except_fd_set,
565 GNUNET_assert (CURLM_OK ==
566 curl_multi_fdset (ctx->multi,
572 *max_fd = GNUNET_MAX (m, *max_fd);
573 GNUNET_assert (CURLM_OK ==
574 curl_multi_timeout (ctx->multi,
577 /* Only if what we got back from curl is smaller than what we
578 already had (-1 == infinity!), then update timeout */
579 if ( (to < *timeout) &&
582 if ( (-1 == (*timeout)) &&
583 (NULL != ctx->jobs_head) )
589 * Cleanup library initialisation resources. This function should be called
590 * after using this library to cleanup the resources occupied during library's
593 * @param ctx the library context
596 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
598 /* all jobs must have been cancelled at this time, assert this */
599 GNUNET_assert (NULL == ctx->jobs_head);
600 curl_share_cleanup (ctx->share);
601 curl_multi_cleanup (ctx->multi);
602 curl_slist_free_all (ctx->json_header);
608 * Initial global setup logic, specifically runs the Curl setup.
610 __attribute__ ((constructor))
612 GNUNET_CURL_constructor__ (void)
616 if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
618 CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR,
627 * Cleans up after us, specifically runs the Curl cleanup.
629 __attribute__ ((destructor))
631 GNUNET_CURL_destructor__ (void)
635 curl_global_cleanup ();