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>
52 #ifdef HAVE_BYTESWAP_H
58 #if 0 /* keep Emacsens' auto-indent happy */
64 * Version of the API (for entire gnunetutil.so library).
66 #define GNUNET_UTIL_VERSION 0x000A0103
70 * Named constants for return values. The following invariants hold:
71 * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK !=
72 * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO !=
73 * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`.
76 #define GNUNET_SYSERR -1
80 #define GNUNET_MIN(a, b) (((a) < (b)) ? (a) : (b))
82 #define GNUNET_MAX(a, b) (((a) > (b)) ? (a) : (b))
84 /* some systems use one underscore only, and mingw uses no underscore... */
87 #define __BYTE_ORDER _BYTE_ORDER
90 #define __BYTE_ORDER BYTE_ORDER
96 #define __BIG_ENDIAN _BIG_ENDIAN
99 #define __BIG_ENDIAN BIG_ENDIAN
103 #ifndef __LITTLE_ENDIAN
104 #ifdef _LITTLE_ENDIAN
105 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
108 #define __LITTLE_ENDIAN LITTLE_ENDIAN
114 * wrap va_arg for enums
116 #define GNUNET_VA_ARG_ENUM(va, X) ((enum X) va_arg (va, int))
121 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
122 * tree where gnunet_config.h is unavailable
124 #ifndef GNUNET_EXTRA_LOGGING
125 #define GNUNET_EXTRA_LOGGING 0
132 #if __BYTE_ORDER == __LITTLE_ENDIAN
133 #define GNUNET_htobe16(x) __bswap_16 (x)
134 #define GNUNET_htole16(x) (x)
135 #define GNUNET_be16toh(x) __bswap_16 (x)
136 #define GNUNET_le16toh(x) (x)
138 #define GNUNET_htobe32(x) __bswap_32 (x)
139 #define GNUNET_htole32(x) (x)
140 #define GNUNET_be32toh(x) __bswap_32 (x)
141 #define GNUNET_le32toh(x) (x)
143 #define GNUNET_htobe64(x) __bswap_64 (x)
144 #define GNUNET_htole64(x) (x)
145 #define GNUNET_be64toh(x) __bswap_64 (x)
146 #define GNUNET_le64toh(x) (x)
148 #if __BYTE_ORDER == __BIG_ENDIAN
149 #define GNUNET_htobe16(x) (x)
150 #define GNUNET_htole16(x) __bswap_16 (x)
151 #define GNUNET_be16toh(x) (x)
152 #define GNUNET_le16toh(x) __bswap_16 (x)
154 #define GNUNET_htobe32(x) (x)
155 #define GNUNET_htole32(x) __bswap_32 (x)
156 #define GNUNET_be32toh(x) (x)
157 #define GNUNET_le32toh(x) __bswap_32 (x)
159 #define GNUNET_htobe64(x) (x)
160 #define GNUNET_htole64(x) __bswap_64 (x)
161 #define GNUNET_be64toh(x) (x)
162 #define GNUNET_le64toh(x) __bswap_64 (x)
167 * Macro used to avoid using 0 for the length of a variable-size
168 * array (Non-Zero-Length).
170 * Basically, C standard says that "int[n] x;" is undefined if n=0.
171 * This was supposed to prevent issues with pointer aliasing.
172 * However, C compilers may conclude that n!=0 as n=0 would be
173 * undefined, and then optimize under the assumption n!=0, which
174 * could cause actual issues. Hence, when initializing an array
175 * on the stack with a variable-length that might be zero, write
176 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
178 #define GNUNET_NZL(l) GNUNET_MAX (1, l)
182 * gcc-ism to get packed structs.
184 #define GNUNET_PACKED __attribute__ ((packed))
187 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
189 #define GNUNET_GCC_STRUCT_LAYOUT
192 * gcc-ism to force alignment; we use this to align char-arrays
193 * that may then be cast to 'struct's. See also gcc
196 #ifdef __BIGGEST_ALIGNMENT__
197 #define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__)))
199 #define GNUNET_ALIGN __attribute__ ((aligned (8)))
203 * gcc-ism to document unused arguments
205 #define GNUNET_UNUSED __attribute__ ((unused))
208 * gcc-ism to document functions that don't return
210 #define GNUNET_NORETURN __attribute__ ((noreturn))
213 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
215 #define GNUNET_NETWORK_STRUCT_BEGIN
218 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
220 #define GNUNET_NETWORK_STRUCT_END
222 /* ************************ super-general types *********************** */
224 GNUNET_NETWORK_STRUCT_BEGIN
227 * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512.
229 struct GNUNET_HashCode
231 uint32_t bits[512 / 8 / sizeof(uint32_t)]; /* = 16 */
236 * @brief A 256-bit hashcode. Used under special conditions, like when space
237 * is critical and security is not impacted by it.
239 struct GNUNET_ShortHashCode
241 uint32_t bits[256 / 8 / sizeof(uint32_t)]; /* = 8 */
246 * A UUID, a 128 bit random value.
258 * Header for all communications.
260 struct GNUNET_MessageHeader
263 * The length of the struct (in bytes, including the length field itself),
264 * in big-endian format.
266 uint16_t size GNUNET_PACKED;
269 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
271 uint16_t type GNUNET_PACKED;
276 * Answer from service to client about last operation.
278 struct GNUNET_OperationResultMessage
280 struct GNUNET_MessageHeader header;
282 uint32_t reserved GNUNET_PACKED;
287 uint64_t op_id GNUNET_PACKED;
290 * Status code for the operation.
292 uint64_t result_code GNUNET_PACKED;
294 /* Followed by data. */
299 * Identifier for an asynchronous execution context.
301 struct GNUNET_AsyncScopeId
303 uint32_t bits[16 / sizeof(uint32_t)]; /* = 16 bytes */
306 GNUNET_NETWORK_STRUCT_END
310 * Saved async scope identifier or root scope.
312 struct GNUNET_AsyncScopeSave
315 * Saved scope. Unused if 'have_scope==GNUNET_NO'.
317 struct GNUNET_AsyncScopeId scope_id;
320 * GNUNET_YES unless this saved scope is the unnamed root scope.
327 * Function called with a filename.
330 * @param filename complete filename (absolute path)
331 * @return #GNUNET_OK to continue to iterate,
332 * #GNUNET_NO to stop iteration with no error,
333 * #GNUNET_SYSERR to abort iteration with error!
335 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
339 * Generic continuation callback.
341 * @param cls Closure.
343 typedef void (*GNUNET_ContinuationCallback) (void *cls);
347 * Function called with the result of an asynchronous operation.
352 * Result code for the operation.
354 * Data result for the operation.
358 typedef void (*GNUNET_ResultCallback) (void *cls,
364 /* ****************************** logging ***************************** */
370 enum GNUNET_ErrorType
372 GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
373 GNUNET_ERROR_TYPE_NONE = 0,
374 GNUNET_ERROR_TYPE_ERROR = 1,
375 GNUNET_ERROR_TYPE_WARNING = 2,
376 /* UX: We need a message type that is output by
377 * default without looking like there is a problem.
379 GNUNET_ERROR_TYPE_MESSAGE = 4,
380 GNUNET_ERROR_TYPE_INFO = 8,
381 GNUNET_ERROR_TYPE_DEBUG = 16,
382 GNUNET_ERROR_TYPE_INVALID = 32,
383 GNUNET_ERROR_TYPE_BULK = 64
389 * User-defined handler for log messages.
392 * @param kind severeity
393 * @param component what component is issuing the message?
394 * @param date when was the message logged?
395 * @param message what is the message
397 typedef void (*GNUNET_Logger) (void *cls,
398 enum GNUNET_ErrorType kind,
399 const char *component,
401 const char *message);
406 * Get the number of log calls that are going to be skipped
408 * @return number of log calls to be ignored
411 GNUNET_get_log_skip (void);
414 #if ! defined(GNUNET_CULL_LOGGING)
416 GNUNET_get_log_call_status (int caller_level,
419 const char *function,
428 * @param kind how serious is the error?
429 * @param message what is the message (format string)
430 * @param ... arguments for format string
433 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
434 __attribute__ ((format (printf, 2, 3)));
437 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
438 #define _GNUNET_BOOLEAN_EXPR(expr) \
440 int _gnunet_boolean_var_; \
442 _gnunet_boolean_var_ = 1; \
444 _gnunet_boolean_var_ = 0; \
445 _gnunet_boolean_var_; \
447 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1))
448 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0))
450 #define GN_LIKELY(expr) (expr)
451 #define GN_UNLIKELY(expr) (expr)
454 #if ! defined(GNUNET_LOG_CALL_STATUS)
455 #define GNUNET_LOG_CALL_STATUS -1
461 * Log function that specifies an alternative component.
462 * This function should be used by plugins.
464 * @param kind how serious is the error?
465 * @param comp component responsible for generating the message
466 * @param message what is the message (format string)
467 * @param ... arguments for format string
470 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
475 #if ! defined(GNUNET_CULL_LOGGING)
476 #define GNUNET_log_from(kind, comp, ...) \
479 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
480 if ((GNUNET_EXTRA_LOGGING > 0) || \
481 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
483 if (GN_UNLIKELY (log_call_enabled == -1)) \
485 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
490 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
492 GNUNET_log_skip (-1, GNUNET_NO); \
496 if (GN_UNLIKELY (log_call_enabled)) \
497 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \
502 #define GNUNET_log(kind, ...) \
505 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \
506 if ((GNUNET_EXTRA_LOGGING > 0) || \
507 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \
509 if (GN_UNLIKELY (log_call_enabled == -1)) \
511 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
516 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \
518 GNUNET_log_skip (-1, GNUNET_NO); \
522 if (GN_UNLIKELY (log_call_enabled)) \
523 GNUNET_log_nocheck ((kind), __VA_ARGS__); \
528 #define GNUNET_log(...)
529 #define GNUNET_log_from(...)
535 * Log error message about missing configuration option.
537 * @param kind log level
538 * @param section section with missing option
539 * @param option name of missing option
542 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
549 * Log error message about invalid configuration option value.
551 * @param kind log level
552 * @param section section with invalid option
553 * @param option name of invalid option
554 * @param required what is required that is invalid about the option
557 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
560 const char *required);
565 * Abort the process, generate a core dump if possible.
566 * Most code should use `GNUNET_assert (0)` instead to
567 * first log the location of the failure.
570 GNUNET_abort_ (void) GNUNET_NORETURN;
575 * Ignore the next @a n calls to the log function.
577 * @param n number of log calls to ignore (could be negative)
578 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
581 GNUNET_log_skip (int n, int check_reset);
588 * @param comp default component to use
589 * @param loglevel what types of messages should be logged
590 * @param logfile change logging to logfile (use NULL to keep stderr)
591 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
594 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile);
599 * Add a custom logger. Note that installing any custom logger
600 * will disable the standard logger. When multiple custom loggers
601 * are installed, all will be called. The standard logger will
602 * only be used if no custom loggers are present.
604 * @param logger log function
605 * @param logger_cls closure for @a logger
608 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
613 * Remove a custom logger.
615 * @param logger log function
616 * @param logger_cls closure for @a logger
619 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
624 * Convert a short hash value to a string (for printing debug messages).
625 * This is one of the very few calls in the entire API that is
628 * @param shc the hash code
632 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
637 * Convert a UUID to a string (for printing debug messages).
638 * This is one of the very few calls in the entire API that is
641 * @param uuid the UUID
645 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid);
650 * Convert a hash value to a string (for printing debug messages).
651 * This is one of the very few calls in the entire API that is
654 * @param hc the hash code
658 GNUNET_h2s (const struct GNUNET_HashCode *hc);
663 * Convert a hash value to a string (for printing debug messages).
664 * This is one of the very few calls in the entire API that is
665 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
666 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
667 * used within the same log statement.
669 * @param hc the hash code
673 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
678 * Convert a hash value to a string (for printing debug messages).
679 * This prints all 104 characters of a hashcode!
680 * This is one of the very few calls in the entire API that is
683 * @param hc the hash code
687 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
691 * Public key. Details in gnunet_util_crypto.h.
693 struct GNUNET_CRYPTO_EddsaPublicKey;
697 * Public key. Details in gnunet_util_crypto.h.
699 struct GNUNET_CRYPTO_EcdhePublicKey;
704 * Convert a public key value to a string (for printing debug messages).
705 * This is one of the very few calls in the entire API that is
708 * @param hc the hash code
712 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
717 * Convert a public key value to a string (for printing debug messages).
718 * This is one of the very few calls in the entire API that is
721 * @param hc the hash code
725 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
730 * Convert a public key value to a string (for printing debug messages).
731 * This is one of the very few calls in the entire API that is
734 * @param hc the hash code
738 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
743 * Convert a public key value to a string (for printing debug messages).
744 * This is one of the very few calls in the entire API that is
747 * @param hc the hash code
751 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
756 * Convert a peer identity to a string (for printing debug messages).
757 * This is one of the very few calls in the entire API that is
760 * @param pid the peer identity
761 * @return string form of the pid; will be overwritten by next
762 * call to #GNUNET_i2s().
765 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
770 * Convert a peer identity to a string (for printing debug messages).
771 * This is one of the very few calls in the entire API that is
772 * NOT reentrant! Identical to #GNUNET_i2s(), except that another
773 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
774 * used within the same log statement.
776 * @param pid the peer identity
777 * @return string form of the pid; will be overwritten by next
778 * call to #GNUNET_i2s().
781 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
786 * Convert a peer identity to a string (for printing debug messages).
787 * This is one of the very few calls in the entire API that is
790 * @param pid the peer identity
791 * @return string form of the pid; will be overwritten by next
792 * call to #GNUNET_i2s_full().
795 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
800 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
801 * (for printing debug messages). This is one of the very few calls
802 * in the entire API that is NOT reentrant!
804 * @param addr the address
805 * @param addrlen the length of the @a addr
806 * @return nicely formatted string for the address
807 * will be overwritten by next call to #GNUNET_a2s().
810 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen);
815 * Convert error type to string.
817 * @param kind type to convert
818 * @return string corresponding to the type
821 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
826 * Use this for fatal errors that cannot be handled
828 #define GNUNET_assert(cond) \
833 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
834 _ ("Assertion failed at %s:%d. Aborting.\n"), \
844 * Use this for fatal errors that cannot be handled
846 #define GNUNET_assert_at(cond, f, l) \
851 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
852 _ ("Assertion failed at %s:%d. Aborting.\n"), \
862 * Use this for fatal errors that cannot be handled
864 * @param cond Condition to evaluate
865 * @param comp Component string to use for logging
867 #define GNUNET_assert_from(cond, comp) \
872 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \
874 _ ("Assertion failed at %s:%d. Aborting.\n"), \
884 * Use this for internal assertion violations that are
885 * not fatal (can be handled) but should not occur.
887 #define GNUNET_break(cond) \
892 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \
893 _ ("Assertion failed at %s:%d.\n"), \
902 * Use this for assertion violations caused by other
903 * peers (i.e. protocol violations). We do not want to
904 * confuse end-users (say, some other peer runs an
905 * older, broken or incompatible GNUnet version), but
906 * we still want to see these problems during
907 * development and testing. "OP == other peer".
909 #define GNUNET_break_op(cond) \
914 GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \
915 _ ("External protocol violation detected at %s:%d.\n"), \
924 * Log an error message at log-level 'level' that indicates
925 * a failure of the command 'cmd' with the message given
926 * by strerror(errno).
928 #define GNUNET_log_strerror(level, cmd) \
932 _ ("`%s' failed at %s:%d with error: %s\n"), \
942 * Log an error message at log-level 'level' that indicates
943 * a failure of the command 'cmd' with the message given
944 * by strerror(errno).
946 #define GNUNET_log_from_strerror(level, component, cmd) \
949 GNUNET_log_from (level, \
951 _ ("`%s' failed at %s:%d with error: %s\n"), \
961 * Log an error message at log-level 'level' that indicates
962 * a failure of the command 'cmd' with the message given
963 * by strerror(errno).
965 #define GNUNET_log_strerror_file(level, cmd, filename) \
969 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
980 * Log an error message at log-level 'level' that indicates
981 * a failure of the command 'cmd' with the message given
982 * by strerror(errno).
984 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) \
987 GNUNET_log_from (level, \
989 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
997 /* ************************* endianess conversion ****************** */
1000 * Convert unsigned 64-bit integer to network byte order.
1003 * The value in host byte order.
1005 * @return The same value in network byte order.
1008 GNUNET_htonll (uint64_t n);
1012 * Convert unsigned 64-bit integer to host byte order.
1015 * The value in network byte order.
1017 * @return The same value in host byte order.
1020 GNUNET_ntohll (uint64_t n);
1024 * Convert double to network byte order.
1027 * The value in host byte order.
1029 * @return The same value in network byte order.
1032 GNUNET_hton_double (double d);
1036 * Convert double to host byte order
1039 * The value in network byte order.
1041 * @return The same value in host byte order.
1044 GNUNET_ntoh_double (double d);
1047 /* ************************* allocation functions ****************** */
1051 * Maximum allocation with GNUNET_malloc macro.
1053 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
1057 * Allocate a struct or union of the given @a type.
1058 * Wrapper around #GNUNET_malloc that returns a pointer
1059 * to the newly created object of the correct type.
1061 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1063 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof(type))
1067 * Compare memory in @a a and @a b, where both must be of
1068 * the same pointer type.
1070 #define GNUNET_memcmp(a, b) \
1072 const typeof (*b) * _a = (a); \
1073 const typeof (*a) * _b = (b); \
1074 memcmp (_a, _b, sizeof(*a)); \
1079 * Check that memory in @a a is all zeros. @a a must be a pointer.
1081 * @param a pointer to a struct which should be tested for the
1082 * entire memory being zero'ed out.
1084 #define GNUNET_is_zero(a) \
1086 static const typeof (*a) _z; \
1087 memcmp ((a), &_z, sizeof(_z)); \
1092 * Call memcpy() but check for @a n being 0 first. In the latter
1093 * case, it is now safe to pass NULL for @a src or @a dst.
1094 * Unlike traditional memcpy(), returns nothing.
1096 * @param dst destination of the copy, may be NULL if @a n is zero
1097 * @param src source of the copy, may be NULL if @a n is zero
1098 * @param n number of bytes to copy
1100 #define GNUNET_memcpy(dst, src, n) \
1105 (void) memcpy (dst, src, n); \
1112 * Allocate a size @a n array with structs or unions of the given @a type.
1113 * Wrapper around #GNUNET_malloc that returns a pointer
1114 * to the newly created objects of the correct type.
1116 * @param n number of elements in the array
1117 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1119 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof(type))
1123 * Allocate a size @a n times @a m array
1124 * with structs or unions of the given @a type.
1126 * @param n size of the first dimension
1127 * @param m size of the second dimension
1128 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1130 #define GNUNET_new_array_2d(n, m, type) \
1131 (type **) GNUNET_xnew_array_2d_ (n, m, sizeof(type), __FILE__, __LINE__)
1135 * Allocate a size @a n times @a m times @a o array
1136 * with structs or unions of the given @a type.
1138 * @param n size of the first dimension
1139 * @param m size of the second dimension
1140 * @param o size of the third dimension
1141 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1143 #define GNUNET_new_array_3d(n, m, o, type) \
1144 (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof(type), __FILE__, __LINE__)
1148 * Wrapper around malloc. Allocates size bytes of memory.
1149 * The memory will be zero'ed out.
1151 * @param size the number of bytes to allocate, must be
1152 * smaller than 40 MB.
1153 * @return pointer to size bytes of memory, never NULL (!)
1155 #define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__)
1159 * Allocate and initialize a block of memory.
1161 * @param buf data to initalize the block with
1162 * @param size the number of bytes in buf (and size of the allocation)
1163 * @return pointer to size bytes of memory, never NULL (!)
1165 #define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__)
1169 * Wrapper around malloc. Allocates size bytes of memory.
1170 * The memory will be zero'ed out.
1172 * @param size the number of bytes to allocate
1173 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1175 #define GNUNET_malloc_large(size) \
1176 GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__)
1180 * Wrapper around realloc. Reallocates size bytes of memory.
1181 * The content of the intersection of the new and old size will be unchanged.
1183 * @param ptr the pointer to reallocate
1184 * @param size the number of bytes to reallocate
1185 * @return pointer to size bytes of memory
1187 #define GNUNET_realloc(ptr, size) \
1188 GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__)
1192 * Wrapper around free. Frees the memory referred to by ptr.
1193 * Note that it is generally better to free memory that was
1194 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1196 * @param ptr location where to free the memory. ptr must have
1197 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1199 #define GNUNET_free(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__)
1203 * Free the memory pointed to by ptr if ptr is not NULL.
1204 * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1206 * @param ptr the location in memory to free
1208 #define GNUNET_free_non_null(ptr) \
1211 void *__x__ = ptr; \
1212 if (__x__ != NULL) \
1214 GNUNET_free (__x__); \
1220 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string
1223 * @param a pointer to a zero-terminated string
1224 * @return a copy of the string including zero-termination
1226 #define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__)
1230 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string
1233 * @param a pointer to a string
1234 * @param length of the string to duplicate
1235 * @return a partial copy of the string including zero-termination
1237 #define GNUNET_strndup(a, length) \
1238 GNUNET_xstrndup_ (a, length, __FILE__, __LINE__)
1242 * Grow a well-typed (!) array. This is a convenience
1243 * method to grow a vector @a arr of size @a size
1244 * to the new (target) size @a tsize.
1247 * Example (simple, well-typed stack):
1250 * static struct foo * myVector = NULL;
1251 * static int myVecLen = 0;
1253 * static void push(struct foo * elem) {
1254 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1255 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1258 * static void pop(struct foo * elem) {
1259 * if (myVecLen == 0) die();
1260 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1261 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1265 * @param arr base-pointer of the vector, may be NULL if size is 0;
1266 * will be updated to reflect the new address. The TYPE of
1267 * arr is important since size is the number of elements and
1268 * not the size in bytes
1269 * @param size the number of elements in the existing vector (number
1270 * of elements to copy over), will be updated with the new
1272 * @param tsize the target size for the resulting vector, use 0 to
1273 * free the vector (then, arr will be NULL afterwards).
1275 #define GNUNET_array_grow(arr, size, tsize) \
1276 GNUNET_xgrow_ ((void **) &(arr), \
1285 * Append an element to a list (growing the list by one).
1287 * @param arr base-pointer of the vector, may be NULL if size is 0;
1288 * will be updated to reflect the new address. The TYPE of
1289 * arr is important since size is the number of elements and
1290 * not the size in bytes
1291 * @param size the number of elements in the existing vector (number
1292 * of elements to copy over), will be updated with the new
1294 * @param element the element that will be appended to the array
1296 #define GNUNET_array_append(arr, size, element) \
1299 GNUNET_array_grow (arr, size, size + 1); \
1300 (arr) [size - 1] = element; \
1305 * Like snprintf, just aborts if the buffer is of insufficient size.
1307 * @param buf pointer to buffer that is written to
1308 * @param size number of bytes in @a buf
1309 * @param format format strings
1310 * @param ... data for format string
1311 * @return number of bytes written to buf or negative value on error
1314 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1319 * Like asprintf, just portable.
1321 * @param buf set to a buffer of sufficient size (allocated, caller must free)
1322 * @param format format string (see printf, fprintf, etc.)
1323 * @param ... data for format string
1324 * @return number of bytes in "*buf" excluding 0-termination
1327 GNUNET_asprintf (char **buf, const char *format, ...);
1330 /* ************** internal implementations, use macros above! ************** */
1333 * Allocate memory. Checks the return value, aborts if no more
1334 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the
1335 * #GNUNET_malloc macro.
1336 * The memory will be zero'ed out.
1338 * @param size number of bytes to allocate
1339 * @param filename where is this call being made (for debugging)
1340 * @param linenumber line where this call is being made (for debugging)
1341 * @return allocated memory, never NULL
1344 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
1348 * Allocate memory for a two dimensional array in one block
1349 * and set up pointers. Aborts if no more memory is available.
1350 * Don't use GNUNET_xnew_array_2d_ directly. Use the
1351 * #GNUNET_new_array_2d macro.
1352 * The memory of the elements will be zero'ed out.
1354 * @param n size of the first dimension
1355 * @param m size of the second dimension
1356 * @param elementSize size of a single element in bytes
1357 * @param filename where is this call being made (for debugging)
1358 * @param linenumber line where this call is being made (for debugging)
1359 * @return allocated memory, never NULL
1362 GNUNET_xnew_array_2d_ (size_t n,
1365 const char *filename,
1370 * Allocate memory for a three dimensional array in one block
1371 * and set up pointers. Aborts if no more memory is available.
1372 * Don't use GNUNET_xnew_array_3d_ directly. Use the
1373 * #GNUNET_new_array_3d macro.
1374 * The memory of the elements will be zero'ed out.
1376 * @param n size of the first dimension
1377 * @param m size of the second dimension
1378 * @param o size of the third dimension
1379 * @param elementSize size of a single element in bytes
1380 * @param filename where is this call being made (for debugging)
1381 * @param linenumber line where this call is being made (for debugging)
1382 * @return allocated memory, never NULL
1385 GNUNET_xnew_array_3d_ (size_t n,
1389 const char *filename,
1394 * Allocate and initialize memory. Checks the return value, aborts if no more
1395 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the
1396 * #GNUNET_memdup macro.
1398 * @param buf buffer to initialize from (must contain size bytes)
1399 * @param size number of bytes to allocate
1400 * @param filename where is this call being made (for debugging)
1401 * @param linenumber line where this call is being made (for debugging)
1402 * @return allocated memory, never NULL
1405 GNUNET_xmemdup_ (const void *buf,
1407 const char *filename,
1412 * Allocate memory. This function does not check if the allocation
1413 * request is within reasonable bounds, allowing allocations larger
1414 * than 40 MB. If you don't expect the possibility of very large
1415 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed
1418 * @param size number of bytes to allocate
1419 * @param filename where is this call being made (for debugging)
1420 * @param linenumber line where this call is being made (for debugging)
1421 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1424 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1428 * Reallocate memory. Checks the return value, aborts if no more
1429 * memory is available.
1432 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1436 * Free memory. Merely a wrapper for the case that we
1437 * want to keep track of allocations. Don't use GNUNET_xfree_
1438 * directly. Use the #GNUNET_free macro.
1440 * @param ptr pointer to memory to free
1441 * @param filename where is this call being made (for debugging)
1442 * @param linenumber line where this call is being made (for debugging)
1445 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1449 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1450 * @param str string to duplicate
1451 * @param filename where is this call being made (for debugging)
1452 * @param linenumber line where this call is being made (for debugging)
1453 * @return the duplicated string
1456 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1459 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1461 * @param str string to duplicate
1462 * @param len length of the string to duplicate
1463 * @param filename where is this call being made (for debugging)
1464 * @param linenumber line where this call is being made (for debugging)
1465 * @return the duplicated string
1468 GNUNET_xstrndup_ (const char *str,
1470 const char *filename,
1474 * Grow an array, the new elements are zeroed out.
1475 * Grows old by (*oldCount-newCount)*elementSize
1476 * bytes and sets *oldCount to newCount.
1478 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1480 * @param old address of the pointer to the array
1482 * @param elementSize the size of the elements of the array
1483 * @param oldCount address of the number of elements in the *old array
1484 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1485 * @param filename where is this call being made (for debugging)
1486 * @param linenumber line where this call is being made (for debugging)
1489 GNUNET_xgrow_ (void **old,
1491 unsigned int *oldCount,
1492 unsigned int newCount,
1493 const char *filename,
1499 * Create a copy of the given message.
1501 * @param msg message to copy
1502 * @return duplicate of the message
1504 struct GNUNET_MessageHeader *
1505 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1509 * Set the async scope for the current thread.
1511 * @param aid the async scope identifier
1512 * @param old_scope[out] location to save the old scope
1515 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1516 struct GNUNET_AsyncScopeSave *old_scope);
1520 * Clear the current thread's async scope.
1522 * @param old_scope scope to restore
1525 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope);
1529 * Get the current async scope.
1531 * @param[out] scope_ret pointer to where the result is stored
1534 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret);
1538 * Generate a fresh async scope identifier.
1540 * @param[out] aid_ret pointer to where the result is stored
1543 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret);
1546 #if __STDC_VERSION__ < 199901L
1548 #define __func__ __FUNCTION__
1550 #define __func__ "<unknown>"
1556 * Valid task priorities. Use these, do not pass random integers!
1557 * For various reasons (#3862 -- building with QT Creator, and
1558 * our restricted cross-compilation with emscripten) this cannot
1559 * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1560 * Naturally, logically this is part of the scheduler.
1562 enum GNUNET_SCHEDULER_Priority
1565 * Run with the same priority as the current job.
1567 GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1570 * Run when otherwise idle.
1572 GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1575 * Run as background job (higher than idle,
1576 * lower than default).
1578 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1581 * Run with the default priority (normal
1582 * P2P operations). Any task that is scheduled
1583 * without an explicit priority being specified
1584 * will run with this priority.
1586 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1589 * Run with high priority (important requests).
1590 * Higher than DEFAULT.
1592 GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1595 * Run with priority for interactive tasks.
1596 * Higher than "HIGH".
1598 GNUNET_SCHEDULER_PRIORITY_UI = 5,
1601 * Run with priority for urgent tasks. Use
1602 * for things like aborts and shutdowns that
1603 * need to preempt "UI"-level tasks.
1606 GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1609 * This is an internal priority level that is only used for tasks
1610 * that are being triggered due to shutdown (they have automatically
1611 * highest priority). User code must not use this priority level
1612 * directly. Tasks run with this priority level that internally
1613 * schedule other tasks will see their original priority level
1614 * be inherited (unless otherwise specified).
1616 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1619 * Number of priorities (must be the last priority).
1620 * This priority must not be used by clients.
1622 GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1626 #if 0 /* keep Emacsens' auto-indent happy */
1633 #endif /* GNUNET_COMMON_H */