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
62 #if 0 /* keep Emacsens' auto-indent happy */
68 * Version of the API (for entire gnunetutil.so library).
70 #define GNUNET_UTIL_VERSION 0x000A0102
74 * Named constants for return values. The following invariants hold:
75 * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK !=
76 * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO !=
77 * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`.
80 #define GNUNET_SYSERR -1
84 #define GNUNET_MIN(a,b) (((a) < (b)) ? (a) : (b))
86 #define GNUNET_MAX(a,b) (((a) > (b)) ? (a) : (b))
88 /* some systems use one underscore only, and mingw uses no underscore... */
91 #define __BYTE_ORDER _BYTE_ORDER
94 #define __BYTE_ORDER BYTE_ORDER
100 #define __BIG_ENDIAN _BIG_ENDIAN
103 #define __BIG_ENDIAN BIG_ENDIAN
107 #ifndef __LITTLE_ENDIAN
108 #ifdef _LITTLE_ENDIAN
109 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
112 #define __LITTLE_ENDIAN LITTLE_ENDIAN
118 * wrap va_arg for enums
120 #define GNUNET_VA_ARG_ENUM(va,X) ((enum X) va_arg (va, int))
125 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
126 * tree where gnunet_config.h is unavailable
128 #ifndef GNUNET_EXTRA_LOGGING
129 #define GNUNET_EXTRA_LOGGING 0
136 # if __BYTE_ORDER == __LITTLE_ENDIAN
137 # define GNUNET_htobe16(x) __bswap_16 (x)
138 # define GNUNET_htole16(x) (x)
139 # define GNUNET_be16toh(x) __bswap_16 (x)
140 # define GNUNET_le16toh(x) (x)
142 # define GNUNET_htobe32(x) __bswap_32 (x)
143 # define GNUNET_htole32(x) (x)
144 # define GNUNET_be32toh(x) __bswap_32 (x)
145 # define GNUNET_le32toh(x) (x)
147 # define GNUNET_htobe64(x) __bswap_64 (x)
148 # define GNUNET_htole64(x) (x)
149 # define GNUNET_be64toh(x) __bswap_64 (x)
150 # define GNUNET_le64toh(x) (x)
152 # if __BYTE_ORDER == __BIG_ENDIAN
153 # define GNUNET_htobe16(x) (x)
154 # define GNUNET_htole16(x) __bswap_16 (x)
155 # define GNUNET_be16toh(x) (x)
156 # define GNUNET_le16toh(x) __bswap_16 (x)
158 # define GNUNET_htobe32(x) (x)
159 # define GNUNET_htole32(x) __bswap_32 (x)
160 # define GNUNET_be32toh(x) (x)
161 # define GNUNET_le32toh(x) __bswap_32 (x)
163 # define GNUNET_htobe64(x) (x)
164 # define GNUNET_htole64(x) __bswap_64 (x)
165 # define GNUNET_be64toh(x) (x)
166 # define GNUNET_le64toh(x) __bswap_64 (x)
171 * Macro used to avoid using 0 for the length of a variable-size
172 * array (Non-Zero-Length).
174 * Basically, C standard says that "int[n] x;" is undefined if n=0.
175 * This was supposed to prevent issues with pointer aliasing.
176 * However, C compilers may conclude that n!=0 as n=0 would be
177 * undefined, and then optimize under the assumption n!=0, which
178 * could cause actual issues. Hence, when initializing an array
179 * on the stack with a variable-length that might be zero, write
180 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
182 #define GNUNET_NZL(l) GNUNET_MAX(1,l)
186 * gcc-ism to get packed structs.
188 #define GNUNET_PACKED __attribute__((packed))
191 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
194 #define GNUNET_GCC_STRUCT_LAYOUT __attribute__((gcc_struct))
196 #define GNUNET_GCC_STRUCT_LAYOUT
200 * gcc-ism to force alignment; we use this to align char-arrays
201 * that may then be cast to 'struct's. See also gcc
204 #ifdef __BIGGEST_ALIGNMENT__
205 #define GNUNET_ALIGN __attribute__((aligned (__BIGGEST_ALIGNMENT__)))
207 #define GNUNET_ALIGN __attribute__((aligned (8)))
211 * gcc-ism to document unused arguments
213 #define GNUNET_UNUSED __attribute__((unused))
216 * gcc-ism to document functions that don't return
218 #define GNUNET_NORETURN __attribute__((noreturn))
223 * gcc 4.x-ism to pack structures even on W32 (to be used before structs);
224 * Using this would cause structs to be unaligned on the stack on Sparc,
225 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
226 * W32 doesn't run on sparc anyway.
228 #define GNUNET_NETWORK_STRUCT_BEGIN \
229 _Pragma("pack(push)") \
233 * gcc 4.x-ism to pack structures even on W32 (to be used after structs)
234 * Using this would cause structs to be unaligned on the stack on Sparc,
235 * so we *only* use this on W32 (see #670578 from Debian); fortunately,
236 * W32 doesn't run on sparc anyway.
238 #define GNUNET_NETWORK_STRUCT_END _Pragma("pack(pop)")
241 #error gcc 4.x or higher required on W32 systems
245 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
247 #define GNUNET_NETWORK_STRUCT_BEGIN
250 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
252 #define GNUNET_NETWORK_STRUCT_END
255 /* ************************ super-general types *********************** */
257 GNUNET_NETWORK_STRUCT_BEGIN
260 * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512.
262 struct GNUNET_HashCode
264 uint32_t bits[512 / 8 / sizeof (uint32_t)]; /* = 16 */
270 * @brief A 256-bit hashcode. Used under special conditions, like when space
271 * is critical and security is not impacted by it.
273 struct GNUNET_ShortHashCode
275 uint32_t bits[256 / 8 / sizeof (uint32_t)]; /* = 8 */
281 * Header for all communications.
283 struct GNUNET_MessageHeader
287 * The length of the struct (in bytes, including the length field itself),
288 * in big-endian format.
290 uint16_t size GNUNET_PACKED;
293 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
295 uint16_t type GNUNET_PACKED;
301 * Answer from service to client about last operation.
303 struct GNUNET_OperationResultMessage
305 struct GNUNET_MessageHeader header;
307 uint32_t reserved GNUNET_PACKED;
312 uint64_t op_id GNUNET_PACKED;
315 * Status code for the operation.
317 uint64_t result_code GNUNET_PACKED;
319 /* Followed by data. */
322 GNUNET_NETWORK_STRUCT_END
325 * Function called with a filename.
328 * @param filename complete filename (absolute path)
329 * @return #GNUNET_OK to continue to iterate,
330 * #GNUNET_NO to stop iteration with no error,
331 * #GNUNET_SYSERR to abort iteration with error!
334 (*GNUNET_FileNameCallback) (void *cls,
335 const char *filename);
339 * Generic continuation callback.
341 * @param cls Closure.
344 (*GNUNET_ContinuationCallback) (void *cls);
348 * Function called with the result of an asynchronous operation.
353 * Result code for the operation.
355 * Data result for the operation.
360 (*GNUNET_ResultCallback) (void *cls, int64_t result_code,
361 const void *data, uint16_t data_size);
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
398 (*GNUNET_Logger) (void *cls,
399 enum GNUNET_ErrorType kind,
400 const char *component,
402 const char *message);
407 * Get the number of log calls that are going to be skipped
409 * @return number of log calls to be ignored
412 GNUNET_get_log_skip (void);
415 #if !defined(GNUNET_CULL_LOGGING)
417 GNUNET_get_log_call_status (int caller_level,
420 const char *function,
429 * @param kind how serious is the error?
430 * @param message what is the message (format string)
431 * @param ... arguments for format string
434 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
435 __attribute__ ((format (printf, 2, 3)));
438 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
439 #define _GNUNET_BOOLEAN_EXPR(expr) \
441 int _gnunet_boolean_var_; \
443 _gnunet_boolean_var_ = 1; \
445 _gnunet_boolean_var_ = 0; \
446 _gnunet_boolean_var_; \
448 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 1))
449 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 0))
451 #define GN_LIKELY(expr) (expr)
452 #define GN_UNLIKELY(expr) (expr)
455 #if !defined(GNUNET_LOG_CALL_STATUS)
456 #define GNUNET_LOG_CALL_STATUS -1
462 * Log function that specifies an alternative component.
463 * This function should be used by plugins.
465 * @param kind how serious is the error?
466 * @param comp component responsible for generating the message
467 * @param message what is the message (format string)
468 * @param ... arguments for format string
471 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
472 const char *message, ...);
474 #if !defined(GNUNET_CULL_LOGGING)
475 #define GNUNET_log_from(kind,comp,...) do { int log_line = __LINE__;\
476 static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
477 if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
478 if (GN_UNLIKELY(log_call_enabled == -1))\
479 log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), (comp), __FILE__, __FUNCTION__, log_line); \
480 if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
482 if (GN_UNLIKELY(log_call_enabled))\
483 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \
488 #define GNUNET_log(kind,...) do { int log_line = __LINE__;\
489 static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
490 if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
491 if (GN_UNLIKELY(log_call_enabled == -1))\
492 log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), NULL, __FILE__, __FUNCTION__, log_line);\
493 if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
495 if (GN_UNLIKELY(log_call_enabled))\
496 GNUNET_log_nocheck ((kind), __VA_ARGS__); \
501 #define GNUNET_log(...)
502 #define GNUNET_log_from(...)
508 * Log error message about missing configuration option.
510 * @param kind log level
511 * @param section section with missing option
512 * @param option name of missing option
515 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
522 * Log error message about invalid configuration option value.
524 * @param kind log level
525 * @param section section with invalid option
526 * @param option name of invalid option
527 * @param required what is required that is invalid about the option
530 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
533 const char *required);
538 * Abort the process, generate a core dump if possible.
539 * Most code should use `GNUNET_assert (0)` instead to
540 * first log the location of the failure.
543 GNUNET_abort_ (void) GNUNET_NORETURN;
548 * Ignore the next @a n calls to the log function.
550 * @param n number of log calls to ignore (could be negative)
551 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
554 GNUNET_log_skip (int n,
562 * @param comp default component to use
563 * @param loglevel what types of messages should be logged
564 * @param logfile change logging to logfile (use NULL to keep stderr)
565 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
568 GNUNET_log_setup (const char *comp,
569 const char *loglevel,
570 const char *logfile);
575 * Add a custom logger. Note that installing any custom logger
576 * will disable the standard logger. When multiple custom loggers
577 * are installed, all will be called. The standard logger will
578 * only be used if no custom loggers are present.
580 * @param logger log function
581 * @param logger_cls closure for @a logger
584 GNUNET_logger_add (GNUNET_Logger logger,
590 * Remove a custom logger.
592 * @param logger log function
593 * @param logger_cls closure for @a logger
596 GNUNET_logger_remove (GNUNET_Logger logger,
602 * Convert a short hash value to a string (for printing debug messages).
603 * This is one of the very few calls in the entire API that is
606 * @param shc the hash code
610 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
615 * Convert a hash value to a string (for printing debug messages).
616 * This is one of the very few calls in the entire API that is
619 * @param hc the hash code
623 GNUNET_h2s (const struct GNUNET_HashCode *hc);
628 * Convert a hash value to a string (for printing debug messages).
629 * This is one of the very few calls in the entire API that is
630 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
631 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
632 * used within the same log statement.
634 * @param hc the hash code
638 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
643 * Convert a hash value to a string (for printing debug messages).
644 * This prints all 104 characters of a hashcode!
645 * This is one of the very few calls in the entire API that is
648 * @param hc the hash code
652 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
656 * Public key. Details in gnunet_util_crypto.h.
658 struct GNUNET_CRYPTO_EddsaPublicKey;
662 * Public key. Details in gnunet_util_crypto.h.
664 struct GNUNET_CRYPTO_EcdhePublicKey;
669 * Convert a public key value to a string (for printing debug messages).
670 * This is one of the very few calls in the entire API that is
673 * @param hc the hash code
677 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
682 * Convert a public key value to a string (for printing debug messages).
683 * This is one of the very few calls in the entire API that is
686 * @param hc the hash code
690 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
695 * Convert a public key value to a string (for printing debug messages).
696 * This is one of the very few calls in the entire API that is
699 * @param hc the hash code
703 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
708 * Convert a public key value to a string (for printing debug messages).
709 * This is one of the very few calls in the entire API that is
712 * @param hc the hash code
716 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
721 * Convert a peer identity to a string (for printing debug messages).
722 * This is one of the very few calls in the entire API that is
725 * @param pid the peer identity
726 * @return string form of the pid; will be overwritten by next
727 * call to #GNUNET_i2s().
730 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
735 * Convert a peer identity to a string (for printing debug messages).
736 * This is one of the very few calls in the entire API that is
737 * NOT reentrant! Identical to #GNUNET_i2s(), except that another
738 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
739 * used within the same log statement.
741 * @param pid the peer identity
742 * @return string form of the pid; will be overwritten by next
743 * call to #GNUNET_i2s().
746 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
751 * Convert a peer identity to a string (for printing debug messages).
752 * This is one of the very few calls in the entire API that is
755 * @param pid the peer identity
756 * @return string form of the pid; will be overwritten by next
757 * call to #GNUNET_i2s_full().
760 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
765 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
766 * (for printing debug messages). This is one of the very few calls
767 * in the entire API that is NOT reentrant!
769 * @param addr the address
770 * @param addrlen the length of the @a addr
771 * @return nicely formatted string for the address
772 * will be overwritten by next call to #GNUNET_a2s().
775 GNUNET_a2s (const struct sockaddr *addr,
781 * Convert error type to string.
783 * @param kind type to convert
784 * @return string corresponding to the type
787 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
792 * Use this for fatal errors that cannot be handled
794 #define GNUNET_assert(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d. Aborting.\n"), __FILE__, __LINE__); GNUNET_abort_(); } } while(0)
799 * Use this for fatal errors that cannot be handled
801 #define GNUNET_assert_at(cond, f, l) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d. Aborting.\n"), f, l); GNUNET_abort_(); } } while(0)
806 * Use this for fatal errors that cannot be handled
808 * @param cond Condition to evaluate
809 * @param comp Component string to use for logging
811 #define GNUNET_assert_from(cond, comp) do { if (! (cond)) { GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, comp, _("Assertion failed at %s:%d. Aborting.\n"), __FILE__, __LINE__); GNUNET_abort_(); } } while(0)
816 * Use this for internal assertion violations that are
817 * not fatal (can be handled) but should not occur.
819 #define GNUNET_break(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
824 * Use this for assertion violations caused by other
825 * peers (i.e. protocol violations). We do not want to
826 * confuse end-users (say, some other peer runs an
827 * older, broken or incompatible GNUnet version), but
828 * we still want to see these problems during
829 * development and testing. "OP == other peer".
831 #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)
836 * Log an error message at log-level 'level' that indicates
837 * a failure of the command 'cmd' with the message given
838 * by strerror(errno).
840 #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)
845 * Log an error message at log-level 'level' that indicates
846 * a failure of the command 'cmd' with the message given
847 * by strerror(errno).
849 #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)
854 * Log an error message at log-level 'level' that indicates
855 * a failure of the command 'cmd' with the message given
856 * by strerror(errno).
858 #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)
863 * Log an error message at log-level 'level' that indicates
864 * a failure of the command 'cmd' with the message given
865 * by strerror(errno).
867 #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)
869 /* ************************* endianess conversion ****************** */
872 * Convert unsigned 64-bit integer to network byte order.
875 * The value in host byte order.
877 * @return The same value in network byte order.
880 GNUNET_htonll (uint64_t n);
884 * Convert unsigned 64-bit integer to host byte order.
887 * The value in network byte order.
889 * @return The same value in host byte order.
892 GNUNET_ntohll (uint64_t n);
896 * Convert double to network byte order.
899 * The value in host byte order.
901 * @return The same value in network byte order.
904 GNUNET_hton_double (double d);
908 * Convert double to host byte order
911 * The value in network byte order.
913 * @return The same value in host byte order.
916 GNUNET_ntoh_double (double d);
919 /* ************************* allocation functions ****************** */
923 * Maximum allocation with GNUNET_malloc macro.
925 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
929 * Allocate a struct or union of the given @a type.
930 * Wrapper around #GNUNET_malloc that returns a pointer
931 * to the newly created object of the correct type.
933 * @param type name of the struct or union, i.e. pass 'struct Foo'.
935 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
939 * Compare memory in @a a and @a b, where both must be of
940 * the same pointer type.
942 #define GNUNET_memcmp(a,b) ({ \
943 const typeof(*b) * _a = (a); \
944 const typeof(*a) * _b = (b); \
951 * Check that memory in @a a is all zeros. @a a must be a pointer.
953 * @param a pointer to a struct which should be tested for the
954 * entire memory being zero'ed out.
956 #define GNUNET_is_zero(a) ({ \
957 static const typeof(*a) _z; \
964 * Call memcpy() but check for @a n being 0 first. In the latter
965 * case, it is now safe to pass NULL for @a src or @a dst.
966 * Unlike traditional memcpy(), returns nothing.
968 * @param dst destination of the copy, may be NULL if @a n is zero
969 * @param src source of the copy, may be NULL if @a n is zero
970 * @param n number of bytes to copy
972 #define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0)
977 * Allocate a size @a n array with structs or unions of the given @a type.
978 * Wrapper around #GNUNET_malloc that returns a pointer
979 * to the newly created objects of the correct type.
981 * @param n number of elements in the array
982 * @param type name of the struct or union, i.e. pass 'struct Foo'.
984 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
988 * Allocate a size @a n times @a m array
989 * with structs or unions of the given @a type.
991 * @param n size of the first dimension
992 * @param m size of the second dimension
993 * @param type name of the struct or union, i.e. pass 'struct Foo'.
995 #define GNUNET_new_array_2d(n, m, type) (type **) GNUNET_xnew_array_2d_ (n, m, sizeof (type), __FILE__, __LINE__)
999 * Allocate a size @a n times @a m times @a o array
1000 * with structs or unions of the given @a type.
1002 * @param n size of the first dimension
1003 * @param m size of the second dimension
1004 * @param o size of the third dimension
1005 * @param type name of the struct or union, i.e. pass 'struct Foo'.
1007 #define GNUNET_new_array_3d(n, m, o, type) (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof (type), __FILE__, __LINE__)
1011 * Wrapper around malloc. Allocates size bytes of memory.
1012 * The memory will be zero'ed out.
1014 * @param size the number of bytes to allocate, must be
1015 * smaller than 40 MB.
1016 * @return pointer to size bytes of memory, never NULL (!)
1018 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
1022 * Allocate and initialize a block of memory.
1024 * @param buf data to initalize the block with
1025 * @param size the number of bytes in buf (and size of the allocation)
1026 * @return pointer to size bytes of memory, never NULL (!)
1028 #define GNUNET_memdup(buf,size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__)
1032 * Wrapper around malloc. Allocates size bytes of memory.
1033 * The memory will be zero'ed out.
1035 * @param size the number of bytes to allocate
1036 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1038 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
1042 * Wrapper around realloc. Reallocates size bytes of memory.
1043 * The content of the intersection of the new and old size will be unchanged.
1045 * @param ptr the pointer to reallocate
1046 * @param size the number of bytes to reallocate
1047 * @return pointer to size bytes of memory
1049 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
1053 * Wrapper around free. Frees the memory referred to by ptr.
1054 * Note that it is generally better to free memory that was
1055 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1057 * @param ptr location where to free the memory. ptr must have
1058 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1060 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
1064 * Free the memory pointed to by ptr if ptr is not NULL.
1065 * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1067 * @param ptr the location in memory to free
1069 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
1073 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string
1076 * @param a pointer to a zero-terminated string
1077 * @return a copy of the string including zero-termination
1079 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
1083 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string
1086 * @param a pointer to a string
1087 * @param length of the string to duplicate
1088 * @return a partial copy of the string including zero-termination
1090 #define GNUNET_strndup(a,length) GNUNET_xstrndup_(a,length,__FILE__,__LINE__)
1094 * Grow a well-typed (!) array. This is a convenience
1095 * method to grow a vector @a arr of size @a size
1096 * to the new (target) size @a tsize.
1099 * Example (simple, well-typed stack):
1102 * static struct foo * myVector = NULL;
1103 * static int myVecLen = 0;
1105 * static void push(struct foo * elem) {
1106 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1107 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1110 * static void pop(struct foo * elem) {
1111 * if (myVecLen == 0) die();
1112 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1113 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1117 * @param arr base-pointer of the vector, may be NULL if size is 0;
1118 * will be updated to reflect the new address. The TYPE of
1119 * arr is important since size is the number of elements and
1120 * not the size in bytes
1121 * @param size the number of elements in the existing vector (number
1122 * of elements to copy over), will be updated with the new
1124 * @param tsize the target size for the resulting vector, use 0 to
1125 * free the vector (then, arr will be NULL afterwards).
1127 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&(arr), sizeof((arr)[0]), &size, tsize, __FILE__, __LINE__)
1131 * Append an element to a list (growing the list by one).
1133 * @param arr base-pointer of the vector, may be NULL if size is 0;
1134 * will be updated to reflect the new address. The TYPE of
1135 * arr is important since size is the number of elements and
1136 * not the size in bytes
1137 * @param size the number of elements in the existing vector (number
1138 * of elements to copy over), will be updated with the new
1140 * @param element the element that will be appended to the array
1142 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); (arr)[size-1] = element; } while(0)
1146 * Like snprintf, just aborts if the buffer is of insufficient size.
1148 * @param buf pointer to buffer that is written to
1149 * @param size number of bytes in @a buf
1150 * @param format format strings
1151 * @param ... data for format string
1152 * @return number of bytes written to buf or negative value on error
1155 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1160 * Like asprintf, just portable.
1162 * @param buf set to a buffer of sufficient size (allocated, caller must free)
1163 * @param format format string (see printf, fprintf, etc.)
1164 * @param ... data for format string
1165 * @return number of bytes in "*buf" excluding 0-termination
1168 GNUNET_asprintf (char **buf, const char *format, ...);
1171 /* ************** internal implementations, use macros above! ************** */
1174 * Allocate memory. Checks the return value, aborts if no more
1175 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the
1176 * #GNUNET_malloc macro.
1177 * The memory will be zero'ed out.
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_xmalloc_ (size_t size, const char *filename, int linenumber);
1189 * Allocate memory for a two dimensional array in one block
1190 * and set up pointers. Aborts if no more memory is available.
1191 * Don't use GNUNET_xnew_array_2d_ directly. Use the
1192 * #GNUNET_new_array_2d macro.
1193 * The memory of the elements will be zero'ed out.
1195 * @param n size of the first dimension
1196 * @param m size of the second dimension
1197 * @param elementSize size of a single element in bytes
1198 * @param filename where is this call being made (for debugging)
1199 * @param linenumber line where this call is being made (for debugging)
1200 * @return allocated memory, never NULL
1203 GNUNET_xnew_array_2d_ (size_t n, size_t m, size_t elementSize,
1204 const char *filename, int linenumber);
1208 * Allocate memory for a three dimensional array in one block
1209 * and set up pointers. Aborts if no more memory is available.
1210 * Don't use GNUNET_xnew_array_3d_ directly. Use the
1211 * #GNUNET_new_array_3d macro.
1212 * The memory of the elements will be zero'ed out.
1214 * @param n size of the first dimension
1215 * @param m size of the second dimension
1216 * @param o size of the third dimension
1217 * @param elementSize size of a single element in bytes
1218 * @param filename where is this call being made (for debugging)
1219 * @param linenumber line where this call is being made (for debugging)
1220 * @return allocated memory, never NULL
1223 GNUNET_xnew_array_3d_ (size_t n, size_t m, size_t o, size_t elementSize,
1224 const char *filename, int linenumber);
1228 * Allocate and initialize memory. Checks the return value, aborts if no more
1229 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the
1230 * #GNUNET_memdup macro.
1232 * @param buf buffer to initialize from (must contain size bytes)
1233 * @param size number of bytes to allocate
1234 * @param filename where is this call being made (for debugging)
1235 * @param linenumber line where this call is being made (for debugging)
1236 * @return allocated memory, never NULL
1239 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
1244 * Allocate memory. This function does not check if the allocation
1245 * request is within reasonable bounds, allowing allocations larger
1246 * than 40 MB. If you don't expect the possibility of very large
1247 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed
1250 * @param size number of bytes to allocate
1251 * @param filename where is this call being made (for debugging)
1252 * @param linenumber line where this call is being made (for debugging)
1253 * @return pointer to size bytes of memory, NULL if we do not have enough memory
1256 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1260 * Reallocate memory. Checks the return value, aborts if no more
1261 * memory is available.
1264 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1268 * Free memory. Merely a wrapper for the case that we
1269 * want to keep track of allocations. Don't use GNUNET_xfree_
1270 * directly. Use the #GNUNET_free macro.
1272 * @param ptr pointer to memory to free
1273 * @param filename where is this call being made (for debugging)
1274 * @param linenumber line where this call is being made (for debugging)
1277 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1281 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1282 * @param str string to duplicate
1283 * @param filename where is this call being made (for debugging)
1284 * @param linenumber line where this call is being made (for debugging)
1285 * @return the duplicated string
1288 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1291 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1293 * @param str string to duplicate
1294 * @param len length of the string to duplicate
1295 * @param filename where is this call being made (for debugging)
1296 * @param linenumber line where this call is being made (for debugging)
1297 * @return the duplicated string
1300 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
1304 * Grow an array, the new elements are zeroed out.
1305 * Grows old by (*oldCount-newCount)*elementSize
1306 * bytes and sets *oldCount to newCount.
1308 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1310 * @param old address of the pointer to the array
1312 * @param elementSize the size of the elements of the array
1313 * @param oldCount address of the number of elements in the *old array
1314 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1315 * @param filename where is this call being made (for debugging)
1316 * @param linenumber line where this call is being made (for debugging)
1319 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
1320 unsigned int newCount, const char *filename, int linenumber);
1325 * Create a copy of the given message.
1327 * @param msg message to copy
1328 * @return duplicate of the message
1330 struct GNUNET_MessageHeader *
1331 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1334 #if __STDC_VERSION__ < 199901L
1336 #define __func__ __FUNCTION__
1338 #define __func__ "<unknown>"
1344 * Valid task priorities. Use these, do not pass random integers!
1345 * For various reasons (#3862 -- building with QT Creator, and
1346 * our restricted cross-compilation with emscripten) this cannot
1347 * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1348 * Naturally, logically this is part of the scheduler.
1350 enum GNUNET_SCHEDULER_Priority
1353 * Run with the same priority as the current job.
1355 GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1358 * Run when otherwise idle.
1360 GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1363 * Run as background job (higher than idle,
1364 * lower than default).
1366 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1369 * Run with the default priority (normal
1370 * P2P operations). Any task that is scheduled
1371 * without an explicit priority being specified
1372 * will run with this priority.
1374 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1377 * Run with high priority (important requests).
1378 * Higher than DEFAULT.
1380 GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1383 * Run with priority for interactive tasks.
1384 * Higher than "HIGH".
1386 GNUNET_SCHEDULER_PRIORITY_UI = 5,
1389 * Run with priority for urgent tasks. Use
1390 * for things like aborts and shutdowns that
1391 * need to preempt "UI"-level tasks.
1394 GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1397 * This is an internal priority level that is only used for tasks
1398 * that are being triggered due to shutdown (they have automatically
1399 * highest priority). User code must not use this priority level
1400 * directly. Tasks run with this priority level that internally
1401 * schedule other tasks will see their original priority level
1402 * be inherited (unless otherwise specified).
1404 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1407 * Number of priorities (must be the last priority).
1408 * This priority must not be used by clients.
1410 GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1414 #if 0 /* keep Emacsens' auto-indent happy */
1421 #endif /* GNUNET_COMMON_H */