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