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