2 This file is part of GNUnet.
3 Copyright (C) 2006-2013 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 * @file include/gnunet_common.h
23 * @brief commonly used definitions; globals in this file
24 * are exempt from the rule that the module name ("common")
25 * must be part of the symbol name.
27 * @author Christian Grothoff
29 * @author Martin Schanzenbach
31 * @defgroup logging Logging
32 * @see [Documentation](https://gnunet.org/logging)
34 * @defgroup memory Memory management
36 #ifndef GNUNET_COMMON_H
37 #define GNUNET_COMMON_H
41 #include <sys/socket.h>
44 #include <netinet/in.h>
52 #ifdef HAVE_SYS_TYPES_H
53 #include <sys/types.h>
55 #ifdef HAVE_SYS_SOCKET_H
56 #include <sys/socket.h>
60 #ifdef HAVE_BYTESWAP_H
66 #if 0 /* keep Emacsens' auto-indent happy */
72 * Version of the API (for entire gnunetutil.so library).
74 #define GNUNET_UTIL_VERSION 0x000A0103
78 * Named constants for return values. The following invariants hold:
79 * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK !=
80 * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO !=
81 * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`.
84 #define GNUNET_SYSERR -1
88 #define GNUNET_MIN(a, b) (((a) < (b)) ? (a) : (b))
90 #define GNUNET_MAX(a, b) (((a) > (b)) ? (a) : (b))
92 /* some systems use one underscore only, and mingw uses no underscore... */
95 #define __BYTE_ORDER _BYTE_ORDER
98 #define __BYTE_ORDER BYTE_ORDER
104 #define __BIG_ENDIAN _BIG_ENDIAN
107 #define __BIG_ENDIAN BIG_ENDIAN
111 #ifndef __LITTLE_ENDIAN
112 #ifdef _LITTLE_ENDIAN
113 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
116 #define __LITTLE_ENDIAN LITTLE_ENDIAN
122 * wrap va_arg for enums
124 #define GNUNET_VA_ARG_ENUM(va, X) ((enum X) va_arg (va, int))
129 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
130 * tree where gnunet_config.h is unavailable
132 #ifndef GNUNET_EXTRA_LOGGING
133 #define GNUNET_EXTRA_LOGGING 0
140 #if __BYTE_ORDER == __LITTLE_ENDIAN
141 #define GNUNET_htobe16(x) __bswap_16 (x)
142 #define GNUNET_htole16(x) (x)
143 #define GNUNET_be16toh(x) __bswap_16 (x)
144 #define GNUNET_le16toh(x) (x)
146 #define GNUNET_htobe32(x) __bswap_32 (x)
147 #define GNUNET_htole32(x) (x)
148 #define GNUNET_be32toh(x) __bswap_32 (x)
149 #define GNUNET_le32toh(x) (x)
151 #define GNUNET_htobe64(x) __bswap_64 (x)
152 #define GNUNET_htole64(x) (x)
153 #define GNUNET_be64toh(x) __bswap_64 (x)
154 #define GNUNET_le64toh(x) (x)
156 #if __BYTE_ORDER == __BIG_ENDIAN
157 #define GNUNET_htobe16(x) (x)
158 #define GNUNET_htole16(x) __bswap_16 (x)
159 #define GNUNET_be16toh(x) (x)
160 #define GNUNET_le16toh(x) __bswap_16 (x)
162 #define GNUNET_htobe32(x) (x)
163 #define GNUNET_htole32(x) __bswap_32 (x)
164 #define GNUNET_be32toh(x) (x)
165 #define GNUNET_le32toh(x) __bswap_32 (x)
167 #define GNUNET_htobe64(x) (x)
168 #define GNUNET_htole64(x) __bswap_64 (x)
169 #define GNUNET_be64toh(x) (x)
170 #define GNUNET_le64toh(x) __bswap_64 (x)
175 * Macro used to avoid using 0 for the length of a variable-size
176 * array (Non-Zero-Length).
178 * Basically, C standard says that "int[n] x;" is undefined if n=0.
179 * This was supposed to prevent issues with pointer aliasing.
180 * However, C compilers may conclude that n!=0 as n=0 would be
181 * undefined, and then optimize under the assumption n!=0, which
182 * could cause actual issues. Hence, when initializing an array
183 * on the stack with a variable-length that might be zero, write
184 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
186 #define GNUNET_NZL(l) GNUNET_MAX (1, l)
190 * gcc-ism to get packed structs.
192 #define GNUNET_PACKED __attribute__ ((packed))
195 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
197 #define GNUNET_GCC_STRUCT_LAYOUT
200 * gcc-ism to force alignment; we use this to align char-arrays
201 * that may then be cast to 'struct's. See also gcc
204 #ifdef __BIGGEST_ALIGNMENT__
205 #define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__)))
207 #define GNUNET_ALIGN __attribute__ ((aligned (8)))
211 * gcc-ism to document unused arguments
213 #define GNUNET_UNUSED __attribute__ ((unused))
216 * gcc-ism to document functions that don't return
218 #define GNUNET_NORETURN __attribute__ ((noreturn))
221 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
223 #define GNUNET_NETWORK_STRUCT_BEGIN
226 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
228 #define GNUNET_NETWORK_STRUCT_END
230 /* ************************ super-general types *********************** */
232 GNUNET_NETWORK_STRUCT_BEGIN
235 * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512.
237 struct GNUNET_HashCode
239 uint32_t bits[512 / 8 / sizeof(uint32_t)]; /* = 16 */
244 * @brief A 256-bit hashcode. Used under special conditions, like when space
245 * is critical and security is not impacted by it.
247 struct GNUNET_ShortHashCode
249 uint32_t bits[256 / 8 / sizeof(uint32_t)]; /* = 8 */
254 * A UUID, a 128 bit random value.
266 * Header for all communications.
268 struct GNUNET_MessageHeader
271 * The length of the struct (in bytes, including the length field itself),
272 * in big-endian format.
274 uint16_t size GNUNET_PACKED;
277 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
279 uint16_t type GNUNET_PACKED;
284 * Answer from service to client about last operation.
286 struct GNUNET_OperationResultMessage
288 struct GNUNET_MessageHeader header;
290 uint32_t reserved GNUNET_PACKED;
295 uint64_t op_id GNUNET_PACKED;
298 * Status code for the operation.
300 uint64_t result_code GNUNET_PACKED;
302 /* Followed by data. */
307 * Identifier for an asynchronous execution context.
309 struct GNUNET_AsyncScopeId
311 uint32_t bits[16 / sizeof(uint32_t)]; /* = 16 bytes */
314 GNUNET_NETWORK_STRUCT_END
318 * Saved async scope identifier or root scope.
320 struct GNUNET_AsyncScopeSave
323 * Saved scope. Unused if 'have_scope==GNUNET_NO'.
325 struct GNUNET_AsyncScopeId scope_id;
328 * GNUNET_YES unless this saved scope is the unnamed root scope.
335 * Function called with a filename.
338 * @param filename complete filename (absolute path)
339 * @return #GNUNET_OK to continue to iterate,
340 * #GNUNET_NO to stop iteration with no error,
341 * #GNUNET_SYSERR to abort iteration with error!
343 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
347 * Generic continuation callback.
349 * @param cls Closure.
351 typedef void (*GNUNET_ContinuationCallback) (void *cls);
355 * Function called with the result of an asynchronous operation.
360 * Result code for the operation.
362 * Data result for the operation.
366 typedef void (*GNUNET_ResultCallback) (void *cls,
372 /* ****************************** logging ***************************** */
378 enum GNUNET_ErrorType
380 GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
381 GNUNET_ERROR_TYPE_NONE = 0,
382 GNUNET_ERROR_TYPE_ERROR = 1,
383 GNUNET_ERROR_TYPE_WARNING = 2,
384 /* UX: We need a message type that is output by
385 * default without looking like there is a problem.
387 GNUNET_ERROR_TYPE_MESSAGE = 4,
388 GNUNET_ERROR_TYPE_INFO = 8,
389 GNUNET_ERROR_TYPE_DEBUG = 16,
390 GNUNET_ERROR_TYPE_INVALID = 32,
391 GNUNET_ERROR_TYPE_BULK = 64
397 * User-defined handler for log messages.
400 * @param kind severeity
401 * @param component what component is issuing the message?
402 * @param date when was the message logged?
403 * @param message what is the message
405 typedef void (*GNUNET_Logger) (void *cls,
406 enum GNUNET_ErrorType kind,
407 const char *component,
409 const char *message);
414 * Get the number of log calls that are going to be skipped
416 * @return number of log calls to be ignored
419 GNUNET_get_log_skip (void);
422 #if ! defined(GNUNET_CULL_LOGGING)
424 GNUNET_get_log_call_status (int caller_level,
427 const char *function,
437 * @param kind how serious is the error?
438 * @param message what is the message (format string)
439 * @param ... arguments for format string
442 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
443 __attribute__ ((format (printf, 2, 3)));
446 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
447 #define _GNUNET_BOOLEAN_EXPR(expr) \
449 int _gnunet_boolean_var_; \
451 _gnunet_boolean_var_ = 1; \
453 _gnunet_boolean_var_ = 0; \
454 _gnunet_boolean_var_; \
456 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1))
457 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0))
459 #define GN_LIKELY(expr) (expr)
460 #define GN_UNLIKELY(expr) (expr)
463 #if ! defined(GNUNET_LOG_CALL_STATUS)
464 #define GNUNET_LOG_CALL_STATUS -1
470 * Log function that specifies an alternative component.
471 * This function should be used by plugins.
473 * @param kind how serious is the error?
474 * @param comp component responsible for generating the message
475 * @param message what is the message (format string)
476 * @param ... arguments for format string
479 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
484 #if ! defined(GNUNET_CULL_LOGGING)
485 #define GNUNET_log_from(kind, comp, ...) \
488 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
489 if ((GNUNET_EXTRA_LOGGING > 0) || \
490 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
492 if (GN_UNLIKELY (log_call_enabled == -1)) \
494 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
499 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
501 GNUNET_log_skip (-1, GNUNET_NO); \
505 if (GN_UNLIKELY (log_call_enabled)) \
506 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \
511 #define GNUNET_log(kind, ...) \
514 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
515 if ((GNUNET_EXTRA_LOGGING > 0) || \
516 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
518 if (GN_UNLIKELY (log_call_enabled == -1)) \
520 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
525 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
527 GNUNET_log_skip (-1, GNUNET_NO); \
531 if (GN_UNLIKELY (log_call_enabled)) \
532 GNUNET_log_nocheck ((kind), __VA_ARGS__); \
537 #define GNUNET_log(...)
538 #define GNUNET_log_from(...)
544 * Log error message about missing configuration option.
546 * @param kind log level
547 * @param section section with missing option
548 * @param option name of missing option
551 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
558 * Log error message about invalid configuration option value.
560 * @param kind log level
561 * @param section section with invalid option
562 * @param option name of invalid option
563 * @param required what is required that is invalid about the option
566 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
569 const char *required);
574 * Abort the process, generate a core dump if possible.
575 * Most code should use `GNUNET_assert (0)` instead to
576 * first log the location of the failure.
579 GNUNET_abort_ (void) GNUNET_NORETURN;
584 * Ignore the next @a n calls to the log function.
586 * @param n number of log calls to ignore (could be negative)
587 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
590 GNUNET_log_skip (int n, int check_reset);
597 * @param comp default component to use
598 * @param loglevel what types of messages should be logged
599 * @param logfile change logging to logfile (use NULL to keep stderr)
600 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
603 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile);
608 * Add a custom logger. Note that installing any custom logger
609 * will disable the standard logger. When multiple custom loggers
610 * are installed, all will be called. The standard logger will
611 * only be used if no custom loggers are present.
613 * @param logger log function
614 * @param logger_cls closure for @a logger
617 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
622 * Remove a custom logger.
624 * @param logger log function
625 * @param logger_cls closure for @a logger
628 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
633 * Convert a short hash value to a string (for printing debug messages).
634 * This is one of the very few calls in the entire API that is
637 * @param shc the hash code
641 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
646 * Convert a UUID to a string (for printing debug messages).
647 * This is one of the very few calls in the entire API that is
650 * @param uuid the UUID
654 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid);
659 * Convert a hash value to a string (for printing debug messages).
660 * This is one of the very few calls in the entire API that is
663 * @param hc the hash code
667 GNUNET_h2s (const struct GNUNET_HashCode *hc);
672 * Convert a hash value to a string (for printing debug messages).
673 * This is one of the very few calls in the entire API that is
674 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
675 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
676 * used within the same log statement.
678 * @param hc the hash code
682 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
687 * Convert a hash value to a string (for printing debug messages).
688 * This prints all 104 characters of a hashcode!
689 * This is one of the very few calls in the entire API that is
692 * @param hc the hash code
696 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
700 * Public key. Details in gnunet_util_crypto.h.
702 struct GNUNET_CRYPTO_EddsaPublicKey;
706 * Public key. Details in gnunet_util_crypto.h.
708 struct GNUNET_CRYPTO_EcdhePublicKey;
713 * Convert a public key value to a string (for printing debug messages).
714 * This is one of the very few calls in the entire API that is
717 * @param hc the hash code
721 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
726 * Convert a public key value to a string (for printing debug messages).
727 * This is one of the very few calls in the entire API that is
730 * @param hc the hash code
734 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
739 * Convert a public key value to a string (for printing debug messages).
740 * This is one of the very few calls in the entire API that is
743 * @param hc the hash code
747 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
752 * Convert a public key value to a string (for printing debug messages).
753 * This is one of the very few calls in the entire API that is
756 * @param hc the hash code
760 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
765 * Convert a peer identity to a string (for printing debug messages).
766 * This is one of the very few calls in the entire API that is
769 * @param pid the peer identity
770 * @return string form of the pid; will be overwritten by next
771 * call to #GNUNET_i2s().
774 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
779 * Convert a peer identity to a string (for printing debug messages).
780 * This is one of the very few calls in the entire API that is
781 * NOT reentrant! Identical to #GNUNET_i2s(), except that another
782 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
783 * used within the same log statement.
785 * @param pid the peer identity
786 * @return string form of the pid; will be overwritten by next
787 * call to #GNUNET_i2s().
790 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
795 * Convert a peer identity to a string (for printing debug messages).
796 * This is one of the very few calls in the entire API that is
799 * @param pid the peer identity
800 * @return string form of the pid; will be overwritten by next
801 * call to #GNUNET_i2s_full().
804 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
809 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
810 * (for printing debug messages). This is one of the very few calls
811 * in the entire API that is NOT reentrant!
813 * @param addr the address
814 * @param addrlen the length of the @a addr
815 * @return nicely formatted string for the address
816 * will be overwritten by next call to #GNUNET_a2s().
819 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen);
824 * Convert error type to string.
826 * @param kind type to convert
827 * @return string corresponding to the type
830 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
835 * Use this for fatal errors that cannot be handled
837 #define GNUNET_assert(cond) \
842 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
843 _ ("Assertion failed at %s:%d. Aborting.\n"), \
853 * Use this for fatal errors that cannot be handled
855 #define GNUNET_assert_at(cond, f, l) \
860 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
861 _ ("Assertion failed at %s:%d. Aborting.\n"), \
871 * Use this for fatal errors that cannot be handled
873 * @param cond Condition to evaluate
874 * @param comp Component string to use for logging
876 #define GNUNET_assert_from(cond, comp) \
881 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \
883 _ ("Assertion failed at %s:%d. Aborting.\n"), \
893 * Use this for internal assertion violations that are
894 * not fatal (can be handled) but should not occur.
896 #define GNUNET_break(cond) \
901 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
902 _ ("Assertion failed at %s:%d.\n"), \
911 * Use this for assertion violations caused by other
912 * peers (i.e. protocol violations). We do not want to
913 * confuse end-users (say, some other peer runs an
914 * older, broken or incompatible GNUnet version), but
915 * we still want to see these problems during
916 * development and testing. "OP == other peer".
918 #define GNUNET_break_op(cond) \
923 GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \
924 _ ("External protocol violation detected at %s:%d.\n"), \
933 * Log an error message at log-level 'level' that indicates
934 * a failure of the command 'cmd' with the message given
935 * by strerror(errno).
937 #define GNUNET_log_strerror(level, cmd) \
941 _ ("`%s' failed at %s:%d with error: %s\n"), \
951 * Log an error message at log-level 'level' that indicates
952 * a failure of the command 'cmd' with the message given
953 * by strerror(errno).
955 #define GNUNET_log_from_strerror(level, component, cmd) \
958 GNUNET_log_from (level, \
960 _ ("`%s' failed at %s:%d with error: %s\n"), \
970 * Log an error message at log-level 'level' that indicates
971 * a failure of the command 'cmd' with the message given
972 * by strerror(errno).
974 #define GNUNET_log_strerror_file(level, cmd, filename) \
978 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
989 * Log an error message at log-level 'level' that indicates
990 * a failure of the command 'cmd' with the message given
991 * by strerror(errno).
993 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) \
996 GNUNET_log_from (level, \
998 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
1003 strerror (errno)); \
1006 /* ************************* endianess conversion ****************** */
1010 #define GNUNET_htonll(n) htobe64 (n)
1014 * Convert unsigned 64-bit integer to network byte order.
1017 * The value in host byte order.
1019 * @return The same value in network byte order.
1022 GNUNET_htonll (uint64_t n);
1029 #define GNUNET_ntohll(n) be64toh (n)
1033 * Convert unsigned 64-bit integer to host byte order.
1036 * The value in network byte order.
1038 * @return The same value in host byte order.
1041 GNUNET_ntohll (uint64_t n);
1047 * Convert double to network byte order.
1050 * The value in host byte order.
1052 * @return The same value in network byte order.
1055 GNUNET_hton_double (double d);
1059 * Convert double to host byte order
1062 * The value in network byte order.
1064 * @return The same value in host byte order.
1067 GNUNET_ntoh_double (double d);
1070 /* ************************* allocation functions ****************** */
1074 * Maximum allocation with GNUNET_malloc macro.
1076 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
1080 * Allocate a struct or union of the given @a type.
1081 * Wrapper around #GNUNET_malloc that returns a pointer
1082 * to the newly created object of the correct type.
1084 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1086 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof(type))
1090 * Compare memory in @a a and @a b, where both must be of
1091 * the same pointer type.
1093 #define GNUNET_memcmp(a, b) \
1095 const typeof (*b) * _a = (a); \
1096 const typeof (*a) * _b = (b); \
1097 memcmp (_a, _b, sizeof(*a)); \
1102 * Check that memory in @a a is all zeros. @a a must be a pointer.
1104 * @param a pointer to a struct which should be tested for the
1105 * entire memory being zero'ed out.
1106 * @return 0 if a is zero, non-zero otherwise
1108 #define GNUNET_is_zero(a) \
1110 static const typeof (*a) _z; \
1111 memcmp ((a), &_z, sizeof(_z)); \
1116 * Call memcpy() but check for @a n being 0 first. In the latter
1117 * case, it is now safe to pass NULL for @a src or @a dst.
1118 * Unlike traditional memcpy(), returns nothing.
1120 * @param dst destination of the copy, may be NULL if @a n is zero
1121 * @param src source of the copy, may be NULL if @a n is zero
1122 * @param n number of bytes to copy
1124 #define GNUNET_memcpy(dst, src, n) \
1129 (void) memcpy (dst, src, n); \
1136 * Allocate a size @a n array with structs or unions of the given @a type.
1137 * Wrapper around #GNUNET_malloc that returns a pointer
1138 * to the newly created objects of the correct type.
1140 * @param n number of elements in the array
1141 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1143 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof(type))
1147 * Allocate a size @a n times @a m array
1148 * with structs or unions of the given @a type.
1150 * @param n size of the first dimension
1151 * @param m size of the second dimension
1152 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1154 #define GNUNET_new_array_2d(n, m, type) \
1155 (type **) GNUNET_xnew_array_2d_ (n, m, sizeof(type), __FILE__, __LINE__)
1159 * Allocate a size @a n times @a m times @a o array
1160 * with structs or unions of the given @a type.
1162 * @param n size of the first dimension
1163 * @param m size of the second dimension
1164 * @param o size of the third dimension
1165 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1167 #define GNUNET_new_array_3d(n, m, o, type) \
1168 (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof(type), __FILE__, __LINE__)
1172 * Wrapper around malloc. Allocates size bytes of memory.
1173 * The memory will be zero'ed out.
1175 * @param size the number of bytes to allocate, must be
1176 * smaller than 40 MB.
1177 * @return pointer to size bytes of memory, never NULL (!)
1179 #define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__)
1183 * Allocate and initialize a block of memory.
1185 * @param buf data to initalize the block with
1186 * @param size the number of bytes in buf (and size of the allocation)
1187 * @return pointer to size bytes of memory, never NULL (!)
1189 #define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__)
1193 * Wrapper around malloc. Allocates size bytes of memory.
1194 * The memory will be zero'ed out.
1196 * @param size the number of bytes to allocate
1197 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1199 #define GNUNET_malloc_large(size) \
1200 GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__)
1204 * Wrapper around realloc. Reallocates size bytes of memory.
1205 * The content of the intersection of the new and old size will be unchanged.
1207 * @param ptr the pointer to reallocate
1208 * @param size the number of bytes to reallocate
1209 * @return pointer to size bytes of memory
1211 #define GNUNET_realloc(ptr, size) \
1212 GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__)
1216 * Wrapper around free. Frees the memory referred to by ptr.
1217 * Note that it is generally better to free memory that was
1218 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1220 * @param ptr location where to free the memory. ptr must have
1221 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1223 #define GNUNET_free(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__)
1227 * Free the memory pointed to by ptr if ptr is not NULL.
1228 * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1230 * @param ptr the location in memory to free
1232 #define GNUNET_free_non_null(ptr) \
1235 void *__x__ = ptr; \
1236 if (__x__ != NULL) \
1238 GNUNET_free (__x__); \
1244 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string
1247 * @param a pointer to a zero-terminated string
1248 * @return a copy of the string including zero-termination
1250 #define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__)
1254 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string
1257 * @param a pointer to a string
1258 * @param length of the string to duplicate
1259 * @return a partial copy of the string including zero-termination
1261 #define GNUNET_strndup(a, length) \
1262 GNUNET_xstrndup_ (a, length, __FILE__, __LINE__)
1266 * Grow a well-typed (!) array. This is a convenience
1267 * method to grow a vector @a arr of size @a size
1268 * to the new (target) size @a tsize.
1271 * Example (simple, well-typed stack):
1274 * static struct foo * myVector = NULL;
1275 * static int myVecLen = 0;
1277 * static void push(struct foo * elem) {
1278 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1279 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1282 * static void pop(struct foo * elem) {
1283 * if (myVecLen == 0) die();
1284 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1285 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1289 * @param arr base-pointer of the vector, may be NULL if size is 0;
1290 * will be updated to reflect the new address. The TYPE of
1291 * arr is important since size is the number of elements and
1292 * not the size in bytes
1293 * @param size the number of elements in the existing vector (number
1294 * of elements to copy over), will be updated with the new
1296 * @param tsize the target size for the resulting vector, use 0 to
1297 * free the vector (then, arr will be NULL afterwards).
1299 #define GNUNET_array_grow(arr, size, tsize) \
1300 GNUNET_xgrow_ ((void **) &(arr), \
1309 * Append an element to a list (growing the list by one).
1311 * @param arr base-pointer of the vector, may be NULL if size is 0;
1312 * will be updated to reflect the new address. The TYPE of
1313 * arr is important since size is the number of elements and
1314 * not the size in bytes
1315 * @param size the number of elements in the existing vector (number
1316 * of elements to copy over), will be updated with the new
1318 * @param element the element that will be appended to the array
1320 #define GNUNET_array_append(arr, size, element) \
1323 GNUNET_array_grow (arr, size, size + 1); \
1324 (arr) [size - 1] = element; \
1329 * Like snprintf, just aborts if the buffer is of insufficient size.
1331 * @param buf pointer to buffer that is written to
1332 * @param size number of bytes in @a buf
1333 * @param format format strings
1334 * @param ... data for format string
1335 * @return number of bytes written to buf or negative value on error
1338 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1343 * Like asprintf, just portable.
1345 * @param buf set to a buffer of sufficient size (allocated, caller must free)
1346 * @param format format string (see printf, fprintf, etc.)
1347 * @param ... data for format string
1348 * @return number of bytes in "*buf" excluding 0-termination
1351 GNUNET_asprintf (char **buf, const char *format, ...);
1354 /* ************** internal implementations, use macros above! ************** */
1357 * Allocate memory. Checks the return value, aborts if no more
1358 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the
1359 * #GNUNET_malloc macro.
1360 * The memory will be zero'ed out.
1362 * @param size number of bytes to allocate
1363 * @param filename where is this call being made (for debugging)
1364 * @param linenumber line where this call is being made (for debugging)
1365 * @return allocated memory, never NULL
1368 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
1372 * Allocate memory for a two dimensional array in one block
1373 * and set up pointers. Aborts if no more memory is available.
1374 * Don't use GNUNET_xnew_array_2d_ directly. Use the
1375 * #GNUNET_new_array_2d macro.
1376 * The memory of the elements will be zero'ed out.
1378 * @param n size of the first dimension
1379 * @param m size of the second dimension
1380 * @param elementSize size of a single element in bytes
1381 * @param filename where is this call being made (for debugging)
1382 * @param linenumber line where this call is being made (for debugging)
1383 * @return allocated memory, never NULL
1386 GNUNET_xnew_array_2d_ (size_t n,
1389 const char *filename,
1394 * Allocate memory for a three dimensional array in one block
1395 * and set up pointers. Aborts if no more memory is available.
1396 * Don't use GNUNET_xnew_array_3d_ directly. Use the
1397 * #GNUNET_new_array_3d macro.
1398 * The memory of the elements will be zero'ed out.
1400 * @param n size of the first dimension
1401 * @param m size of the second dimension
1402 * @param o size of the third dimension
1403 * @param elementSize size of a single element in bytes
1404 * @param filename where is this call being made (for debugging)
1405 * @param linenumber line where this call is being made (for debugging)
1406 * @return allocated memory, never NULL
1409 GNUNET_xnew_array_3d_ (size_t n,
1413 const char *filename,
1418 * Allocate and initialize memory. Checks the return value, aborts if no more
1419 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the
1420 * #GNUNET_memdup macro.
1422 * @param buf buffer to initialize from (must contain size bytes)
1423 * @param size number of bytes to allocate
1424 * @param filename where is this call being made (for debugging)
1425 * @param linenumber line where this call is being made (for debugging)
1426 * @return allocated memory, never NULL
1429 GNUNET_xmemdup_ (const void *buf,
1431 const char *filename,
1436 * Allocate memory. This function does not check if the allocation
1437 * request is within reasonable bounds, allowing allocations larger
1438 * than 40 MB. If you don't expect the possibility of very large
1439 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed
1442 * @param size number of bytes to allocate
1443 * @param filename where is this call being made (for debugging)
1444 * @param linenumber line where this call is being made (for debugging)
1445 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1448 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1452 * Reallocate memory. Checks the return value, aborts if no more
1453 * memory is available.
1456 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1460 * Free memory. Merely a wrapper for the case that we
1461 * want to keep track of allocations. Don't use GNUNET_xfree_
1462 * directly. Use the #GNUNET_free macro.
1464 * @param ptr pointer to memory to free
1465 * @param filename where is this call being made (for debugging)
1466 * @param linenumber line where this call is being made (for debugging)
1469 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1473 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1474 * @param str string to duplicate
1475 * @param filename where is this call being made (for debugging)
1476 * @param linenumber line where this call is being made (for debugging)
1477 * @return the duplicated string
1480 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1483 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1485 * @param str string to duplicate
1486 * @param len length of the string to duplicate
1487 * @param filename where is this call being made (for debugging)
1488 * @param linenumber line where this call is being made (for debugging)
1489 * @return the duplicated string
1492 GNUNET_xstrndup_ (const char *str,
1494 const char *filename,
1498 * Grow an array, the new elements are zeroed out.
1499 * Grows old by (*oldCount-newCount)*elementSize
1500 * bytes and sets *oldCount to newCount.
1502 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1504 * @param old address of the pointer to the array
1506 * @param elementSize the size of the elements of the array
1507 * @param oldCount address of the number of elements in the *old array
1508 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1509 * @param filename where is this call being made (for debugging)
1510 * @param linenumber line where this call is being made (for debugging)
1513 GNUNET_xgrow_ (void **old,
1515 unsigned int *oldCount,
1516 unsigned int newCount,
1517 const char *filename,
1523 * Create a copy of the given message.
1525 * @param msg message to copy
1526 * @return duplicate of the message
1528 struct GNUNET_MessageHeader *
1529 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1533 * Set the async scope for the current thread.
1535 * @param aid the async scope identifier
1536 * @param old_scope[out] location to save the old scope
1539 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1540 struct GNUNET_AsyncScopeSave *old_scope);
1544 * Clear the current thread's async scope.
1546 * @param old_scope scope to restore
1549 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope);
1553 * Get the current async scope.
1555 * @param[out] scope_ret pointer to where the result is stored
1558 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret);
1562 * Generate a fresh async scope identifier.
1564 * @param[out] aid_ret pointer to where the result is stored
1567 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret);
1570 #if __STDC_VERSION__ < 199901L
1572 #define __func__ __FUNCTION__
1574 #define __func__ "<unknown>"
1580 * Valid task priorities. Use these, do not pass random integers!
1581 * For various reasons (#3862 -- building with QT Creator, and
1582 * our restricted cross-compilation with emscripten) this cannot
1583 * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1584 * Naturally, logically this is part of the scheduler.
1586 enum GNUNET_SCHEDULER_Priority
1589 * Run with the same priority as the current job.
1591 GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1594 * Run when otherwise idle.
1596 GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1599 * Run as background job (higher than idle,
1600 * lower than default).
1602 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1605 * Run with the default priority (normal
1606 * P2P operations). Any task that is scheduled
1607 * without an explicit priority being specified
1608 * will run with this priority.
1610 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1613 * Run with high priority (important requests).
1614 * Higher than DEFAULT.
1616 GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1619 * Run with priority for interactive tasks.
1620 * Higher than "HIGH".
1622 GNUNET_SCHEDULER_PRIORITY_UI = 5,
1625 * Run with priority for urgent tasks. Use
1626 * for things like aborts and shutdowns that
1627 * need to preempt "UI"-level tasks.
1630 GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1633 * This is an internal priority level that is only used for tasks
1634 * that are being triggered due to shutdown (they have automatically
1635 * highest priority). User code must not use this priority level
1636 * directly. Tasks run with this priority level that internally
1637 * schedule other tasks will see their original priority level
1638 * be inherited (unless otherwise specified).
1640 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1643 * Number of priorities (must be the last priority).
1644 * This priority must not be used by clients.
1646 GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1650 #if 0 /* keep Emacsens' auto-indent happy */
1657 #endif /* GNUNET_COMMON_H */