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