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