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