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
40 #include <sys/socket.h>
43 #include <netinet/in.h>
55 #ifdef HAVE_BYTESWAP_H
61 #if 0 /* keep Emacsens' auto-indent happy */
67 * Version of the API (for entire gnunetutil.so library).
69 #define GNUNET_UTIL_VERSION 0x000A0103
73 * Named constants for return values. The following invariants hold:
74 * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK !=
75 * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO !=
76 * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`.
79 #define GNUNET_SYSERR -1
83 #define GNUNET_MIN(a, b) (((a) < (b)) ? (a) : (b))
85 #define GNUNET_MAX(a, b) (((a) > (b)) ? (a) : (b))
87 /* some systems use one underscore only, and mingw uses no underscore... */
90 #define __BYTE_ORDER _BYTE_ORDER
93 #define __BYTE_ORDER BYTE_ORDER
99 #define __BIG_ENDIAN _BIG_ENDIAN
102 #define __BIG_ENDIAN BIG_ENDIAN
106 #ifndef __LITTLE_ENDIAN
107 #ifdef _LITTLE_ENDIAN
108 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
111 #define __LITTLE_ENDIAN LITTLE_ENDIAN
117 * wrap va_arg for enums
119 #define GNUNET_VA_ARG_ENUM(va, X) ((enum X) va_arg (va, int))
124 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
125 * tree where gnunet_config.h is unavailable
127 #ifndef GNUNET_EXTRA_LOGGING
128 #define GNUNET_EXTRA_LOGGING 0
135 #if __BYTE_ORDER == __LITTLE_ENDIAN
136 #define GNUNET_htobe16(x) __bswap_16 (x)
137 #define GNUNET_htole16(x) (x)
138 #define GNUNET_be16toh(x) __bswap_16 (x)
139 #define GNUNET_le16toh(x) (x)
141 #define GNUNET_htobe32(x) __bswap_32 (x)
142 #define GNUNET_htole32(x) (x)
143 #define GNUNET_be32toh(x) __bswap_32 (x)
144 #define GNUNET_le32toh(x) (x)
146 #define GNUNET_htobe64(x) __bswap_64 (x)
147 #define GNUNET_htole64(x) (x)
148 #define GNUNET_be64toh(x) __bswap_64 (x)
149 #define GNUNET_le64toh(x) (x)
151 #if __BYTE_ORDER == __BIG_ENDIAN
152 #define GNUNET_htobe16(x) (x)
153 #define GNUNET_htole16(x) __bswap_16 (x)
154 #define GNUNET_be16toh(x) (x)
155 #define GNUNET_le16toh(x) __bswap_16 (x)
157 #define GNUNET_htobe32(x) (x)
158 #define GNUNET_htole32(x) __bswap_32 (x)
159 #define GNUNET_be32toh(x) (x)
160 #define GNUNET_le32toh(x) __bswap_32 (x)
162 #define GNUNET_htobe64(x) (x)
163 #define GNUNET_htole64(x) __bswap_64 (x)
164 #define GNUNET_be64toh(x) (x)
165 #define GNUNET_le64toh(x) __bswap_64 (x)
170 * Macro used to avoid using 0 for the length of a variable-size
171 * array (Non-Zero-Length).
173 * Basically, C standard says that "int[n] x;" is undefined if n=0.
174 * This was supposed to prevent issues with pointer aliasing.
175 * However, C compilers may conclude that n!=0 as n=0 would be
176 * undefined, and then optimize under the assumption n!=0, which
177 * could cause actual issues. Hence, when initializing an array
178 * on the stack with a variable-length that might be zero, write
179 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
181 #define GNUNET_NZL(l) GNUNET_MAX (1, l)
185 * gcc-ism to get packed structs.
187 #define GNUNET_PACKED __attribute__ ((packed))
190 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
193 #define GNUNET_GCC_STRUCT_LAYOUT __attribute__ ((gcc_struct))
195 #define GNUNET_GCC_STRUCT_LAYOUT
199 * gcc-ism to force alignment; we use this to align char-arrays
200 * that may then be cast to 'struct's. See also gcc
203 #ifdef __BIGGEST_ALIGNMENT__
204 #define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__)))
206 #define GNUNET_ALIGN __attribute__ ((aligned (8)))
210 * gcc-ism to document unused arguments
212 #define GNUNET_UNUSED __attribute__ ((unused))
215 * gcc-ism to document functions that don't return
217 #define GNUNET_NORETURN __attribute__ ((noreturn))
222 * gcc 4.x-ism to pack structures even on W32 (to be used before structs);
223 * Using this would cause structs to be unaligned on the stack on Sparc,
224 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
225 * W32 doesn't run on sparc anyway.
227 #define GNUNET_NETWORK_STRUCT_BEGIN _Pragma ("pack(push)") _Pragma ("pack(1)")
230 * gcc 4.x-ism to pack structures even on W32 (to be used after structs)
231 * Using this would cause structs to be unaligned on the stack on Sparc,
232 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
233 * W32 doesn't run on sparc anyway.
235 #define GNUNET_NETWORK_STRUCT_END _Pragma ("pack(pop)")
238 #error gcc 4.x or higher required on W32 systems
242 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
244 #define GNUNET_NETWORK_STRUCT_BEGIN
247 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
249 #define GNUNET_NETWORK_STRUCT_END
252 /* ************************ super-general types *********************** */
254 GNUNET_NETWORK_STRUCT_BEGIN
257 * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512.
259 struct GNUNET_HashCode
261 uint32_t bits[512 / 8 / sizeof (uint32_t)]; /* = 16 */
266 * @brief A 256-bit hashcode. Used under special conditions, like when space
267 * is critical and security is not impacted by it.
269 struct GNUNET_ShortHashCode
271 uint32_t bits[256 / 8 / sizeof (uint32_t)]; /* = 8 */
276 * A UUID, a 128 bit random value.
288 * Header for all communications.
290 struct GNUNET_MessageHeader
294 * The length of the struct (in bytes, including the length field itself),
295 * in big-endian format.
297 uint16_t size GNUNET_PACKED;
300 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
302 uint16_t type GNUNET_PACKED;
307 * Answer from service to client about last operation.
309 struct GNUNET_OperationResultMessage
311 struct GNUNET_MessageHeader header;
313 uint32_t reserved GNUNET_PACKED;
318 uint64_t op_id GNUNET_PACKED;
321 * Status code for the operation.
323 uint64_t result_code GNUNET_PACKED;
325 /* Followed by data. */
330 * Identifier for an asynchronous execution context.
332 struct GNUNET_AsyncScopeId
334 uint32_t bits[16 / sizeof (uint32_t)]; /* = 16 bytes */
337 GNUNET_NETWORK_STRUCT_END
341 * Saved async scope identifier or root scope.
343 struct GNUNET_AsyncScopeSave
346 * Saved scope. Unused if 'have_scope==GNUNET_NO'.
348 struct GNUNET_AsyncScopeId scope_id;
351 * GNUNET_YES unless this saved scope is the unnamed root scope.
358 * Function called with a filename.
361 * @param filename complete filename (absolute path)
362 * @return #GNUNET_OK to continue to iterate,
363 * #GNUNET_NO to stop iteration with no error,
364 * #GNUNET_SYSERR to abort iteration with error!
366 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
370 * Generic continuation callback.
372 * @param cls Closure.
374 typedef void (*GNUNET_ContinuationCallback) (void *cls);
378 * Function called with the result of an asynchronous operation.
383 * Result code for the operation.
385 * Data result for the operation.
389 typedef void (*GNUNET_ResultCallback) (void *cls,
395 /* ****************************** logging ***************************** */
401 enum GNUNET_ErrorType
403 GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
404 GNUNET_ERROR_TYPE_NONE = 0,
405 GNUNET_ERROR_TYPE_ERROR = 1,
406 GNUNET_ERROR_TYPE_WARNING = 2,
407 /* UX: We need a message type that is output by
408 * default without looking like there is a problem.
410 GNUNET_ERROR_TYPE_MESSAGE = 4,
411 GNUNET_ERROR_TYPE_INFO = 8,
412 GNUNET_ERROR_TYPE_DEBUG = 16,
413 GNUNET_ERROR_TYPE_INVALID = 32,
414 GNUNET_ERROR_TYPE_BULK = 64
420 * User-defined handler for log messages.
423 * @param kind severeity
424 * @param component what component is issuing the message?
425 * @param date when was the message logged?
426 * @param message what is the message
428 typedef void (*GNUNET_Logger) (void *cls,
429 enum GNUNET_ErrorType kind,
430 const char *component,
432 const char *message);
437 * Get the number of log calls that are going to be skipped
439 * @return number of log calls to be ignored
442 GNUNET_get_log_skip (void);
445 #if ! defined(GNUNET_CULL_LOGGING)
447 GNUNET_get_log_call_status (int caller_level,
450 const char *function,
459 * @param kind how serious is the error?
460 * @param message what is the message (format string)
461 * @param ... arguments for format string
464 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
465 __attribute__ ((format (printf, 2, 3)));
468 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
469 #define _GNUNET_BOOLEAN_EXPR(expr) \
471 int _gnunet_boolean_var_; \
473 _gnunet_boolean_var_ = 1; \
475 _gnunet_boolean_var_ = 0; \
476 _gnunet_boolean_var_; \
478 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1))
479 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0))
481 #define GN_LIKELY(expr) (expr)
482 #define GN_UNLIKELY(expr) (expr)
485 #if ! defined(GNUNET_LOG_CALL_STATUS)
486 #define GNUNET_LOG_CALL_STATUS -1
492 * Log function that specifies an alternative component.
493 * This function should be used by plugins.
495 * @param kind how serious is the error?
496 * @param comp component responsible for generating the message
497 * @param message what is the message (format string)
498 * @param ... arguments for format string
501 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
506 #if ! defined(GNUNET_CULL_LOGGING)
507 #define GNUNET_log_from(kind, comp, ...) \
510 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
511 if ((GNUNET_EXTRA_LOGGING > 0) || \
512 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
514 if (GN_UNLIKELY (log_call_enabled == -1)) \
516 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
521 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
523 GNUNET_log_skip (-1, GNUNET_NO); \
527 if (GN_UNLIKELY (log_call_enabled)) \
528 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \
533 #define GNUNET_log(kind, ...) \
536 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
537 if ((GNUNET_EXTRA_LOGGING > 0) || \
538 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
540 if (GN_UNLIKELY (log_call_enabled == -1)) \
542 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
547 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
549 GNUNET_log_skip (-1, GNUNET_NO); \
553 if (GN_UNLIKELY (log_call_enabled)) \
554 GNUNET_log_nocheck ((kind), __VA_ARGS__); \
559 #define GNUNET_log(...)
560 #define GNUNET_log_from(...)
566 * Log error message about missing configuration option.
568 * @param kind log level
569 * @param section section with missing option
570 * @param option name of missing option
573 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
580 * Log error message about invalid configuration option value.
582 * @param kind log level
583 * @param section section with invalid option
584 * @param option name of invalid option
585 * @param required what is required that is invalid about the option
588 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
591 const char *required);
596 * Abort the process, generate a core dump if possible.
597 * Most code should use `GNUNET_assert (0)` instead to
598 * first log the location of the failure.
601 GNUNET_abort_ (void) GNUNET_NORETURN;
606 * Ignore the next @a n calls to the log function.
608 * @param n number of log calls to ignore (could be negative)
609 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
612 GNUNET_log_skip (int n, int check_reset);
619 * @param comp default component to use
620 * @param loglevel what types of messages should be logged
621 * @param logfile change logging to logfile (use NULL to keep stderr)
622 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
625 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile);
630 * Add a custom logger. Note that installing any custom logger
631 * will disable the standard logger. When multiple custom loggers
632 * are installed, all will be called. The standard logger will
633 * only be used if no custom loggers are present.
635 * @param logger log function
636 * @param logger_cls closure for @a logger
639 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
644 * Remove a custom logger.
646 * @param logger log function
647 * @param logger_cls closure for @a logger
650 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
655 * Convert a short hash value to a string (for printing debug messages).
656 * This is one of the very few calls in the entire API that is
659 * @param shc the hash code
663 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
668 * Convert a UUID to a string (for printing debug messages).
669 * This is one of the very few calls in the entire API that is
672 * @param uuid the UUID
676 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid);
681 * Convert a hash value to a string (for printing debug messages).
682 * This is one of the very few calls in the entire API that is
685 * @param hc the hash code
689 GNUNET_h2s (const struct GNUNET_HashCode *hc);
694 * Convert a hash value to a string (for printing debug messages).
695 * This is one of the very few calls in the entire API that is
696 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
697 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
698 * used within the same log statement.
700 * @param hc the hash code
704 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
709 * Convert a hash value to a string (for printing debug messages).
710 * This prints all 104 characters of a hashcode!
711 * This is one of the very few calls in the entire API that is
714 * @param hc the hash code
718 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
722 * Public key. Details in gnunet_util_crypto.h.
724 struct GNUNET_CRYPTO_EddsaPublicKey;
728 * Public key. Details in gnunet_util_crypto.h.
730 struct GNUNET_CRYPTO_EcdhePublicKey;
735 * Convert a public key value to a string (for printing debug messages).
736 * This is one of the very few calls in the entire API that is
739 * @param hc the hash code
743 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
748 * Convert a public key value to a string (for printing debug messages).
749 * This is one of the very few calls in the entire API that is
752 * @param hc the hash code
756 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
761 * Convert a public key value to a string (for printing debug messages).
762 * This is one of the very few calls in the entire API that is
765 * @param hc the hash code
769 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
774 * Convert a public key value to a string (for printing debug messages).
775 * This is one of the very few calls in the entire API that is
778 * @param hc the hash code
782 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
787 * Convert a peer identity to a string (for printing debug messages).
788 * This is one of the very few calls in the entire API that is
791 * @param pid the peer identity
792 * @return string form of the pid; will be overwritten by next
793 * call to #GNUNET_i2s().
796 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
801 * Convert a peer identity to a string (for printing debug messages).
802 * This is one of the very few calls in the entire API that is
803 * NOT reentrant! Identical to #GNUNET_i2s(), except that another
804 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
805 * used within the same log statement.
807 * @param pid the peer identity
808 * @return string form of the pid; will be overwritten by next
809 * call to #GNUNET_i2s().
812 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
817 * Convert a peer identity to a string (for printing debug messages).
818 * This is one of the very few calls in the entire API that is
821 * @param pid the peer identity
822 * @return string form of the pid; will be overwritten by next
823 * call to #GNUNET_i2s_full().
826 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
831 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
832 * (for printing debug messages). This is one of the very few calls
833 * in the entire API that is NOT reentrant!
835 * @param addr the address
836 * @param addrlen the length of the @a addr
837 * @return nicely formatted string for the address
838 * will be overwritten by next call to #GNUNET_a2s().
841 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen);
846 * Convert error type to string.
848 * @param kind type to convert
849 * @return string corresponding to the type
852 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
857 * Use this for fatal errors that cannot be handled
859 #define GNUNET_assert(cond) \
864 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
865 _ ("Assertion failed at %s:%d. Aborting.\n"), \
875 * Use this for fatal errors that cannot be handled
877 #define GNUNET_assert_at(cond, f, l) \
882 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
883 _ ("Assertion failed at %s:%d. Aborting.\n"), \
893 * Use this for fatal errors that cannot be handled
895 * @param cond Condition to evaluate
896 * @param comp Component string to use for logging
898 #define GNUNET_assert_from(cond, comp) \
903 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \
905 _ ("Assertion failed at %s:%d. Aborting.\n"), \
915 * Use this for internal assertion violations that are
916 * not fatal (can be handled) but should not occur.
918 #define GNUNET_break(cond) \
923 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
924 _ ("Assertion failed at %s:%d.\n"), \
933 * Use this for assertion violations caused by other
934 * peers (i.e. protocol violations). We do not want to
935 * confuse end-users (say, some other peer runs an
936 * older, broken or incompatible GNUnet version), but
937 * we still want to see these problems during
938 * development and testing. "OP == other peer".
940 #define GNUNET_break_op(cond) \
945 GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \
946 _ ("External protocol violation detected at %s:%d.\n"), \
955 * Log an error message at log-level 'level' that indicates
956 * a failure of the command 'cmd' with the message given
957 * by strerror(errno).
959 #define GNUNET_log_strerror(level, cmd) \
963 _ ("`%s' failed at %s:%d with error: %s\n"), \
973 * Log an error message at log-level 'level' that indicates
974 * a failure of the command 'cmd' with the message given
975 * by strerror(errno).
977 #define GNUNET_log_from_strerror(level, component, cmd) \
980 GNUNET_log_from (level, \
982 _ ("`%s' failed at %s:%d with error: %s\n"), \
992 * Log an error message at log-level 'level' that indicates
993 * a failure of the command 'cmd' with the message given
994 * by strerror(errno).
996 #define GNUNET_log_strerror_file(level, cmd, filename) \
1000 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
1005 strerror (errno)); \
1011 * Log an error message at log-level 'level' that indicates
1012 * a failure of the command 'cmd' with the message given
1013 * by strerror(errno).
1015 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) \
1018 GNUNET_log_from (level, \
1020 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
1025 strerror (errno)); \
1028 /* ************************* endianess conversion ****************** */
1031 * Convert unsigned 64-bit integer to network byte order.
1034 * The value in host byte order.
1036 * @return The same value in network byte order.
1039 GNUNET_htonll (uint64_t n);
1043 * Convert unsigned 64-bit integer to host byte order.
1046 * The value in network byte order.
1048 * @return The same value in host byte order.
1051 GNUNET_ntohll (uint64_t n);
1055 * Convert double to network byte order.
1058 * The value in host byte order.
1060 * @return The same value in network byte order.
1063 GNUNET_hton_double (double d);
1067 * Convert double to host byte order
1070 * The value in network byte order.
1072 * @return The same value in host byte order.
1075 GNUNET_ntoh_double (double d);
1078 /* ************************* allocation functions ****************** */
1082 * Maximum allocation with GNUNET_malloc macro.
1084 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
1088 * Allocate a struct or union of the given @a type.
1089 * Wrapper around #GNUNET_malloc that returns a pointer
1090 * to the newly created object of the correct type.
1092 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1094 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
1098 * Compare memory in @a a and @a b, where both must be of
1099 * the same pointer type.
1101 #define GNUNET_memcmp(a, b) \
1103 const typeof (*b) *_a = (a); \
1104 const typeof (*a) *_b = (b); \
1105 memcmp (_a, _b, sizeof (*a)); \
1110 * Check that memory in @a a is all zeros. @a a must be a pointer.
1112 * @param a pointer to a struct which should be tested for the
1113 * entire memory being zero'ed out.
1115 #define GNUNET_is_zero(a) \
1117 static const typeof (*a) _z; \
1118 memcmp ((a), &_z, sizeof (_z)); \
1123 * Call memcpy() but check for @a n being 0 first. In the latter
1124 * case, it is now safe to pass NULL for @a src or @a dst.
1125 * Unlike traditional memcpy(), returns nothing.
1127 * @param dst destination of the copy, may be NULL if @a n is zero
1128 * @param src source of the copy, may be NULL if @a n is zero
1129 * @param n number of bytes to copy
1131 #define GNUNET_memcpy(dst, src, n) \
1136 (void) memcpy (dst, src, n); \
1143 * Allocate a size @a n array with structs or unions of the given @a type.
1144 * Wrapper around #GNUNET_malloc that returns a pointer
1145 * to the newly created objects of the correct type.
1147 * @param n number of elements in the array
1148 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1150 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
1154 * Allocate a size @a n times @a m array
1155 * with structs or unions of the given @a type.
1157 * @param n size of the first dimension
1158 * @param m size of the second dimension
1159 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1161 #define GNUNET_new_array_2d(n, m, type) \
1162 (type **) GNUNET_xnew_array_2d_ (n, m, sizeof (type), __FILE__, __LINE__)
1166 * Allocate a size @a n times @a m times @a o array
1167 * with structs or unions of the given @a type.
1169 * @param n size of the first dimension
1170 * @param m size of the second dimension
1171 * @param o size of the third dimension
1172 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1174 #define GNUNET_new_array_3d(n, m, o, type) \
1175 (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof (type), __FILE__, __LINE__)
1179 * Wrapper around malloc. Allocates size bytes of memory.
1180 * The memory will be zero'ed out.
1182 * @param size the number of bytes to allocate, must be
1183 * smaller than 40 MB.
1184 * @return pointer to size bytes of memory, never NULL (!)
1186 #define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__)
1190 * Allocate and initialize a block of memory.
1192 * @param buf data to initalize the block with
1193 * @param size the number of bytes in buf (and size of the allocation)
1194 * @return pointer to size bytes of memory, never NULL (!)
1196 #define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__)
1200 * Wrapper around malloc. Allocates size bytes of memory.
1201 * The memory will be zero'ed out.
1203 * @param size the number of bytes to allocate
1204 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1206 #define GNUNET_malloc_large(size) \
1207 GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__)
1211 * Wrapper around realloc. Reallocates size bytes of memory.
1212 * The content of the intersection of the new and old size will be unchanged.
1214 * @param ptr the pointer to reallocate
1215 * @param size the number of bytes to reallocate
1216 * @return pointer to size bytes of memory
1218 #define GNUNET_realloc(ptr, size) \
1219 GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__)
1223 * Wrapper around free. Frees the memory referred to by ptr.
1224 * Note that it is generally better to free memory that was
1225 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1227 * @param ptr location where to free the memory. ptr must have
1228 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1230 #define GNUNET_free(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__)
1234 * Free the memory pointed to by ptr if ptr is not NULL.
1235 * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1237 * @param ptr the location in memory to free
1239 #define GNUNET_free_non_null(ptr) \
1242 void *__x__ = ptr; \
1243 if (__x__ != NULL) \
1245 GNUNET_free (__x__); \
1251 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string
1254 * @param a pointer to a zero-terminated string
1255 * @return a copy of the string including zero-termination
1257 #define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__)
1261 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string
1264 * @param a pointer to a string
1265 * @param length of the string to duplicate
1266 * @return a partial copy of the string including zero-termination
1268 #define GNUNET_strndup(a, length) \
1269 GNUNET_xstrndup_ (a, length, __FILE__, __LINE__)
1273 * Grow a well-typed (!) array. This is a convenience
1274 * method to grow a vector @a arr of size @a size
1275 * to the new (target) size @a tsize.
1278 * Example (simple, well-typed stack):
1281 * static struct foo * myVector = NULL;
1282 * static int myVecLen = 0;
1284 * static void push(struct foo * elem) {
1285 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1286 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1289 * static void pop(struct foo * elem) {
1290 * if (myVecLen == 0) die();
1291 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1292 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1296 * @param arr base-pointer of the vector, may be NULL if size is 0;
1297 * will be updated to reflect the new address. The TYPE of
1298 * arr is important since size is the number of elements and
1299 * not the size in bytes
1300 * @param size the number of elements in the existing vector (number
1301 * of elements to copy over), will be updated with the new
1303 * @param tsize the target size for the resulting vector, use 0 to
1304 * free the vector (then, arr will be NULL afterwards).
1306 #define GNUNET_array_grow(arr, size, tsize) \
1307 GNUNET_xgrow_ ((void **) &(arr), \
1308 sizeof ((arr)[0]), \
1316 * Append an element to a list (growing the list by one).
1318 * @param arr base-pointer of the vector, may be NULL if size is 0;
1319 * will be updated to reflect the new address. The TYPE of
1320 * arr is important since size is the number of elements and
1321 * not the size in bytes
1322 * @param size the number of elements in the existing vector (number
1323 * of elements to copy over), will be updated with the new
1325 * @param element the element that will be appended to the array
1327 #define GNUNET_array_append(arr, size, element) \
1330 GNUNET_array_grow (arr, size, size + 1); \
1331 (arr)[size - 1] = element; \
1336 * Like snprintf, just aborts if the buffer is of insufficient size.
1338 * @param buf pointer to buffer that is written to
1339 * @param size number of bytes in @a buf
1340 * @param format format strings
1341 * @param ... data for format string
1342 * @return number of bytes written to buf or negative value on error
1345 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1350 * Like asprintf, just portable.
1352 * @param buf set to a buffer of sufficient size (allocated, caller must free)
1353 * @param format format string (see printf, fprintf, etc.)
1354 * @param ... data for format string
1355 * @return number of bytes in "*buf" excluding 0-termination
1358 GNUNET_asprintf (char **buf, const char *format, ...);
1361 /* ************** internal implementations, use macros above! ************** */
1364 * Allocate memory. Checks the return value, aborts if no more
1365 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the
1366 * #GNUNET_malloc macro.
1367 * The memory will be zero'ed out.
1369 * @param size number of bytes to allocate
1370 * @param filename where is this call being made (for debugging)
1371 * @param linenumber line where this call is being made (for debugging)
1372 * @return allocated memory, never NULL
1375 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
1379 * Allocate memory for a two dimensional array in one block
1380 * and set up pointers. Aborts if no more memory is available.
1381 * Don't use GNUNET_xnew_array_2d_ directly. Use the
1382 * #GNUNET_new_array_2d macro.
1383 * The memory of the elements will be zero'ed out.
1385 * @param n size of the first dimension
1386 * @param m size of the second dimension
1387 * @param elementSize size of a single element in bytes
1388 * @param filename where is this call being made (for debugging)
1389 * @param linenumber line where this call is being made (for debugging)
1390 * @return allocated memory, never NULL
1393 GNUNET_xnew_array_2d_ (size_t n,
1396 const char *filename,
1401 * Allocate memory for a three dimensional array in one block
1402 * and set up pointers. Aborts if no more memory is available.
1403 * Don't use GNUNET_xnew_array_3d_ directly. Use the
1404 * #GNUNET_new_array_3d macro.
1405 * The memory of the elements will be zero'ed out.
1407 * @param n size of the first dimension
1408 * @param m size of the second dimension
1409 * @param o size of the third dimension
1410 * @param elementSize size of a single element in bytes
1411 * @param filename where is this call being made (for debugging)
1412 * @param linenumber line where this call is being made (for debugging)
1413 * @return allocated memory, never NULL
1416 GNUNET_xnew_array_3d_ (size_t n,
1420 const char *filename,
1425 * Allocate and initialize memory. Checks the return value, aborts if no more
1426 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the
1427 * #GNUNET_memdup macro.
1429 * @param buf buffer to initialize from (must contain size bytes)
1430 * @param size number of bytes to allocate
1431 * @param filename where is this call being made (for debugging)
1432 * @param linenumber line where this call is being made (for debugging)
1433 * @return allocated memory, never NULL
1436 GNUNET_xmemdup_ (const void *buf,
1438 const char *filename,
1443 * Allocate memory. This function does not check if the allocation
1444 * request is within reasonable bounds, allowing allocations larger
1445 * than 40 MB. If you don't expect the possibility of very large
1446 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed
1449 * @param size number of bytes to allocate
1450 * @param filename where is this call being made (for debugging)
1451 * @param linenumber line where this call is being made (for debugging)
1452 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1455 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1459 * Reallocate memory. Checks the return value, aborts if no more
1460 * memory is available.
1463 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1467 * Free memory. Merely a wrapper for the case that we
1468 * want to keep track of allocations. Don't use GNUNET_xfree_
1469 * directly. Use the #GNUNET_free macro.
1471 * @param ptr pointer to memory to free
1472 * @param filename where is this call being made (for debugging)
1473 * @param linenumber line where this call is being made (for debugging)
1476 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1480 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1481 * @param str string to duplicate
1482 * @param filename where is this call being made (for debugging)
1483 * @param linenumber line where this call is being made (for debugging)
1484 * @return the duplicated string
1487 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1490 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1492 * @param str string to duplicate
1493 * @param len length of the string to duplicate
1494 * @param filename where is this call being made (for debugging)
1495 * @param linenumber line where this call is being made (for debugging)
1496 * @return the duplicated string
1499 GNUNET_xstrndup_ (const char *str,
1501 const char *filename,
1505 * Grow an array, the new elements are zeroed out.
1506 * Grows old by (*oldCount-newCount)*elementSize
1507 * bytes and sets *oldCount to newCount.
1509 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1511 * @param old address of the pointer to the array
1513 * @param elementSize the size of the elements of the array
1514 * @param oldCount address of the number of elements in the *old array
1515 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1516 * @param filename where is this call being made (for debugging)
1517 * @param linenumber line where this call is being made (for debugging)
1520 GNUNET_xgrow_ (void **old,
1522 unsigned int *oldCount,
1523 unsigned int newCount,
1524 const char *filename,
1530 * Create a copy of the given message.
1532 * @param msg message to copy
1533 * @return duplicate of the message
1535 struct GNUNET_MessageHeader *
1536 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1540 * Set the async scope for the current thread.
1542 * @param aid the async scope identifier
1543 * @param old_scope[out] location to save the old scope
1546 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1547 struct GNUNET_AsyncScopeSave *old_scope);
1551 * Clear the current thread's async scope.
1553 * @param old_scope scope to restore
1556 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope);
1560 * Get the current async scope.
1562 * @param[out] scope_ret pointer to where the result is stored
1565 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret);
1569 * Generate a fresh async scope identifier.
1571 * @param[out] aid_ret pointer to where the result is stored
1574 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret);
1577 #if __STDC_VERSION__ < 199901L
1579 #define __func__ __FUNCTION__
1581 #define __func__ "<unknown>"
1587 * Valid task priorities. Use these, do not pass random integers!
1588 * For various reasons (#3862 -- building with QT Creator, and
1589 * our restricted cross-compilation with emscripten) this cannot
1590 * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1591 * Naturally, logically this is part of the scheduler.
1593 enum GNUNET_SCHEDULER_Priority
1596 * Run with the same priority as the current job.
1598 GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1601 * Run when otherwise idle.
1603 GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1606 * Run as background job (higher than idle,
1607 * lower than default).
1609 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1612 * Run with the default priority (normal
1613 * P2P operations). Any task that is scheduled
1614 * without an explicit priority being specified
1615 * will run with this priority.
1617 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1620 * Run with high priority (important requests).
1621 * Higher than DEFAULT.
1623 GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1626 * Run with priority for interactive tasks.
1627 * Higher than "HIGH".
1629 GNUNET_SCHEDULER_PRIORITY_UI = 5,
1632 * Run with priority for urgent tasks. Use
1633 * for things like aborts and shutdowns that
1634 * need to preempt "UI"-level tasks.
1637 GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1640 * This is an internal priority level that is only used for tasks
1641 * that are being triggered due to shutdown (they have automatically
1642 * highest priority). User code must not use this priority level
1643 * directly. Tasks run with this priority level that internally
1644 * schedule other tasks will see their original priority level
1645 * be inherited (unless otherwise specified).
1647 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1650 * Number of priorities (must be the last priority).
1651 * This priority must not be used by clients.
1653 GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1657 #if 0 /* keep Emacsens' auto-indent happy */
1664 #endif /* GNUNET_COMMON_H */