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
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
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
30 * @defgroup logging Logging
31 * @see [Documentation](https://gnunet.org/logging)
33 * @defgroup memory Memory management
35 #ifndef GNUNET_COMMON_H
36 #define GNUNET_COMMON_H
39 #include <sys/socket.h>
42 #include <netinet/in.h>
54 #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 0x000A0102
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
118 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
119 * tree where gnunet_config.h is unavailable
121 #ifndef GNUNET_EXTRA_LOGGING
122 #define GNUNET_EXTRA_LOGGING 0
129 # if __BYTE_ORDER == __LITTLE_ENDIAN
130 # define GNUNET_htobe16(x) __bswap_16 (x)
131 # define GNUNET_htole16(x) (x)
132 # define GNUNET_be16toh(x) __bswap_16 (x)
133 # define GNUNET_le16toh(x) (x)
135 # define GNUNET_htobe32(x) __bswap_32 (x)
136 # define GNUNET_htole32(x) (x)
137 # define GNUNET_be32toh(x) __bswap_32 (x)
138 # define GNUNET_le32toh(x) (x)
140 # define GNUNET_htobe64(x) __bswap_64 (x)
141 # define GNUNET_htole64(x) (x)
142 # define GNUNET_be64toh(x) __bswap_64 (x)
143 # define GNUNET_le64toh(x) (x)
145 # if __BYTE_ORDER == __BIG_ENDIAN
146 # define GNUNET_htobe16(x) (x)
147 # define GNUNET_htole16(x) __bswap_16 (x)
148 # define GNUNET_be16toh(x) (x)
149 # define GNUNET_le16toh(x) __bswap_16 (x)
151 # define GNUNET_htobe32(x) (x)
152 # define GNUNET_htole32(x) __bswap_32 (x)
153 # define GNUNET_be32toh(x) (x)
154 # define GNUNET_le32toh(x) __bswap_32 (x)
156 # define GNUNET_htobe64(x) (x)
157 # define GNUNET_htole64(x) __bswap_64 (x)
158 # define GNUNET_be64toh(x) (x)
159 # define GNUNET_le64toh(x) __bswap_64 (x)
164 * Macro used to avoid using 0 for the length of a variable-size
165 * array (Non-Zero-Length).
167 * Basically, C standard says that "int[n] x;" is undefined if n=0.
168 * This was supposed to prevent issues with pointer aliasing.
169 * However, C compilers may conclude that n!=0 as n=0 would be
170 * undefined, and then optimize under the assumption n!=0, which
171 * could cause actual issues. Hence, when initializing an array
172 * on the stack with a variable-length that might be zero, write
173 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
175 #define GNUNET_NZL(l) GNUNET_MAX(1,l)
179 * gcc-ism to get packed structs.
181 #define GNUNET_PACKED __attribute__((packed))
184 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
187 #define GNUNET_GCC_STRUCT_LAYOUT __attribute__((gcc_struct))
189 #define GNUNET_GCC_STRUCT_LAYOUT
193 * gcc-ism to force alignment; we use this to align char-arrays
194 * that may then be cast to 'struct's. See also gcc
197 #ifdef __BIGGEST_ALIGNMENT__
198 #define GNUNET_ALIGN __attribute__((aligned (__BIGGEST_ALIGNMENT__)))
200 #define GNUNET_ALIGN __attribute__((aligned (8)))
204 * gcc-ism to document unused arguments
206 #define GNUNET_UNUSED __attribute__((unused))
209 * gcc-ism to document functions that don't return
211 #define GNUNET_NORETURN __attribute__((noreturn))
216 * gcc 4.x-ism to pack structures even on W32 (to be used before structs);
217 * Using this would cause structs to be unaligned on the stack on Sparc,
218 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
219 * W32 doesn't run on sparc anyway.
221 #define GNUNET_NETWORK_STRUCT_BEGIN \
222 _Pragma("pack(push)") \
226 * gcc 4.x-ism to pack structures even on W32 (to be used after structs)
227 * Using this would cause structs to be unaligned on the stack on Sparc,
228 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
229 * W32 doesn't run on sparc anyway.
231 #define GNUNET_NETWORK_STRUCT_END _Pragma("pack(pop)")
234 #error gcc 4.x or higher required on W32 systems
238 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
240 #define GNUNET_NETWORK_STRUCT_BEGIN
243 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
245 #define GNUNET_NETWORK_STRUCT_END
248 /* ************************ super-general types *********************** */
250 GNUNET_NETWORK_STRUCT_BEGIN
253 * Header for all communications.
255 struct GNUNET_MessageHeader
259 * The length of the struct (in bytes, including the length field itself),
260 * in big-endian format.
262 uint16_t size GNUNET_PACKED;
265 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
267 uint16_t type GNUNET_PACKED;
273 * Answer from service to client about last operation.
275 struct GNUNET_OperationResultMessage
277 struct GNUNET_MessageHeader header;
279 uint32_t reserved GNUNET_PACKED;
284 uint64_t op_id GNUNET_PACKED;
287 * Status code for the operation.
289 uint64_t result_code GNUNET_PACKED;
291 /* Followed by data. */
294 GNUNET_NETWORK_STRUCT_END
297 * Function called with a filename.
300 * @param filename complete filename (absolute path)
301 * @return #GNUNET_OK to continue to iterate,
302 * #GNUNET_NO to stop iteration with no error,
303 * #GNUNET_SYSERR to abort iteration with error!
306 (*GNUNET_FileNameCallback) (void *cls,
307 const char *filename);
311 * Generic continuation callback.
313 * @param cls Closure.
316 (*GNUNET_ContinuationCallback) (void *cls);
320 * Function called with the result of an asynchronous operation.
325 * Result code for the operation.
327 * Data result for the operation.
332 (*GNUNET_ResultCallback) (void *cls, int64_t result_code,
333 const void *data, uint16_t data_size);
336 /* ****************************** logging ***************************** */
342 enum GNUNET_ErrorType
344 GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
345 GNUNET_ERROR_TYPE_NONE = 0,
346 GNUNET_ERROR_TYPE_ERROR = 1,
347 GNUNET_ERROR_TYPE_WARNING = 2,
348 /* UX: We need a message type that is output by
349 * default without looking like there is a problem.
351 GNUNET_ERROR_TYPE_MESSAGE = 4,
352 GNUNET_ERROR_TYPE_INFO = 8,
353 GNUNET_ERROR_TYPE_DEBUG = 16,
354 GNUNET_ERROR_TYPE_INVALID = 32,
355 GNUNET_ERROR_TYPE_BULK = 64
361 * User-defined handler for log messages.
364 * @param kind severeity
365 * @param component what component is issuing the message?
366 * @param date when was the message logged?
367 * @param message what is the message
370 (*GNUNET_Logger) (void *cls,
371 enum GNUNET_ErrorType kind,
372 const char *component,
374 const char *message);
379 * Get the number of log calls that are going to be skipped
381 * @return number of log calls to be ignored
384 GNUNET_get_log_skip (void);
387 #if !defined(GNUNET_CULL_LOGGING)
389 GNUNET_get_log_call_status (int caller_level,
392 const char *function,
401 * @param kind how serious is the error?
402 * @param message what is the message (format string)
403 * @param ... arguments for format string
406 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
407 __attribute__ ((format (gnu_printf, 2, 3)));
410 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
411 #define _GNUNET_BOOLEAN_EXPR(expr) \
413 int _gnunet_boolean_var_; \
415 _gnunet_boolean_var_ = 1; \
417 _gnunet_boolean_var_ = 0; \
418 _gnunet_boolean_var_; \
420 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 1))
421 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 0))
423 #define GN_LIKELY(expr) (expr)
424 #define GN_UNLIKELY(expr) (expr)
427 #if !defined(GNUNET_LOG_CALL_STATUS)
428 #define GNUNET_LOG_CALL_STATUS -1
434 * Log function that specifies an alternative component.
435 * This function should be used by plugins.
437 * @param kind how serious is the error?
438 * @param comp component responsible for generating the message
439 * @param message what is the message (format string)
440 * @param ... arguments for format string
443 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
444 const char *message, ...);
446 #if !defined(GNUNET_CULL_LOGGING)
447 #define GNUNET_log_from(kind,comp,...) do { int log_line = __LINE__;\
448 static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
449 if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
450 if (GN_UNLIKELY(log_call_enabled == -1))\
451 log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), (comp), __FILE__, __FUNCTION__, log_line); \
452 if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
454 if (GN_UNLIKELY(log_call_enabled))\
455 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \
460 #define GNUNET_log(kind,...) do { int log_line = __LINE__;\
461 static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
462 if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
463 if (GN_UNLIKELY(log_call_enabled == -1))\
464 log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), NULL, __FILE__, __FUNCTION__, log_line);\
465 if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
467 if (GN_UNLIKELY(log_call_enabled))\
468 GNUNET_log_nocheck ((kind), __VA_ARGS__); \
473 #define GNUNET_log(...)
474 #define GNUNET_log_from(...)
480 * Log error message about missing configuration option.
482 * @param kind log level
483 * @param section section with missing option
484 * @param option name of missing option
487 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
494 * Log error message about invalid configuration option value.
496 * @param kind log level
497 * @param section section with invalid option
498 * @param option name of invalid option
499 * @param required what is required that is invalid about the option
502 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
505 const char *required);
510 * Abort the process, generate a core dump if possible.
511 * Most code should use `GNUNET_assert (0)` instead to
512 * first log the location of the failure.
515 GNUNET_abort_ (void) GNUNET_NORETURN;
520 * Ignore the next @a n calls to the log function.
522 * @param n number of log calls to ignore (could be negative)
523 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
526 GNUNET_log_skip (int n,
534 * @param comp default component to use
535 * @param loglevel what types of messages should be logged
536 * @param logfile change logging to logfile (use NULL to keep stderr)
537 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
540 GNUNET_log_setup (const char *comp,
541 const char *loglevel,
542 const char *logfile);
547 * Add a custom logger. Note that installing any custom logger
548 * will disable the standard logger. When multiple custom loggers
549 * are installed, all will be called. The standard logger will
550 * only be used if no custom loggers are present.
552 * @param logger log function
553 * @param logger_cls closure for @a logger
556 GNUNET_logger_add (GNUNET_Logger logger,
562 * Remove a custom logger.
564 * @param logger log function
565 * @param logger_cls closure for @a logger
568 GNUNET_logger_remove (GNUNET_Logger logger,
574 * Convert a short hash value to a string (for printing debug messages).
575 * This is one of the very few calls in the entire API that is
578 * @param shc the hash code
582 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
587 * Convert a hash value to a string (for printing debug messages).
588 * This is one of the very few calls in the entire API that is
591 * @param hc the hash code
595 GNUNET_h2s (const struct GNUNET_HashCode *hc);
600 * Convert a hash value to a string (for printing debug messages).
601 * This is one of the very few calls in the entire API that is
602 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
603 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
604 * used within the same log statement.
606 * @param hc the hash code
610 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
615 * Convert a hash value to a string (for printing debug messages).
616 * This prints all 104 characters of a hashcode!
617 * This is one of the very few calls in the entire API that is
620 * @param hc the hash code
624 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
628 * Public key. Details in gnunet_util_crypto.h.
630 struct GNUNET_CRYPTO_EddsaPublicKey;
634 * Public key. Details in gnunet_util_crypto.h.
636 struct GNUNET_CRYPTO_EcdhePublicKey;
641 * Convert a public key value to a string (for printing debug messages).
642 * This is one of the very few calls in the entire API that is
645 * @param hc the hash code
649 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
654 * Convert a public key value to a string (for printing debug messages).
655 * This is one of the very few calls in the entire API that is
658 * @param hc the hash code
662 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
667 * Convert a public key value to a string (for printing debug messages).
668 * This is one of the very few calls in the entire API that is
671 * @param hc the hash code
675 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
680 * Convert a public key value to a string (for printing debug messages).
681 * This is one of the very few calls in the entire API that is
684 * @param hc the hash code
688 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
693 * Convert a peer identity to a string (for printing debug messages).
694 * This is one of the very few calls in the entire API that is
697 * @param pid the peer identity
698 * @return string form of the pid; will be overwritten by next
699 * call to #GNUNET_i2s().
702 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
707 * Convert a peer identity to a string (for printing debug messages).
708 * This is one of the very few calls in the entire API that is
709 * NOT reentrant! Identical to #GNUNET_i2s(), except that another
710 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
711 * used within the same log statement.
713 * @param pid the peer identity
714 * @return string form of the pid; will be overwritten by next
715 * call to #GNUNET_i2s().
718 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
723 * Convert a peer identity to a string (for printing debug messages).
724 * This is one of the very few calls in the entire API that is
727 * @param pid the peer identity
728 * @return string form of the pid; will be overwritten by next
729 * call to #GNUNET_i2s_full().
732 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
737 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
738 * (for printing debug messages). This is one of the very few calls
739 * in the entire API that is NOT reentrant!
741 * @param addr the address
742 * @param addrlen the length of the @a addr
743 * @return nicely formatted string for the address
744 * will be overwritten by next call to #GNUNET_a2s().
747 GNUNET_a2s (const struct sockaddr *addr,
753 * Convert error type to string.
755 * @param kind type to convert
756 * @return string corresponding to the type
759 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
764 * Use this for fatal errors that cannot be handled
766 #define GNUNET_assert(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); GNUNET_abort_(); } } while(0)
771 * Use this for fatal errors that cannot be handled
773 #define GNUNET_assert_at(cond, f, l) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), f, l); GNUNET_abort_(); } } while(0)
778 * Use this for fatal errors that cannot be handled
780 * @param cond Condition to evaluate
781 * @param comp Component string to use for logging
783 #define GNUNET_assert_from(cond, comp) do { if (! (cond)) { GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, comp, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); GNUNET_abort_(); } } while(0)
788 * Use this for internal assertion violations that are
789 * not fatal (can be handled) but should not occur.
791 #define GNUNET_break(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
796 * Use this for assertion violations caused by other
797 * peers (i.e. protocol violations). We do not want to
798 * confuse end-users (say, some other peer runs an
799 * older, broken or incompatible GNUnet version), but
800 * we still want to see these problems during
801 * development and testing. "OP == other peer".
803 #define GNUNET_break_op(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, _("External protocol violation detected at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
808 * Log an error message at log-level 'level' that indicates
809 * a failure of the command 'cmd' with the message given
810 * by strerror(errno).
812 #define GNUNET_log_strerror(level, cmd) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, STRERROR(errno)); } while(0)
817 * Log an error message at log-level 'level' that indicates
818 * a failure of the command 'cmd' with the message given
819 * by strerror(errno).
821 #define GNUNET_log_from_strerror(level, component, cmd) do { GNUNET_log_from (level, component, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, STRERROR(errno)); } while(0)
826 * Log an error message at log-level 'level' that indicates
827 * a failure of the command 'cmd' with the message given
828 * by strerror(errno).
830 #define GNUNET_log_strerror_file(level, cmd, filename) do { GNUNET_log(level, _("`%s' failed on file `%s' at %s:%d with error: %s\n"), cmd, filename, __FILE__, __LINE__, STRERROR(errno)); } while(0)
835 * Log an error message at log-level 'level' that indicates
836 * a failure of the command 'cmd' with the message given
837 * by strerror(errno).
839 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) do { GNUNET_log_from (level, component, _("`%s' failed on file `%s' at %s:%d with error: %s\n"), cmd, filename,__FILE__, __LINE__, STRERROR(errno)); } while(0)
841 /* ************************* endianess conversion ****************** */
844 * Convert unsigned 64-bit integer to network byte order.
847 * The value in host byte order.
849 * @return The same value in network byte order.
852 GNUNET_htonll (uint64_t n);
856 * Convert unsigned 64-bit integer to host byte order.
859 * The value in network byte order.
861 * @return The same value in host byte order.
864 GNUNET_ntohll (uint64_t n);
868 * Convert double to network byte order.
871 * The value in host byte order.
873 * @return The same value in network byte order.
876 GNUNET_hton_double (double d);
880 * Convert double to host byte order
883 * The value in network byte order.
885 * @return The same value in host byte order.
888 GNUNET_ntoh_double (double d);
891 /* ************************* allocation functions ****************** */
895 * Maximum allocation with GNUNET_malloc macro.
897 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
901 * Allocate a struct or union of the given @a type.
902 * Wrapper around #GNUNET_malloc that returns a pointer
903 * to the newly created object of the correct type.
905 * @param type name of the struct or union, i.e. pass 'struct Foo'.
907 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
910 * Call memcpy() but check for @a n being 0 first. In the latter
911 * case, it is now safe to pass NULL for @a src or @a dst.
912 * Unlike traditional memcpy(), returns nothing.
914 * @param dst destination of the copy, may be NULL if @a n is zero
915 * @param src source of the copy, may be NULL if @a n is zero
916 * @param n number of bytes to copy
918 #define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0)
923 * Allocate a size @a n array with structs or unions of the given @a type.
924 * Wrapper around #GNUNET_malloc that returns a pointer
925 * to the newly created objects of the correct type.
927 * @param n number of elements in the array
928 * @param type name of the struct or union, i.e. pass 'struct Foo'.
930 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
934 * Allocate a size @a n times @a m array
935 * with structs or unions of the given @a type.
937 * @param n size of the first dimension
938 * @param m size of the second dimension
939 * @param type name of the struct or union, i.e. pass 'struct Foo'.
941 #define GNUNET_new_array_2d(n, m, type) (type **) GNUNET_xnew_array_2d_ (n, m, sizeof (type), __FILE__, __LINE__)
945 * Allocate a size @a n times @a m times @a o array
946 * with structs or unions of the given @a type.
948 * @param n size of the first dimension
949 * @param m size of the second dimension
950 * @param o size of the third dimension
951 * @param type name of the struct or union, i.e. pass 'struct Foo'.
953 #define GNUNET_new_array_3d(n, m, o, type) (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof (type), __FILE__, __LINE__)
957 * Wrapper around malloc. Allocates size bytes of memory.
958 * The memory will be zero'ed out.
960 * @param size the number of bytes to allocate, must be
961 * smaller than 40 MB.
962 * @return pointer to size bytes of memory, never NULL (!)
964 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
968 * Allocate and initialize a block of memory.
970 * @param buf data to initalize the block with
971 * @param size the number of bytes in buf (and size of the allocation)
972 * @return pointer to size bytes of memory, never NULL (!)
974 #define GNUNET_memdup(buf,size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__)
978 * Wrapper around malloc. Allocates size bytes of memory.
979 * The memory will be zero'ed out.
981 * @param size the number of bytes to allocate
982 * @return pointer to size bytes of memory, NULL if we do not have enough memory
984 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
988 * Wrapper around realloc. Reallocates size bytes of memory.
989 * The content of the intersection of the new and old size will be unchanged.
991 * @param ptr the pointer to reallocate
992 * @param size the number of bytes to reallocate
993 * @return pointer to size bytes of memory
995 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
999 * Wrapper around free. Frees the memory referred to by ptr.
1000 * Note that it is generally better to free memory that was
1001 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1003 * @param ptr location where to free the memory. ptr must have
1004 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1006 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
1010 * Free the memory pointed to by ptr if ptr is not NULL.
1011 * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1013 * @param ptr the location in memory to free
1015 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
1019 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string
1022 * @param a pointer to a zero-terminated string
1023 * @return a copy of the string including zero-termination
1025 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
1029 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string
1032 * @param a pointer to a string
1033 * @param length of the string to duplicate
1034 * @return a partial copy of the string including zero-termination
1036 #define GNUNET_strndup(a,length) GNUNET_xstrndup_(a,length,__FILE__,__LINE__)
1040 * Grow a well-typed (!) array. This is a convenience
1041 * method to grow a vector @a arr of size @a size
1042 * to the new (target) size @a tsize.
1045 * Example (simple, well-typed stack):
1048 * static struct foo * myVector = NULL;
1049 * static int myVecLen = 0;
1051 * static void push(struct foo * elem) {
1052 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1053 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1056 * static void pop(struct foo * elem) {
1057 * if (myVecLen == 0) die();
1058 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1059 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1063 * @param arr base-pointer of the vector, may be NULL if size is 0;
1064 * will be updated to reflect the new address. The TYPE of
1065 * arr is important since size is the number of elements and
1066 * not the size in bytes
1067 * @param size the number of elements in the existing vector (number
1068 * of elements to copy over), will be updated with the new
1070 * @param tsize the target size for the resulting vector, use 0 to
1071 * free the vector (then, arr will be NULL afterwards).
1073 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
1077 * Append an element to a list (growing the list by one).
1079 * @param arr base-pointer of the vector, may be NULL if size is 0;
1080 * will be updated to reflect the new address. The TYPE of
1081 * arr is important since size is the number of elements and
1082 * not the size in bytes
1083 * @param size the number of elements in the existing vector (number
1084 * of elements to copy over), will be updated with the new
1086 * @param element the element that will be appended to the array
1088 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
1092 * Like snprintf, just aborts if the buffer is of insufficient size.
1094 * @param buf pointer to buffer that is written to
1095 * @param size number of bytes in @a buf
1096 * @param format format strings
1097 * @param ... data for format string
1098 * @return number of bytes written to buf or negative value on error
1101 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1106 * Like asprintf, just portable.
1108 * @param buf set to a buffer of sufficient size (allocated, caller must free)
1109 * @param format format string (see printf, fprintf, etc.)
1110 * @param ... data for format string
1111 * @return number of bytes in "*buf" excluding 0-termination
1114 GNUNET_asprintf (char **buf, const char *format, ...);
1117 /* ************** internal implementations, use macros above! ************** */
1120 * Allocate memory. Checks the return value, aborts if no more
1121 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the
1122 * #GNUNET_malloc macro.
1123 * The memory will be zero'ed out.
1125 * @param size number of bytes to allocate
1126 * @param filename where is this call being made (for debugging)
1127 * @param linenumber line where this call is being made (for debugging)
1128 * @return allocated memory, never NULL
1131 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
1135 * Allocate memory for a two dimensional array in one block
1136 * and set up pointers. Aborts if no more memory is available.
1137 * Don't use GNUNET_xnew_array_2d_ directly. Use the
1138 * #GNUNET_new_array_2d macro.
1139 * The memory of the elements will be zero'ed out.
1141 * @param n size of the first dimension
1142 * @param m size of the second dimension
1143 * @param elementSize size of a single element in bytes
1144 * @param filename where is this call being made (for debugging)
1145 * @param linenumber line where this call is being made (for debugging)
1146 * @return allocated memory, never NULL
1149 GNUNET_xnew_array_2d_ (size_t n, size_t m, size_t elementSize,
1150 const char *filename, int linenumber);
1154 * Allocate memory for a three dimensional array in one block
1155 * and set up pointers. Aborts if no more memory is available.
1156 * Don't use GNUNET_xnew_array_3d_ directly. Use the
1157 * #GNUNET_new_array_3d macro.
1158 * The memory of the elements will be zero'ed out.
1160 * @param n size of the first dimension
1161 * @param m size of the second dimension
1162 * @param o size of the third dimension
1163 * @param elementSize size of a single element in bytes
1164 * @param filename where is this call being made (for debugging)
1165 * @param linenumber line where this call is being made (for debugging)
1166 * @return allocated memory, never NULL
1169 GNUNET_xnew_array_3d_ (size_t n, size_t m, size_t o, size_t elementSize,
1170 const char *filename, int linenumber);
1174 * Allocate and initialize memory. Checks the return value, aborts if no more
1175 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the
1176 * #GNUNET_memdup macro.
1178 * @param buf buffer to initialize from (must contain size bytes)
1179 * @param size number of bytes to allocate
1180 * @param filename where is this call being made (for debugging)
1181 * @param linenumber line where this call is being made (for debugging)
1182 * @return allocated memory, never NULL
1185 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
1190 * Allocate memory. This function does not check if the allocation
1191 * request is within reasonable bounds, allowing allocations larger
1192 * than 40 MB. If you don't expect the possibility of very large
1193 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed
1196 * @param size number of bytes to allocate
1197 * @param filename where is this call being made (for debugging)
1198 * @param linenumber line where this call is being made (for debugging)
1199 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1202 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1206 * Reallocate memory. Checks the return value, aborts if no more
1207 * memory is available.
1210 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1214 * Free memory. Merely a wrapper for the case that we
1215 * want to keep track of allocations. Don't use GNUNET_xfree_
1216 * directly. Use the #GNUNET_free macro.
1218 * @param ptr pointer to memory to free
1219 * @param filename where is this call being made (for debugging)
1220 * @param linenumber line where this call is being made (for debugging)
1223 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1227 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1228 * @param str string to duplicate
1229 * @param filename where is this call being made (for debugging)
1230 * @param linenumber line where this call is being made (for debugging)
1231 * @return the duplicated string
1234 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1237 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1239 * @param str string to duplicate
1240 * @param len length of the string to duplicate
1241 * @param filename where is this call being made (for debugging)
1242 * @param linenumber line where this call is being made (for debugging)
1243 * @return the duplicated string
1246 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
1250 * Grow an array, the new elements are zeroed out.
1251 * Grows old by (*oldCount-newCount)*elementSize
1252 * bytes and sets *oldCount to newCount.
1254 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1256 * @param old address of the pointer to the array
1258 * @param elementSize the size of the elements of the array
1259 * @param oldCount address of the number of elements in the *old array
1260 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1261 * @param filename where is this call being made (for debugging)
1262 * @param linenumber line where this call is being made (for debugging)
1265 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
1266 unsigned int newCount, const char *filename, int linenumber);
1271 * Create a copy of the given message.
1273 * @param msg message to copy
1274 * @return duplicate of the message
1276 struct GNUNET_MessageHeader *
1277 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1280 #if __STDC_VERSION__ < 199901L
1282 #define __func__ __FUNCTION__
1284 #define __func__ "<unknown>"
1290 * Valid task priorities. Use these, do not pass random integers!
1291 * For various reasons (#3862 -- building with QT Creator, and
1292 * our restricted cross-compilation with emscripten) this cannot
1293 * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1294 * Naturally, logically this is part of the scheduler.
1296 enum GNUNET_SCHEDULER_Priority
1299 * Run with the same priority as the current job.
1301 GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1304 * Run when otherwise idle.
1306 GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1309 * Run as background job (higher than idle,
1310 * lower than default).
1312 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1315 * Run with the default priority (normal
1316 * P2P operations). Any task that is scheduled
1317 * without an explicit priority being specified
1318 * will run with this priority.
1320 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1323 * Run with high priority (important requests).
1324 * Higher than DEFAULT.
1326 GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1329 * Run with priority for interactive tasks.
1330 * Higher than "HIGH".
1332 GNUNET_SCHEDULER_PRIORITY_UI = 5,
1335 * Run with priority for urgent tasks. Use
1336 * for things like aborts and shutdowns that
1337 * need to preempt "UI"-level tasks.
1340 GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1343 * This is an internal priority level that is only used for tasks
1344 * that are being triggered due to shutdown (they have automatically
1345 * highest priority). User code must not use this priority level
1346 * directly. Tasks run with this priority level that internally
1347 * schedule other tasks will see their original priority level
1348 * be inherited (unless otherwise specified).
1350 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1353 * Number of priorities (must be the last priority).
1354 * This priority must not be used by clients.
1356 GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1360 #if 0 /* keep Emacsens' auto-indent happy */
1367 #endif /* GNUNET_COMMON_H */