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 "gnunet_curl_lib.h"
31 #include "../util/benchmark.h"
36 * Log error related to CURL operations.
38 * @param type log level
39 * @param function which function failed to run
40 * @param code what was the curl error code
42 #define CURL_STRERROR(type, function, code) \
44 "Curl function `%s' has failed at `%s:%d' with error: %s\n", \
48 curl_easy_strerror (code));
51 * Print JSON parsing related error information
53 #define JSON_WARN(error) \
54 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, \
55 "JSON parsing failed at %s:%u: %s (%s)\n", \
63 * Failsafe flag. Raised if our constructor fails to initialize
69 * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`.
71 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;
109 * Headers used for this job, the list needs to be freed
110 * after the job has finished.
112 struct curl_slist *job_headers;
119 struct GNUNET_CURL_Context
132 * We keep jobs in a DLL.
134 struct GNUNET_CURL_Job *jobs_head;
137 * We keep jobs in a DLL.
139 struct GNUNET_CURL_Job *jobs_tail;
142 * Headers common for all requests in the context.
144 struct curl_slist *common_headers;
147 * If non-NULL, the async scope ID is sent in a request
148 * header of this name.
150 const char *async_scope_id_header;
153 * Function we need to call whenever the event loop's
154 * socket set changed.
156 GNUNET_CURL_RescheduleCallback cb;
166 * Initialise this library. This function should be called before using any of
167 * the following functions.
169 * @param cb function to call when rescheduling is required
170 * @param cb_cls closure for @a cb
171 * @return library context
173 struct GNUNET_CURL_Context *
174 GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb, void *cb_cls)
176 struct GNUNET_CURL_Context *ctx;
182 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Curl was not initialised properly\n");
185 if (NULL == (multi = curl_multi_init ()))
187 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
188 "Failed to create a Curl multi handle\n");
191 if (NULL == (share = curl_share_init ()))
193 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
194 "Failed to create a Curl share handle\n");
197 ctx = GNUNET_new (struct GNUNET_CURL_Context);
199 ctx->cb_cls = cb_cls;
207 * Enable sending the async scope ID as a header.
209 * @param ctx the context to enable this for
210 * @param header_name name of the header to send.
213 GNUNET_CURL_enable_async_scope_header (struct GNUNET_CURL_Context *ctx,
214 const char *header_name)
216 ctx->async_scope_id_header = header_name;
221 * Callback used when downloading the reply to an HTTP request.
222 * Just appends all of the data to the `buf` in the
223 * `struct DownloadBuffer` for further processing. The size of
224 * the download is limited to #GNUNET_MAX_MALLOC_CHECKED, if
225 * the download exceeds this size, we abort with an error.
227 * @param bufptr data downloaded via HTTP
228 * @param size size of an item in @a bufptr
229 * @param nitems number of items in @a bufptr
230 * @param cls the `struct DownloadBuffer`
231 * @return number of bytes processed from @a bufptr
234 download_cb (char *bufptr, size_t size, size_t nitems, void *cls)
236 struct GNUNET_CURL_DownloadBuffer *db = cls;
240 if (0 == size * nitems)
242 /* Nothing (left) to do */
245 msize = size * nitems;
246 if ((msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED)
249 return 0; /* signals an error to curl */
251 db->buf = GNUNET_realloc (db->buf, db->buf_size + msize);
252 buf = db->buf + db->buf_size;
253 GNUNET_memcpy (buf, bufptr, msize);
254 db->buf_size += msize;
260 * Schedule a CURL request to be executed and call the given @a jcc
261 * upon its completion. Note that the context will make use of the
262 * CURLOPT_PRIVATE facility of the CURL @a eh.
264 * This function modifies the CURL handle to add the
265 * "Content-Type: application/json" header if @a add_json is set.
267 * @param ctx context to execute the job in
268 * @param eh curl easy handle for the request, will be executed AND
269 * cleaned up. NOTE: the handle should _never_ have gotten
270 * any headers list, as that would then be ovverridden by
271 * @a jcc. Therefore, always pass custom headers as the
272 * @a job_headers parameter.
273 * @param job_headers extra headers to add for this request
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_add2 (struct GNUNET_CURL_Context *ctx,
281 const struct curl_slist *job_headers,
282 GNUNET_CURL_JobCompletionCallback jcc,
285 struct GNUNET_CURL_Job *job;
286 struct curl_slist *all_headers = NULL;
288 for (const struct curl_slist *curr = job_headers; curr != NULL;
291 GNUNET_assert (NULL !=
292 (all_headers = curl_slist_append (all_headers, curr->data)));
295 for (const struct curl_slist *curr = ctx->common_headers; curr != NULL;
298 GNUNET_assert (NULL !=
299 (all_headers = curl_slist_append (all_headers, curr->data)));
302 if (NULL != ctx->async_scope_id_header)
304 struct GNUNET_AsyncScopeSave scope;
306 GNUNET_async_scope_get (&scope);
307 if (GNUNET_YES == scope.have_scope)
309 char *aid_header = NULL;
311 GNUNET_STRINGS_data_to_string_alloc (&scope.scope_id,
313 struct GNUNET_AsyncScopeId));
314 GNUNET_assert (NULL != aid_header);
315 GNUNET_assert (NULL != curl_slist_append (all_headers, aid_header));
316 GNUNET_free (aid_header);
320 if (CURLE_OK != curl_easy_setopt (eh, CURLOPT_HTTPHEADER, all_headers))
323 curl_slist_free_all (all_headers);
324 curl_easy_cleanup (eh);
328 job = GNUNET_new (struct GNUNET_CURL_Job);
329 job->job_headers = all_headers;
331 if ((CURLE_OK != curl_easy_setopt (eh, CURLOPT_PRIVATE, job)) ||
333 curl_easy_setopt (eh, CURLOPT_WRITEFUNCTION, &download_cb)) ||
334 (CURLE_OK != curl_easy_setopt (eh, CURLOPT_WRITEDATA, &job->db)) ||
335 (CURLE_OK != curl_easy_setopt (eh, CURLOPT_SHARE, ctx->share)) ||
336 (CURLM_OK != curl_multi_add_handle (ctx->multi, eh)))
340 curl_easy_cleanup (eh);
344 job->easy_handle = eh;
347 job->jcc_cls = jcc_cls;
348 GNUNET_CONTAINER_DLL_insert (ctx->jobs_head, ctx->jobs_tail, job);
349 ctx->cb (ctx->cb_cls);
355 * Schedule a CURL request to be executed and call the given @a jcc
356 * upon its completion. Note that the context will make use of the
357 * CURLOPT_PRIVATE facility of the CURL @a eh.
359 * This function modifies the CURL handle to add the
360 * "Content-Type: application/json" header if @a add_json is set.
362 * @param ctx context to execute the job in
363 * @param eh curl easy handle for the request, will
364 * be executed AND cleaned up
365 * @param add_json add "application/json" content type header
366 * @param jcc callback to invoke upon completion
367 * @param jcc_cls closure for @a jcc
368 * @return NULL on error (in this case, @eh is still released!)
370 struct GNUNET_CURL_Job *
371 GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx,
374 GNUNET_CURL_JobCompletionCallback jcc,
377 struct GNUNET_CURL_Job *job;
378 struct curl_slist *job_headers = NULL;
380 if (GNUNET_YES == add_json)
383 NULL != (job_headers =
384 curl_slist_append (NULL, "Content-Type: application/json")));
387 job = GNUNET_CURL_job_add2 (ctx, eh, job_headers, jcc, jcc_cls);
388 curl_slist_free_all (job_headers);
394 * Cancel a job. Must only be called before the job completion
395 * callback is called for the respective job.
397 * @param job job to cancel
400 GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job)
402 struct GNUNET_CURL_Context *ctx = job->ctx;
404 GNUNET_CONTAINER_DLL_remove (ctx->jobs_head, ctx->jobs_tail, job);
405 GNUNET_break (CURLM_OK ==
406 curl_multi_remove_handle (ctx->multi, job->easy_handle));
407 curl_easy_cleanup (job->easy_handle);
408 GNUNET_free_non_null (job->db.buf);
409 curl_slist_free_all (job->job_headers);
415 * Obtain information about the final result about the
416 * HTTP download. If the download was successful, parses
417 * the JSON in the @a db and returns it. Also returns
418 * the HTTP @a response_code. If the download failed,
419 * the return value is NULL. The response code is set
420 * in any case, on download errors to zero.
422 * Calling this function also cleans up @a db.
424 * @param db download buffer
425 * @param eh CURL handle (to get the response code)
426 * @param[out] response_code set to the HTTP response code
427 * (or zero if we aborted the download, i.e.
428 * because the response was too big, or if
429 * the JSON we received was malformed).
430 * @return NULL if downloading a JSON reply failed.
433 GNUNET_CURL_download_get_result_ (struct GNUNET_CURL_DownloadBuffer *db,
441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
442 "Downloaded body: %.*s\n",
446 if ((CURLE_OK != curl_easy_getinfo (eh, CURLINFO_CONTENT_TYPE, &ct)) ||
447 (NULL == ct) || (0 != strcasecmp (ct, "application/json")))
449 /* No content type or explicitly not JSON, refuse to parse
450 (but keep response code) */
452 curl_easy_getinfo (eh, CURLINFO_RESPONSE_CODE, response_code))
454 /* unexpected error... */
458 if (0 != db->buf_size)
459 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
460 "Did NOT detect response as JSON\n");
466 json = json_loadb (db->buf,
468 JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK,
476 GNUNET_free_non_null (db->buf);
482 curl_easy_getinfo (eh, CURLINFO_RESPONSE_CODE, response_code))
484 /* unexpected error... */
494 * Add custom request header.
496 * @param ctx cURL context.
497 * @param header header string; will be given to the context AS IS.
498 * @return #GNUNET_OK if no errors occurred, #GNUNET_SYSERR otherwise.
501 GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx, const char *header)
503 ctx->common_headers = curl_slist_append (ctx->common_headers, header);
504 if (NULL == ctx->common_headers)
505 return GNUNET_SYSERR;
512 * Run the main event loop for the Taler interaction.
514 * @param ctx the library context
515 * @param rp parses the raw response returned from
517 * @param rc cleans/frees the response
520 GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx,
521 GNUNET_CURL_RawParser rp,
522 GNUNET_CURL_ResponseCleaner rc)
528 (void) curl_multi_perform (ctx->multi, &n_running);
529 while (NULL != (cmsg = curl_multi_info_read (ctx->multi, &n_completed)))
531 struct GNUNET_CURL_Job *job;
535 /* Only documented return value is CURLMSG_DONE */
536 GNUNET_break (CURLMSG_DONE == cmsg->msg);
537 GNUNET_assert (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
540 GNUNET_assert (job->ctx == ctx);
542 response = rp (&job->db, job->easy_handle, &response_code);
546 double total_as_double = 0;
547 struct GNUNET_TIME_Relative total;
548 struct UrlRequestData *urd;
549 /* Some care required, as curl is using data types (long vs curl_off_t vs
550 * double) inconsistently to store byte count. */
551 curl_off_t size_curl = 0;
553 uint64_t bytes_sent = 0;
554 uint64_t bytes_received = 0;
556 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
559 total.rel_value_us = total_as_double * 1000 * 1000;
561 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
562 CURLINFO_EFFECTIVE_URL,
565 /* HEADER_SIZE + SIZE_DOWNLOAD_T is hopefully the total
566 number of bytes received, not clear from curl docs. */
568 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
569 CURLINFO_HEADER_SIZE,
571 bytes_received += size_long;
573 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
574 CURLINFO_SIZE_DOWNLOAD_T,
576 bytes_received += size_curl;
578 /* REQUEST_SIZE + SIZE_UPLOAD_T is hopefully the total number of bytes
579 sent, again docs are not completely clear. */
581 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
582 CURLINFO_REQUEST_SIZE,
584 bytes_sent += size_long;
586 /* We obtain this value to check an invariant, but never use it otherwise. */
587 GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle,
588 CURLINFO_SIZE_UPLOAD_T,
591 /* CURLINFO_SIZE_UPLOAD_T <= CURLINFO_REQUEST_SIZE should
594 curl -w "foo%{size_request} -XPOST --data "ABC" $URL
595 the CURLINFO_REQUEST_SIZE should be the whole size of the request
596 including headers and body.
597 */GNUNET_break (size_curl <= size_long);
599 urd = get_url_benchmark_data (url, (unsigned int) response_code);
601 urd->time = GNUNET_TIME_relative_add (urd->time, total);
602 urd->time_max = GNUNET_TIME_relative_max (total, urd->time_max);
603 urd->bytes_sent += bytes_sent;
604 urd->bytes_received += bytes_received;
607 job->jcc (job->jcc_cls, response_code, response);
609 GNUNET_CURL_job_cancel (job);
615 * Run the main event loop for the Taler interaction.
617 * @param ctx the library context
620 GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx)
622 GNUNET_CURL_perform2 (ctx,
623 &GNUNET_CURL_download_get_result_,
624 (GNUNET_CURL_ResponseCleaner) & json_decref);
629 * Obtain the information for a select() call to wait until
630 * #GNUNET_CURL_perform() is ready again. Note that calling
631 * any other GNUNET_CURL-API may also imply that the library
632 * is again ready for #GNUNET_CURL_perform().
634 * Basically, a client should use this API to prepare for select(),
635 * then block on select(), then call #GNUNET_CURL_perform() and then
636 * start again until the work with the context is done.
638 * This function will NOT zero out the sets and assumes that @a max_fd
639 * and @a timeout are already set to minimal applicable values. It is
640 * safe to give this API FD-sets and @a max_fd and @a timeout that are
641 * already initialized to some other descriptors that need to go into
644 * @param ctx context to get the event loop information for
645 * @param read_fd_set will be set for any pending read operations
646 * @param write_fd_set will be set for any pending write operations
647 * @param except_fd_set is here because curl_multi_fdset() has this argument
648 * @param max_fd set to the highest FD included in any set;
649 * if the existing sets have no FDs in it, the initial
650 * value should be "-1". (Note that `max_fd + 1` will need
651 * to be passed to select().)
652 * @param timeout set to the timeout in milliseconds (!); -1 means
653 * no timeout (NULL, blocking forever is OK), 0 means to
654 * proceed immediately with #GNUNET_CURL_perform().
657 GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx,
659 fd_set *write_fd_set,
660 fd_set *except_fd_set,
668 GNUNET_assert (CURLM_OK == curl_multi_fdset (ctx->multi,
674 *max_fd = GNUNET_MAX (m, *max_fd);
675 GNUNET_assert (CURLM_OK == curl_multi_timeout (ctx->multi, &to));
677 /* Only if what we got back from curl is smaller than what we
678 already had (-1 == infinity!), then update timeout */
679 if ((to < *timeout) && (-1 != to))
681 if ((-1 == (*timeout)) && (NULL != ctx->jobs_head))
687 * Cleanup library initialisation resources. This function should be called
688 * after using this library to cleanup the resources occupied during library's
691 * @param ctx the library context
694 GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx)
696 /* all jobs must have been cancelled at this time, assert this */
697 GNUNET_assert (NULL == ctx->jobs_head);
698 curl_share_cleanup (ctx->share);
699 curl_multi_cleanup (ctx->multi);
700 curl_slist_free_all (ctx->common_headers);
706 * Initial global setup logic, specifically runs the Curl setup.
708 __attribute__ ((constructor)) void
709 GNUNET_CURL_constructor__ (void)
713 if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT)))
715 CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR, "curl_global_init", ret);
722 * Cleans up after us, specifically runs the Curl cleanup.
724 __attribute__ ((destructor)) void
725 GNUNET_CURL_destructor__ (void)
729 curl_global_cleanup ();