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