first step to remove plibc
[oweals/gnunet.git] / src / include / gnunet_common.h
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2006-2013 GNUnet e.V.
4
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.
9
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.
14
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/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21 /**
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.
26  *
27  * @author Christian Grothoff
28  * @author Nils Durner
29  * @author Martin Schanzenbach
30  *
31  * @defgroup logging Logging
32  * @see [Documentation](https://gnunet.org/logging)
33  *
34  * @defgroup memory Memory management
35  */
36 #ifndef GNUNET_COMMON_H
37 #define GNUNET_COMMON_H
38
39 #if HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
42 #if HAVE_NETINET_IN_H
43 #include <netinet/in.h>
44 #endif
45 #ifdef MINGW
46 #include "winproc.h"
47 #endif
48 #ifdef HAVE_STDINT_H
49 #include <stdint.h>
50 #endif
51 #ifdef HAVE_STDARG_H
52 #include <stdarg.h>
53 #endif
54
55 #ifdef HAVE_BYTESWAP_H
56 #include <byteswap.h>
57 #endif
58
59 #ifdef __cplusplus
60 extern "C" {
61 #if 0 /* keep Emacsens' auto-indent happy */
62 }
63 #endif
64 #endif
65
66 /**
67  * Version of the API (for entire gnunetutil.so library).
68  */
69 #define GNUNET_UTIL_VERSION 0x000A0103
70
71
72 /**
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`.
77  */
78 #define GNUNET_OK 1
79 #define GNUNET_SYSERR -1
80 #define GNUNET_YES 1
81 #define GNUNET_NO 0
82
83 #define GNUNET_MIN(a, b) (((a) < (b)) ? (a) : (b))
84
85 #define GNUNET_MAX(a, b) (((a) > (b)) ? (a) : (b))
86
87 /* some systems use one underscore only, and mingw uses no underscore... */
88 #ifndef __BYTE_ORDER
89 #ifdef _BYTE_ORDER
90 #define __BYTE_ORDER _BYTE_ORDER
91 #else
92 #ifdef BYTE_ORDER
93 #define __BYTE_ORDER BYTE_ORDER
94 #endif
95 #endif
96 #endif
97 #ifndef __BIG_ENDIAN
98 #ifdef _BIG_ENDIAN
99 #define __BIG_ENDIAN _BIG_ENDIAN
100 #else
101 #ifdef BIG_ENDIAN
102 #define __BIG_ENDIAN BIG_ENDIAN
103 #endif
104 #endif
105 #endif
106 #ifndef __LITTLE_ENDIAN
107 #ifdef _LITTLE_ENDIAN
108 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
109 #else
110 #ifdef LITTLE_ENDIAN
111 #define __LITTLE_ENDIAN LITTLE_ENDIAN
112 #endif
113 #endif
114 #endif
115
116 /**
117  * wrap va_arg for enums
118  */
119 #define GNUNET_VA_ARG_ENUM(va, X) ((enum X) va_arg (va, int))
120
121
122 /**
123  * @ingroup logging
124  * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
125  * tree where gnunet_config.h is unavailable
126  */
127 #ifndef GNUNET_EXTRA_LOGGING
128 #define GNUNET_EXTRA_LOGGING 0
129 #endif
130
131 /**
132  * Endian operations
133  */
134
135 #if __BYTE_ORDER == __LITTLE_ENDIAN
136 #define GNUNET_htobe16(x) __bswap_16 (x)
137 #define GNUNET_htole16(x) (x)
138 #define GNUNET_be16toh(x) __bswap_16 (x)
139 #define GNUNET_le16toh(x) (x)
140
141 #define GNUNET_htobe32(x) __bswap_32 (x)
142 #define GNUNET_htole32(x) (x)
143 #define GNUNET_be32toh(x) __bswap_32 (x)
144 #define GNUNET_le32toh(x) (x)
145
146 #define GNUNET_htobe64(x) __bswap_64 (x)
147 #define GNUNET_htole64(x) (x)
148 #define GNUNET_be64toh(x) __bswap_64 (x)
149 #define GNUNET_le64toh(x) (x)
150 #endif
151 #if __BYTE_ORDER == __BIG_ENDIAN
152 #define GNUNET_htobe16(x) (x)
153 #define GNUNET_htole16(x) __bswap_16 (x)
154 #define GNUNET_be16toh(x) (x)
155 #define GNUNET_le16toh(x) __bswap_16 (x)
156
157 #define GNUNET_htobe32(x) (x)
158 #define GNUNET_htole32(x) __bswap_32 (x)
159 #define GNUNET_be32toh(x) (x)
160 #define GNUNET_le32toh(x) __bswap_32 (x)
161
162 #define GNUNET_htobe64(x) (x)
163 #define GNUNET_htole64(x) __bswap_64 (x)
164 #define GNUNET_be64toh(x) (x)
165 #define GNUNET_le64toh(x) __bswap_64 (x)
166 #endif
167
168
169 /**
170  * Macro used to avoid using 0 for the length of a variable-size
171  * array (Non-Zero-Length).
172  *
173  * Basically, C standard says that "int[n] x;" is undefined if n=0.
174  * This was supposed to prevent issues with pointer aliasing.
175  * However, C compilers may conclude that n!=0 as n=0 would be
176  * undefined, and then optimize under the assumption n!=0, which
177  * could cause actual issues.  Hence, when initializing an array
178  * on the stack with a variable-length that might be zero, write
179  * "int[GNUNET_NZL(n)] x;" instead of "int[n] x".
180  */
181 #define GNUNET_NZL(l) GNUNET_MAX (1, l)
182
183
184 /**
185  * gcc-ism to get packed structs.
186  */
187 #define GNUNET_PACKED __attribute__ ((packed))
188
189 /**
190  * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
191  */
192 #if MINGW
193 #define GNUNET_GCC_STRUCT_LAYOUT __attribute__ ((gcc_struct))
194 #else
195 #define GNUNET_GCC_STRUCT_LAYOUT
196 #endif
197
198 /**
199  * gcc-ism to force alignment; we use this to align char-arrays
200  * that may then be cast to 'struct's.  See also gcc
201  * bug #33594.
202  */
203 #ifdef __BIGGEST_ALIGNMENT__
204 #define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__)))
205 #else
206 #define GNUNET_ALIGN __attribute__ ((aligned (8)))
207 #endif
208
209 /**
210  * gcc-ism to document unused arguments
211  */
212 #define GNUNET_UNUSED __attribute__ ((unused))
213
214 /**
215  * gcc-ism to document functions that don't return
216  */
217 #define GNUNET_NORETURN __attribute__ ((noreturn))
218
219 #if MINGW
220 #if __GNUC__ > 3
221 /**
222  * gcc 4.x-ism to pack structures even on W32 (to be used before structs);
223  * Using this would cause structs to be unaligned on the stack on Sparc,
224  * so we *only* use this on W32 (see #670578 from Debian); fortunately,
225  * W32 doesn't run on sparc anyway.
226  */
227 #define GNUNET_NETWORK_STRUCT_BEGIN _Pragma ("pack(push)") _Pragma ("pack(1)")
228
229 /**
230  * gcc 4.x-ism to pack structures even on W32 (to be used after structs)
231  * Using this would cause structs to be unaligned on the stack on Sparc,
232  * so we *only* use this on W32 (see #670578 from Debian); fortunately,
233  * W32 doesn't run on sparc anyway.
234  */
235 #define GNUNET_NETWORK_STRUCT_END _Pragma ("pack(pop)")
236
237 #else
238 #error gcc 4.x or higher required on W32 systems
239 #endif
240 #else
241 /**
242  * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
243  */
244 #define GNUNET_NETWORK_STRUCT_BEGIN
245
246 /**
247  * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
248  */
249 #define GNUNET_NETWORK_STRUCT_END
250 #endif
251
252 /* ************************ super-general types *********************** */
253
254 GNUNET_NETWORK_STRUCT_BEGIN
255
256 /**
257  * @brief A 512-bit hashcode.  These are the default length for GNUnet, using SHA-512.
258  */
259 struct GNUNET_HashCode
260 {
261   uint32_t bits[512 / 8 / sizeof (uint32_t)]; /* = 16 */
262 };
263
264
265 /**
266  * @brief A 256-bit hashcode.  Used under special conditions, like when space
267  * is critical and security is not impacted by it.
268  */
269 struct GNUNET_ShortHashCode
270 {
271   uint32_t bits[256 / 8 / sizeof (uint32_t)]; /* = 8 */
272 };
273
274
275 /**
276  * A UUID, a 128 bit random value.
277  */
278 struct GNUNET_Uuid
279 {
280   /**
281    * 128 random bits.
282    */
283   uint32_t value[4];
284 };
285
286
287 /**
288  * Header for all communications.
289  */
290 struct GNUNET_MessageHeader
291 {
292
293   /**
294    * The length of the struct (in bytes, including the length field itself),
295    * in big-endian format.
296    */
297   uint16_t size GNUNET_PACKED;
298
299   /**
300    * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
301    */
302   uint16_t type GNUNET_PACKED;
303 };
304
305
306 /**
307  * Answer from service to client about last operation.
308  */
309 struct GNUNET_OperationResultMessage
310 {
311   struct GNUNET_MessageHeader header;
312
313   uint32_t reserved GNUNET_PACKED;
314
315   /**
316    * Operation ID.
317    */
318   uint64_t op_id GNUNET_PACKED;
319
320   /**
321    * Status code for the operation.
322    */
323   uint64_t result_code GNUNET_PACKED;
324
325   /* Followed by data. */
326 };
327
328
329 /**
330  * Identifier for an asynchronous execution context.
331  */
332 struct GNUNET_AsyncScopeId
333 {
334   uint32_t bits[16 / sizeof (uint32_t)]; /* = 16 bytes */
335 };
336
337 GNUNET_NETWORK_STRUCT_END
338
339
340 /**
341  * Saved async scope identifier or root scope.
342  */
343 struct GNUNET_AsyncScopeSave
344 {
345   /**
346    * Saved scope.  Unused if 'have_scope==GNUNET_NO'.
347    */
348   struct GNUNET_AsyncScopeId scope_id;
349
350   /**
351    * GNUNET_YES unless this saved scope is the unnamed root scope.
352    */
353   int have_scope;
354 };
355
356
357 /**
358  * Function called with a filename.
359  *
360  * @param cls closure
361  * @param filename complete filename (absolute path)
362  * @return #GNUNET_OK to continue to iterate,
363  *  #GNUNET_NO to stop iteration with no error,
364  *  #GNUNET_SYSERR to abort iteration with error!
365  */
366 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
367
368
369 /**
370  * Generic continuation callback.
371  *
372  * @param cls  Closure.
373  */
374 typedef void (*GNUNET_ContinuationCallback) (void *cls);
375
376
377 /**
378  * Function called with the result of an asynchronous operation.
379  *
380  * @param cls
381  *        Closure.
382  * @param result_code
383  *        Result code for the operation.
384  * @param data
385  *        Data result for the operation.
386  * @param data_size
387  *        Size of @a data.
388  */
389 typedef void (*GNUNET_ResultCallback) (void *cls,
390                                        int64_t result_code,
391                                        const void *data,
392                                        uint16_t data_size);
393
394
395 /* ****************************** logging ***************************** */
396
397 /**
398  * @ingroup logging
399  * Types of errors.
400  */
401 enum GNUNET_ErrorType
402 {
403   GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
404   GNUNET_ERROR_TYPE_NONE = 0,
405   GNUNET_ERROR_TYPE_ERROR = 1,
406   GNUNET_ERROR_TYPE_WARNING = 2,
407   /* UX: We need a message type that is output by
408    * default without looking like there is a problem.
409    */
410   GNUNET_ERROR_TYPE_MESSAGE = 4,
411   GNUNET_ERROR_TYPE_INFO = 8,
412   GNUNET_ERROR_TYPE_DEBUG = 16,
413   GNUNET_ERROR_TYPE_INVALID = 32,
414   GNUNET_ERROR_TYPE_BULK = 64
415 };
416
417
418 /**
419  * @ingroup logging
420  * User-defined handler for log messages.
421  *
422  * @param cls closure
423  * @param kind severeity
424  * @param component what component is issuing the message?
425  * @param date when was the message logged?
426  * @param message what is the message
427  */
428 typedef void (*GNUNET_Logger) (void *cls,
429                                enum GNUNET_ErrorType kind,
430                                const char *component,
431                                const char *date,
432                                const char *message);
433
434
435 /**
436  * @ingroup logging
437  * Get the number of log calls that are going to be skipped
438  *
439  * @return number of log calls to be ignored
440  */
441 int
442 GNUNET_get_log_skip (void);
443
444
445 #if ! defined(GNUNET_CULL_LOGGING)
446 int
447 GNUNET_get_log_call_status (int caller_level,
448                             const char *comp,
449                             const char *file,
450                             const char *function,
451                             int line);
452 #endif
453
454
455 /**
456  * @ingroup logging
457  * Main log function.
458  *
459  * @param kind how serious is the error?
460  * @param message what is the message (format string)
461  * @param ... arguments for format string
462  */
463 void
464 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
465   __attribute__ ((format (printf, 2, 3)));
466
467 /* from glib */
468 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
469 #define _GNUNET_BOOLEAN_EXPR(expr) \
470   __extension__({                  \
471     int _gnunet_boolean_var_;      \
472     if (expr)                      \
473       _gnunet_boolean_var_ = 1;    \
474     else                           \
475       _gnunet_boolean_var_ = 0;    \
476     _gnunet_boolean_var_;          \
477   })
478 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1))
479 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0))
480 #else
481 #define GN_LIKELY(expr) (expr)
482 #define GN_UNLIKELY(expr) (expr)
483 #endif
484
485 #if ! defined(GNUNET_LOG_CALL_STATUS)
486 #define GNUNET_LOG_CALL_STATUS -1
487 #endif
488
489
490 /**
491  * @ingroup logging
492  * Log function that specifies an alternative component.
493  * This function should be used by plugins.
494  *
495  * @param kind how serious is the error?
496  * @param comp component responsible for generating the message
497  * @param message what is the message (format string)
498  * @param ... arguments for format string
499  */
500 void
501 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
502                          const char *comp,
503                          const char *message,
504                          ...);
505
506 #if ! defined(GNUNET_CULL_LOGGING)
507 #define GNUNET_log_from(kind, comp, ...)                                  \
508   do                                                                      \
509   {                                                                       \
510     static int log_call_enabled = GNUNET_LOG_CALL_STATUS;                 \
511     if ((GNUNET_EXTRA_LOGGING > 0) ||                                     \
512         ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0))                        \
513     {                                                                     \
514       if (GN_UNLIKELY (log_call_enabled == -1))                           \
515         log_call_enabled =                                                \
516           GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
517                                       (comp),                             \
518                                       __FILE__,                           \
519                                       __FUNCTION__,                       \
520                                       __LINE__);                          \
521       if (GN_UNLIKELY (GNUNET_get_log_skip () > 0))                       \
522       {                                                                   \
523         GNUNET_log_skip (-1, GNUNET_NO);                                  \
524       }                                                                   \
525       else                                                                \
526       {                                                                   \
527         if (GN_UNLIKELY (log_call_enabled))                               \
528           GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__);            \
529       }                                                                   \
530     }                                                                     \
531   } while (0)
532
533 #define GNUNET_log(kind, ...)                                             \
534   do                                                                      \
535   {                                                                       \
536     static int log_call_enabled = GNUNET_LOG_CALL_STATUS;                 \
537     if ((GNUNET_EXTRA_LOGGING > 0) ||                                     \
538         ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0))                        \
539     {                                                                     \
540       if (GN_UNLIKELY (log_call_enabled == -1))                           \
541         log_call_enabled =                                                \
542           GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \
543                                       NULL,                               \
544                                       __FILE__,                           \
545                                       __FUNCTION__,                       \
546                                       __LINE__);                          \
547       if (GN_UNLIKELY (GNUNET_get_log_skip () > 0))                       \
548       {                                                                   \
549         GNUNET_log_skip (-1, GNUNET_NO);                                  \
550       }                                                                   \
551       else                                                                \
552       {                                                                   \
553         if (GN_UNLIKELY (log_call_enabled))                               \
554           GNUNET_log_nocheck ((kind), __VA_ARGS__);                       \
555       }                                                                   \
556     }                                                                     \
557   } while (0)
558 #else
559 #define GNUNET_log(...)
560 #define GNUNET_log_from(...)
561 #endif
562
563
564 /**
565  * @ingroup logging
566  * Log error message about missing configuration option.
567  *
568  * @param kind log level
569  * @param section section with missing option
570  * @param option name of missing option
571  */
572 void
573 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
574                            const char *section,
575                            const char *option);
576
577
578 /**
579  * @ingroup logging
580  * Log error message about invalid configuration option value.
581  *
582  * @param kind log level
583  * @param section section with invalid option
584  * @param option name of invalid option
585  * @param required what is required that is invalid about the option
586  */
587 void
588 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
589                            const char *section,
590                            const char *option,
591                            const char *required);
592
593
594 /**
595  * @ingroup logging
596  * Abort the process, generate a core dump if possible.
597  * Most code should use `GNUNET_assert (0)` instead to
598  * first log the location of the failure.
599  */
600 void
601 GNUNET_abort_ (void) GNUNET_NORETURN;
602
603
604 /**
605  * @ingroup logging
606  * Ignore the next @a n calls to the log function.
607  *
608  * @param n number of log calls to ignore (could be negative)
609  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
610  */
611 void
612 GNUNET_log_skip (int n, int check_reset);
613
614
615 /**
616  * @ingroup logging
617  * Setup logging.
618  *
619  * @param comp default component to use
620  * @param loglevel what types of messages should be logged
621  * @param logfile change logging to logfile (use NULL to keep stderr)
622  * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
623  */
624 int
625 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile);
626
627
628 /**
629  * @ingroup logging
630  * Add a custom logger.  Note that installing any custom logger
631  * will disable the standard logger.  When multiple custom loggers
632  * are installed, all will be called.  The standard logger will
633  * only be used if no custom loggers are present.
634  *
635  * @param logger log function
636  * @param logger_cls closure for @a logger
637  */
638 void
639 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
640
641
642 /**
643  * @ingroup logging
644  * Remove a custom logger.
645  *
646  * @param logger log function
647  * @param logger_cls closure for @a logger
648  */
649 void
650 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
651
652
653 /**
654  * @ingroup logging
655  * Convert a short hash value to a string (for printing debug messages).
656  * This is one of the very few calls in the entire API that is
657  * NOT reentrant!
658  *
659  * @param shc the hash code
660  * @return string
661  */
662 const char *
663 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc);
664
665
666 /**
667  * @ingroup logging
668  * Convert a UUID to a string (for printing debug messages).
669  * This is one of the very few calls in the entire API that is
670  * NOT reentrant!
671  *
672  * @param uuid the UUID
673  * @return string
674  */
675 const char *
676 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid);
677
678
679 /**
680  * @ingroup logging
681  * Convert a hash value to a string (for printing debug messages).
682  * This is one of the very few calls in the entire API that is
683  * NOT reentrant!
684  *
685  * @param hc the hash code
686  * @return string
687  */
688 const char *
689 GNUNET_h2s (const struct GNUNET_HashCode *hc);
690
691
692 /**
693  * @ingroup logging
694  * Convert a hash value to a string (for printing debug messages).
695  * This is one of the very few calls in the entire API that is
696  * NOT reentrant! Identical to #GNUNET_h2s(), except that another
697  * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
698  * used within the same log statement.
699  *
700  * @param hc the hash code
701  * @return string
702  */
703 const char *
704 GNUNET_h2s2 (const struct GNUNET_HashCode *hc);
705
706
707 /**
708  * @ingroup logging
709  * Convert a hash value to a string (for printing debug messages).
710  * This prints all 104 characters of a hashcode!
711  * This is one of the very few calls in the entire API that is
712  * NOT reentrant!
713  *
714  * @param hc the hash code
715  * @return string
716  */
717 const char *
718 GNUNET_h2s_full (const struct GNUNET_HashCode *hc);
719
720
721 /**
722  * Public key. Details in gnunet_util_crypto.h.
723  */
724 struct GNUNET_CRYPTO_EddsaPublicKey;
725
726
727 /**
728  * Public key. Details in gnunet_util_crypto.h.
729  */
730 struct GNUNET_CRYPTO_EcdhePublicKey;
731
732
733 /**
734  * @ingroup logging
735  * Convert a public key value to a string (for printing debug messages).
736  * This is one of the very few calls in the entire API that is
737  * NOT reentrant!
738  *
739  * @param hc the hash code
740  * @return string
741  */
742 const char *
743 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
744
745
746 /**
747  * @ingroup logging
748  * Convert a public key value to a string (for printing debug messages).
749  * This is one of the very few calls in the entire API that is
750  * NOT reentrant!
751  *
752  * @param hc the hash code
753  * @return string
754  */
755 const char *
756 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p);
757
758
759 /**
760  * @ingroup logging
761  * Convert a public key value to a string (for printing debug messages).
762  * This is one of the very few calls in the entire API that is
763  * NOT reentrant!
764  *
765  * @param hc the hash code
766  * @return string
767  */
768 const char *
769 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
770
771
772 /**
773  * @ingroup logging
774  * Convert a public key value to a string (for printing debug messages).
775  * This is one of the very few calls in the entire API that is
776  * NOT reentrant!
777  *
778  * @param hc the hash code
779  * @return string
780  */
781 const char *
782 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p);
783
784
785 /**
786  * @ingroup logging
787  * Convert a peer identity to a string (for printing debug messages).
788  * This is one of the very few calls in the entire API that is
789  * NOT reentrant!
790  *
791  * @param pid the peer identity
792  * @return string form of the pid; will be overwritten by next
793  *         call to #GNUNET_i2s().
794  */
795 const char *
796 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
797
798
799 /**
800  * @ingroup logging
801  * Convert a peer identity to a string (for printing debug messages).
802  * This is one of the very few calls in the entire API that is
803  * NOT reentrant!  Identical to #GNUNET_i2s(), except that another
804  * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
805  * used within the same log statement.
806  *
807  * @param pid the peer identity
808  * @return string form of the pid; will be overwritten by next
809  *         call to #GNUNET_i2s().
810  */
811 const char *
812 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid);
813
814
815 /**
816  * @ingroup logging
817  * Convert a peer identity to a string (for printing debug messages).
818  * This is one of the very few calls in the entire API that is
819  * NOT reentrant!
820  *
821  * @param pid the peer identity
822  * @return string form of the pid; will be overwritten by next
823  *         call to #GNUNET_i2s_full().
824  */
825 const char *
826 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
827
828
829 /**
830  * @ingroup logging
831  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
832  * (for printing debug messages).  This is one of the very few calls
833  * in the entire API that is NOT reentrant!
834  *
835  * @param addr the address
836  * @param addrlen the length of the @a addr
837  * @return nicely formatted string for the address
838  *  will be overwritten by next call to #GNUNET_a2s().
839  */
840 const char *
841 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen);
842
843
844 /**
845  * @ingroup logging
846  * Convert error type to string.
847  *
848  * @param kind type to convert
849  * @return string corresponding to the type
850  */
851 const char *
852 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
853
854
855 /**
856  * @ingroup logging
857  * Use this for fatal errors that cannot be handled
858  */
859 #define GNUNET_assert(cond)                                     \
860   do                                                            \
861   {                                                             \
862     if (! (cond))                                               \
863     {                                                           \
864       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,                      \
865                   _ ("Assertion failed at %s:%d. Aborting.\n"), \
866                   __FILE__,                                     \
867                   __LINE__);                                    \
868       GNUNET_abort_ ();                                         \
869     }                                                           \
870   } while (0)
871
872
873 /**
874  * @ingroup logging
875  * Use this for fatal errors that cannot be handled
876  */
877 #define GNUNET_assert_at(cond, f, l)                            \
878   do                                                            \
879   {                                                             \
880     if (! (cond))                                               \
881     {                                                           \
882       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,                      \
883                   _ ("Assertion failed at %s:%d. Aborting.\n"), \
884                   f,                                            \
885                   l);                                           \
886       GNUNET_abort_ ();                                         \
887     }                                                           \
888   } while (0)
889
890
891 /**
892  * @ingroup logging
893  * Use this for fatal errors that cannot be handled
894  *
895  * @param cond Condition to evaluate
896  * @param comp Component string to use for logging
897  */
898 #define GNUNET_assert_from(cond, comp)                               \
899   do                                                                 \
900   {                                                                  \
901     if (! (cond))                                                    \
902     {                                                                \
903       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,                      \
904                        comp,                                         \
905                        _ ("Assertion failed at %s:%d. Aborting.\n"), \
906                        __FILE__,                                     \
907                        __LINE__);                                    \
908       GNUNET_abort_ ();                                              \
909     }                                                                \
910   } while (0)
911
912
913 /**
914  * @ingroup logging
915  * Use this for internal assertion violations that are
916  * not fatal (can be handled) but should not occur.
917  */
918 #define GNUNET_break(cond)                            \
919   do                                                  \
920   {                                                   \
921     if (! (cond))                                     \
922     {                                                 \
923       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,            \
924                   _ ("Assertion failed at %s:%d.\n"), \
925                   __FILE__,                           \
926                   __LINE__);                          \
927     }                                                 \
928   } while (0)
929
930
931 /**
932  * @ingroup logging
933  * Use this for assertion violations caused by other
934  * peers (i.e. protocol violations).  We do not want to
935  * confuse end-users (say, some other peer runs an
936  * older, broken or incompatible GNUnet version), but
937  * we still want to see these problems during
938  * development and testing.  "OP == other peer".
939  */
940 #define GNUNET_break_op(cond)                                             \
941   do                                                                      \
942   {                                                                       \
943     if (! (cond))                                                         \
944     {                                                                     \
945       GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,     \
946                   _ ("External protocol violation detected at %s:%d.\n"), \
947                   __FILE__,                                               \
948                   __LINE__);                                              \
949     }                                                                     \
950   } while (0)
951
952
953 /**
954  * @ingroup logging
955  * Log an error message at log-level 'level' that indicates
956  * a failure of the command 'cmd' with the message given
957  * by strerror(errno).
958  */
959 #define GNUNET_log_strerror(level, cmd)                      \
960   do                                                         \
961   {                                                          \
962     GNUNET_log (level,                                       \
963                 _ ("`%s' failed at %s:%d with error: %s\n"), \
964                 cmd,                                         \
965                 __FILE__,                                    \
966                 __LINE__,                                    \
967                 strerror (errno));                           \
968   } while (0)
969
970
971 /**
972  * @ingroup logging
973  * Log an error message at log-level 'level' that indicates
974  * a failure of the command 'cmd' with the message given
975  * by strerror(errno).
976  */
977 #define GNUNET_log_from_strerror(level, component, cmd)           \
978   do                                                              \
979   {                                                               \
980     GNUNET_log_from (level,                                       \
981                      component,                                   \
982                      _ ("`%s' failed at %s:%d with error: %s\n"), \
983                      cmd,                                         \
984                      __FILE__,                                    \
985                      __LINE__,                                    \
986                      strerror (errno));                           \
987   } while (0)
988
989
990 /**
991  * @ingroup logging
992  * Log an error message at log-level 'level' that indicates
993  * a failure of the command 'cmd' with the message given
994  * by strerror(errno).
995  */
996 #define GNUNET_log_strerror_file(level, cmd, filename)                    \
997   do                                                                      \
998   {                                                                       \
999     GNUNET_log (level,                                                    \
1000                 _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
1001                 cmd,                                                      \
1002                 filename,                                                 \
1003                 __FILE__,                                                 \
1004                 __LINE__,                                                 \
1005                 strerror (errno));                                        \
1006   } while (0)
1007
1008
1009 /**
1010  * @ingroup logging
1011  * Log an error message at log-level 'level' that indicates
1012  * a failure of the command 'cmd' with the message given
1013  * by strerror(errno).
1014  */
1015 #define GNUNET_log_from_strerror_file(level, component, cmd, filename)         \
1016   do                                                                           \
1017   {                                                                            \
1018     GNUNET_log_from (level,                                                    \
1019                      component,                                                \
1020                      _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \
1021                      cmd,                                                      \
1022                      filename,                                                 \
1023                      __FILE__,                                                 \
1024                      __LINE__,                                                 \
1025                      strerror (errno));                                        \
1026   } while (0)
1027
1028 /* ************************* endianess conversion ****************** */
1029
1030 /**
1031  * Convert unsigned 64-bit integer to network byte order.
1032  *
1033  * @param n
1034  *        The value in host byte order.
1035  *
1036  * @return The same value in network byte order.
1037  */
1038 uint64_t
1039 GNUNET_htonll (uint64_t n);
1040
1041
1042 /**
1043  * Convert unsigned 64-bit integer to host byte order.
1044  *
1045  * @param n
1046  *        The value in network byte order.
1047  *
1048  * @return The same value in host byte order.
1049  */
1050 uint64_t
1051 GNUNET_ntohll (uint64_t n);
1052
1053
1054 /**
1055  * Convert double to network byte order.
1056  *
1057  * @param d
1058  *        The value in host byte order.
1059  *
1060  * @return The same value in network byte order.
1061  */
1062 double
1063 GNUNET_hton_double (double d);
1064
1065
1066 /**
1067  * Convert double to host byte order
1068  *
1069  * @param d
1070  *        The value in network byte order.
1071  *
1072  * @return The same value in host byte order.
1073  */
1074 double
1075 GNUNET_ntoh_double (double d);
1076
1077
1078 /* ************************* allocation functions ****************** */
1079
1080 /**
1081  * @ingroup memory
1082  * Maximum allocation with GNUNET_malloc macro.
1083  */
1084 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
1085
1086 /**
1087  * @ingroup memory
1088  * Allocate a struct or union of the given @a type.
1089  * Wrapper around #GNUNET_malloc that returns a pointer
1090  * to the newly created object of the correct type.
1091  *
1092  * @param type name of the struct or union, i.e. pass 'struct Foo'.
1093  */
1094 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
1095
1096
1097 /**
1098  * Compare memory in @a a and @a b, where both must be of
1099  * the same pointer type.
1100  */
1101 #define GNUNET_memcmp(a, b)       \
1102   ({                              \
1103     const typeof (*b) *_a = (a);  \
1104     const typeof (*a) *_b = (b);  \
1105     memcmp (_a, _b, sizeof (*a)); \
1106   })
1107
1108
1109 /**
1110  * Check that memory in @a a is all zeros. @a a must be a pointer.
1111  *
1112  * @param a pointer to a struct which should be tested for the
1113  *          entire memory being zero'ed out.
1114  */
1115 #define GNUNET_is_zero(a)           \
1116   ({                                \
1117     static const typeof (*a) _z;    \
1118     memcmp ((a), &_z, sizeof (_z)); \
1119   })
1120
1121
1122 /**
1123  * Call memcpy() but check for @a n being 0 first. In the latter
1124  * case, it is now safe to pass NULL for @a src or @a dst.
1125  * Unlike traditional memcpy(), returns nothing.
1126  *
1127  * @param dst destination of the copy, may be NULL if @a n is zero
1128  * @param src source of the copy, may be NULL if @a n is zero
1129  * @param n number of bytes to copy
1130  */
1131 #define GNUNET_memcpy(dst, src, n) \
1132   do                               \
1133   {                                \
1134     if (0 != n)                    \
1135     {                              \
1136       (void) memcpy (dst, src, n); \
1137     }                              \
1138   } while (0)
1139
1140
1141 /**
1142  * @ingroup memory
1143  * Allocate a size @a n array with structs or unions of the given @a type.
1144  * Wrapper around #GNUNET_malloc that returns a pointer
1145  * to the newly created objects of the correct type.
1146  *
1147  * @param n number of elements in the array
1148  * @param type name of the struct or union, i.e. pass 'struct Foo'.
1149  */
1150 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
1151
1152 /**
1153  * @ingroup memory
1154  * Allocate a size @a n times @a m array
1155  * with structs or unions of the given @a type.
1156  *
1157  * @param n size of the first dimension
1158  * @param m size of the second dimension
1159  * @param type name of the struct or union, i.e. pass 'struct Foo'.
1160  */
1161 #define GNUNET_new_array_2d(n, m, type) \
1162   (type **) GNUNET_xnew_array_2d_ (n, m, sizeof (type), __FILE__, __LINE__)
1163
1164 /**
1165  * @ingroup memory
1166  * Allocate a size @a n times @a m times @a o array
1167  * with structs or unions of the given @a type.
1168  *
1169  * @param n size of the first dimension
1170  * @param m size of the second dimension
1171  * @param o size of the third dimension
1172  * @param type name of the struct or union, i.e. pass 'struct Foo'.
1173  */
1174 #define GNUNET_new_array_3d(n, m, o, type) \
1175   (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof (type), __FILE__, __LINE__)
1176
1177 /**
1178  * @ingroup memory
1179  * Wrapper around malloc. Allocates size bytes of memory.
1180  * The memory will be zero'ed out.
1181  *
1182  * @param size the number of bytes to allocate, must be
1183  *        smaller than 40 MB.
1184  * @return pointer to size bytes of memory, never NULL (!)
1185  */
1186 #define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__)
1187
1188 /**
1189  * @ingroup memory
1190  * Allocate and initialize a block of memory.
1191  *
1192  * @param buf data to initalize the block with
1193  * @param size the number of bytes in buf (and size of the allocation)
1194  * @return pointer to size bytes of memory, never NULL (!)
1195  */
1196 #define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__)
1197
1198 /**
1199  * @ingroup memory
1200  * Wrapper around malloc. Allocates size bytes of memory.
1201  * The memory will be zero'ed out.
1202  *
1203  * @param size the number of bytes to allocate
1204  * @return pointer to size bytes of memory, NULL if we do not have enough memory
1205  */
1206 #define GNUNET_malloc_large(size) \
1207   GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__)
1208
1209 /**
1210  * @ingroup memory
1211  * Wrapper around realloc. Reallocates size bytes of memory.
1212  * The content of the intersection of the new and old size will be unchanged.
1213  *
1214  * @param ptr the pointer to reallocate
1215  * @param size the number of bytes to reallocate
1216  * @return pointer to size bytes of memory
1217  */
1218 #define GNUNET_realloc(ptr, size) \
1219   GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__)
1220
1221 /**
1222  * @ingroup memory
1223  * Wrapper around free. Frees the memory referred to by ptr.
1224  * Note that it is generally better to free memory that was
1225  * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
1226  *
1227  * @param ptr location where to free the memory. ptr must have
1228  *     been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
1229  */
1230 #define GNUNET_free(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__)
1231
1232 /**
1233  * @ingroup memory
1234  * Free the memory pointed to by ptr if ptr is not NULL.
1235  * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
1236  *
1237  * @param ptr the location in memory to free
1238  */
1239 #define GNUNET_free_non_null(ptr) \
1240   do                              \
1241   {                               \
1242     void *__x__ = ptr;            \
1243     if (__x__ != NULL)            \
1244     {                             \
1245       GNUNET_free (__x__);        \
1246     }                             \
1247   } while (0)
1248
1249 /**
1250  * @ingroup memory
1251  * Wrapper around #GNUNET_xstrdup_.  Makes a copy of the zero-terminated string
1252  * pointed to by a.
1253  *
1254  * @param a pointer to a zero-terminated string
1255  * @return a copy of the string including zero-termination
1256  */
1257 #define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__)
1258
1259 /**
1260  * @ingroup memory
1261  * Wrapper around #GNUNET_xstrndup_.  Makes a partial copy of the string
1262  * pointed to by a.
1263  *
1264  * @param a pointer to a string
1265  * @param length of the string to duplicate
1266  * @return a partial copy of the string including zero-termination
1267  */
1268 #define GNUNET_strndup(a, length) \
1269   GNUNET_xstrndup_ (a, length, __FILE__, __LINE__)
1270
1271 /**
1272  * @ingroup memory
1273  * Grow a well-typed (!) array.  This is a convenience
1274  * method to grow a vector @a arr of size @a size
1275  * to the new (target) size @a tsize.
1276  * <p>
1277  *
1278  * Example (simple, well-typed stack):
1279  *
1280  * <pre>
1281  * static struct foo * myVector = NULL;
1282  * static int myVecLen = 0;
1283  *
1284  * static void push(struct foo * elem) {
1285  *   GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
1286  *   GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
1287  * }
1288  *
1289  * static void pop(struct foo * elem) {
1290  *   if (myVecLen == 0) die();
1291  *   GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
1292  *   GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
1293  * }
1294  * </pre>
1295  *
1296  * @param arr base-pointer of the vector, may be NULL if size is 0;
1297  *        will be updated to reflect the new address. The TYPE of
1298  *        arr is important since size is the number of elements and
1299  *        not the size in bytes
1300  * @param size the number of elements in the existing vector (number
1301  *        of elements to copy over), will be updated with the new
1302  *        array size
1303  * @param tsize the target size for the resulting vector, use 0 to
1304  *        free the vector (then, arr will be NULL afterwards).
1305  */
1306 #define GNUNET_array_grow(arr, size, tsize) \
1307   GNUNET_xgrow_ ((void **) &(arr),          \
1308                  sizeof ((arr)[0]),         \
1309                  &size,                     \
1310                  tsize,                     \
1311                  __FILE__,                  \
1312                  __LINE__)
1313
1314 /**
1315  * @ingroup memory
1316  * Append an element to a list (growing the list by one).
1317  *
1318  * @param arr base-pointer of the vector, may be NULL if size is 0;
1319  *        will be updated to reflect the new address. The TYPE of
1320  *        arr is important since size is the number of elements and
1321  *        not the size in bytes
1322  * @param size the number of elements in the existing vector (number
1323  *        of elements to copy over), will be updated with the new
1324  *        array size
1325  * @param element the element that will be appended to the array
1326  */
1327 #define GNUNET_array_append(arr, size, element) \
1328   do                                            \
1329   {                                             \
1330     GNUNET_array_grow (arr, size, size + 1);    \
1331     (arr)[size - 1] = element;                  \
1332   } while (0)
1333
1334 /**
1335  * @ingroup memory
1336  * Like snprintf, just aborts if the buffer is of insufficient size.
1337  *
1338  * @param buf pointer to buffer that is written to
1339  * @param size number of bytes in @a buf
1340  * @param format format strings
1341  * @param ... data for format string
1342  * @return number of bytes written to buf or negative value on error
1343  */
1344 int
1345 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
1346
1347
1348 /**
1349  * @ingroup memory
1350  * Like asprintf, just portable.
1351  *
1352  * @param buf set to a buffer of sufficient size (allocated, caller must free)
1353  * @param format format string (see printf, fprintf, etc.)
1354  * @param ... data for format string
1355  * @return number of bytes in "*buf" excluding 0-termination
1356  */
1357 int
1358 GNUNET_asprintf (char **buf, const char *format, ...);
1359
1360
1361 /* ************** internal implementations, use macros above! ************** */
1362
1363 /**
1364  * Allocate memory. Checks the return value, aborts if no more
1365  * memory is available.  Don't use GNUNET_xmalloc_ directly. Use the
1366  * #GNUNET_malloc macro.
1367  * The memory will be zero'ed out.
1368  *
1369  * @param size number of bytes to allocate
1370  * @param filename where is this call being made (for debugging)
1371  * @param linenumber line where this call is being made (for debugging)
1372  * @return allocated memory, never NULL
1373  */
1374 void *
1375 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
1376
1377
1378 /**
1379  * Allocate memory for a two dimensional array in one block
1380  * and set up pointers. Aborts if no more memory is available.
1381  * Don't use GNUNET_xnew_array_2d_ directly. Use the
1382  * #GNUNET_new_array_2d macro.
1383  * The memory of the elements will be zero'ed out.
1384  *
1385  * @param n size of the first dimension
1386  * @param m size of the second dimension
1387  * @param elementSize size of a single element in bytes
1388  * @param filename where is this call being made (for debugging)
1389  * @param linenumber line where this call is being made (for debugging)
1390  * @return allocated memory, never NULL
1391  */
1392 void **
1393 GNUNET_xnew_array_2d_ (size_t n,
1394                        size_t m,
1395                        size_t elementSize,
1396                        const char *filename,
1397                        int linenumber);
1398
1399
1400 /**
1401  * Allocate memory for a three dimensional array in one block
1402  * and set up pointers. Aborts if no more memory is available.
1403  * Don't use GNUNET_xnew_array_3d_ directly. Use the
1404  * #GNUNET_new_array_3d macro.
1405  * The memory of the elements will be zero'ed out.
1406  *
1407  * @param n size of the first dimension
1408  * @param m size of the second dimension
1409  * @param o size of the third dimension
1410  * @param elementSize size of a single element in bytes
1411  * @param filename where is this call being made (for debugging)
1412  * @param linenumber line where this call is being made (for debugging)
1413  * @return allocated memory, never NULL
1414  */
1415 void ***
1416 GNUNET_xnew_array_3d_ (size_t n,
1417                        size_t m,
1418                        size_t o,
1419                        size_t elementSize,
1420                        const char *filename,
1421                        int linenumber);
1422
1423
1424 /**
1425  * Allocate and initialize memory. Checks the return value, aborts if no more
1426  * memory is available.  Don't use GNUNET_xmemdup_ directly. Use the
1427  * #GNUNET_memdup macro.
1428  *
1429  * @param buf buffer to initialize from (must contain size bytes)
1430  * @param size number of bytes to allocate
1431  * @param filename where is this call being made (for debugging)
1432  * @param linenumber line where this call is being made (for debugging)
1433  * @return allocated memory, never NULL
1434  */
1435 void *
1436 GNUNET_xmemdup_ (const void *buf,
1437                  size_t size,
1438                  const char *filename,
1439                  int linenumber);
1440
1441
1442 /**
1443  * Allocate memory.  This function does not check if the allocation
1444  * request is within reasonable bounds, allowing allocations larger
1445  * than 40 MB.  If you don't expect the possibility of very large
1446  * allocations, use #GNUNET_malloc instead.  The memory will be zero'ed
1447  * out.
1448  *
1449  * @param size number of bytes to allocate
1450  * @param filename where is this call being made (for debugging)
1451  * @param linenumber line where this call is being made (for debugging)
1452  * @return pointer to size bytes of memory, NULL if we do not have enough memory
1453  */
1454 void *
1455 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
1456
1457
1458 /**
1459  * Reallocate memory. Checks the return value, aborts if no more
1460  * memory is available.
1461  */
1462 void *
1463 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
1464
1465
1466 /**
1467  * Free memory. Merely a wrapper for the case that we
1468  * want to keep track of allocations.  Don't use GNUNET_xfree_
1469  * directly. Use the #GNUNET_free macro.
1470  *
1471  * @param ptr pointer to memory to free
1472  * @param filename where is this call being made (for debugging)
1473  * @param linenumber line where this call is being made (for debugging)
1474  */
1475 void
1476 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1477
1478
1479 /**
1480  * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1481  * @param str string to duplicate
1482  * @param filename where is this call being made (for debugging)
1483  * @param linenumber line where this call is being made (for debugging)
1484  * @return the duplicated string
1485  */
1486 char *
1487 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1488
1489 /**
1490  * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1491  *
1492  * @param str string to duplicate
1493  * @param len length of the string to duplicate
1494  * @param filename where is this call being made (for debugging)
1495  * @param linenumber line where this call is being made (for debugging)
1496  * @return the duplicated string
1497  */
1498 char *
1499 GNUNET_xstrndup_ (const char *str,
1500                   size_t len,
1501                   const char *filename,
1502                   int linenumber);
1503
1504 /**
1505  * Grow an array, the new elements are zeroed out.
1506  * Grows old by (*oldCount-newCount)*elementSize
1507  * bytes and sets *oldCount to newCount.
1508  *
1509  * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1510  *
1511  * @param old address of the pointer to the array
1512  *        *old may be NULL
1513  * @param elementSize the size of the elements of the array
1514  * @param oldCount address of the number of elements in the *old array
1515  * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1516  * @param filename where is this call being made (for debugging)
1517  * @param linenumber line where this call is being made (for debugging)
1518  */
1519 void
1520 GNUNET_xgrow_ (void **old,
1521                size_t elementSize,
1522                unsigned int *oldCount,
1523                unsigned int newCount,
1524                const char *filename,
1525                int linenumber);
1526
1527
1528 /**
1529  * @ingroup memory
1530  * Create a copy of the given message.
1531  *
1532  * @param msg message to copy
1533  * @return duplicate of the message
1534  */
1535 struct GNUNET_MessageHeader *
1536 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1537
1538
1539 /**
1540  * Set the async scope for the current thread.
1541  *
1542  * @param aid the async scope identifier
1543  * @param old_scope[out] location to save the old scope
1544  */
1545 void
1546 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1547                           struct GNUNET_AsyncScopeSave *old_scope);
1548
1549
1550 /**
1551  * Clear the current thread's async scope.
1552  *
1553  * @param old_scope scope to restore
1554  */
1555 void
1556 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope);
1557
1558
1559 /**
1560  * Get the current async scope.
1561  *
1562  * @param[out] scope_ret pointer to where the result is stored
1563  */
1564 void
1565 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret);
1566
1567
1568 /**
1569  * Generate a fresh async scope identifier.
1570  *
1571  * @param[out] aid_ret pointer to where the result is stored
1572  */
1573 void
1574 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret);
1575
1576
1577 #if __STDC_VERSION__ < 199901L
1578 #if __GNUC__ >= 2
1579 #define __func__ __FUNCTION__
1580 #else
1581 #define __func__ "<unknown>"
1582 #endif
1583 #endif
1584
1585
1586 /**
1587  * Valid task priorities.  Use these, do not pass random integers!
1588  * For various reasons (#3862 -- building with QT Creator, and
1589  * our restricted cross-compilation with emscripten) this cannot
1590  * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1591  * Naturally, logically this is part of the scheduler.
1592  */
1593 enum GNUNET_SCHEDULER_Priority
1594 {
1595   /**
1596    * Run with the same priority as the current job.
1597    */
1598   GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1599
1600   /**
1601    * Run when otherwise idle.
1602    */
1603   GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1604
1605   /**
1606    * Run as background job (higher than idle,
1607    * lower than default).
1608    */
1609   GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1610
1611   /**
1612    * Run with the default priority (normal
1613    * P2P operations).  Any task that is scheduled
1614    * without an explicit priority being specified
1615    * will run with this priority.
1616    */
1617   GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1618
1619   /**
1620    * Run with high priority (important requests).
1621    * Higher than DEFAULT.
1622    */
1623   GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1624
1625   /**
1626    * Run with priority for interactive tasks.
1627    * Higher than "HIGH".
1628    */
1629   GNUNET_SCHEDULER_PRIORITY_UI = 5,
1630
1631   /**
1632    * Run with priority for urgent tasks.  Use
1633    * for things like aborts and shutdowns that
1634    * need to preempt "UI"-level tasks.
1635    * Higher than "UI".
1636    */
1637   GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1638
1639   /**
1640    * This is an internal priority level that is only used for tasks
1641    * that are being triggered due to shutdown (they have automatically
1642    * highest priority).  User code must not use this priority level
1643    * directly.  Tasks run with this priority level that internally
1644    * schedule other tasks will see their original priority level
1645    * be inherited (unless otherwise specified).
1646    */
1647   GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1648
1649   /**
1650    * Number of priorities (must be the last priority).
1651    * This priority must not be used by clients.
1652    */
1653   GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1654 };
1655
1656
1657 #if 0 /* keep Emacsens' auto-indent happy */
1658 {
1659 #endif
1660 #ifdef __cplusplus
1661 }
1662 #endif
1663
1664 #endif /* GNUNET_COMMON_H */