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