fixing compiler warnings
[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 0x000A0101
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   GNUNET_ERROR_TYPE_INFO = 4,
336   GNUNET_ERROR_TYPE_DEBUG = 8,
337   GNUNET_ERROR_TYPE_INVALID = 16,
338   GNUNET_ERROR_TYPE_BULK = 32
339 };
340
341
342 /**
343  * @ingroup logging
344  * User-defined handler for log messages.
345  *
346  * @param cls closure
347  * @param kind severeity
348  * @param component what component is issuing the message?
349  * @param date when was the message logged?
350  * @param message what is the message
351  */
352 typedef void
353 (*GNUNET_Logger) (void *cls,
354                   enum GNUNET_ErrorType kind,
355                   const char *component,
356                   const char *date,
357                   const char *message);
358
359
360 /**
361  * @ingroup logging
362  * Get the number of log calls that are going to be skipped
363  *
364  * @return number of log calls to be ignored
365  */
366 int
367 GNUNET_get_log_skip (void);
368
369
370 #if !defined(GNUNET_CULL_LOGGING)
371 int
372 GNUNET_get_log_call_status (int caller_level,
373                             const char *comp,
374                             const char *file,
375                             const char *function,
376                             int line);
377 #endif
378
379
380 /**
381  * @ingroup logging
382  * Main log function.
383  *
384  * @param kind how serious is the error?
385  * @param message what is the message (format string)
386  * @param ... arguments for format string
387  */
388 void
389 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
390   __attribute__ ((format (printf, 2, 3)));
391
392 /* from glib */
393 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
394 #define _GNUNET_BOOLEAN_EXPR(expr)              \
395  __extension__ ({                               \
396    int _gnunet_boolean_var_;                    \
397    if (expr)                                    \
398       _gnunet_boolean_var_ = 1;                 \
399    else                                         \
400       _gnunet_boolean_var_ = 0;                 \
401    _gnunet_boolean_var_;                        \
402 })
403 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 1))
404 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 0))
405 #else
406 #define GN_LIKELY(expr) (expr)
407 #define GN_UNLIKELY(expr) (expr)
408 #endif
409
410 #if !defined(GNUNET_LOG_CALL_STATUS)
411 #define GNUNET_LOG_CALL_STATUS -1
412 #endif
413
414
415 /**
416  * @ingroup logging
417  * Log function that specifies an alternative component.
418  * This function should be used by plugins.
419  *
420  * @param kind how serious is the error?
421  * @param comp component responsible for generating the message
422  * @param message what is the message (format string)
423  * @param ... arguments for format string
424  */
425 void
426 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
427                          const char *message, ...);
428
429 #if !defined(GNUNET_CULL_LOGGING)
430 #define GNUNET_log_from(kind,comp,...) do { int log_line = __LINE__;\
431   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
432   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
433     if (GN_UNLIKELY(log_call_enabled == -1))\
434       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), (comp), __FILE__, __FUNCTION__, log_line); \
435     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
436     else {\
437       if (GN_UNLIKELY(log_call_enabled))\
438         GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__);    \
439     }\
440   }\
441 } while (0)
442
443  #define GNUNET_log(kind,...) do { int log_line = __LINE__;\
444   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
445   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
446     if (GN_UNLIKELY(log_call_enabled == -1))\
447       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), NULL, __FILE__, __FUNCTION__, log_line);\
448     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
449     else {\
450       if (GN_UNLIKELY(log_call_enabled))\
451         GNUNET_log_nocheck ((kind), __VA_ARGS__);       \
452     }\
453   }\
454 } while (0)
455 #else
456 #define GNUNET_log(...)
457 #define GNUNET_log_from(...)
458 #endif
459
460
461 /**
462  * @ingroup logging
463  * Log error message about missing configuration option.
464  *
465  * @param kind log level
466  * @param section section with missing option
467  * @param option name of missing option
468  */
469 void
470 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
471                            const char *section,
472                            const char *option);
473
474
475 /**
476  * @ingroup logging
477  * Log error message about invalid configuration option value.
478  *
479  * @param kind log level
480  * @param section section with invalid option
481  * @param option name of invalid option
482  * @param required what is required that is invalid about the option
483  */
484 void
485 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
486                            const char *section,
487                            const char *option,
488                            const char *required);
489
490
491 /**
492  * @ingroup logging
493  * Abort the process, generate a core dump if possible.
494  * Most code should use `GNUNET_assert (0)` instead to
495  * first log the location of the failure.
496  */
497 void
498 GNUNET_abort_ (void) GNUNET_NORETURN;
499
500
501 /**
502  * @ingroup logging
503  * Ignore the next @a n calls to the log function.
504  *
505  * @param n number of log calls to ignore (could be negative)
506  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
507  */
508 void
509 GNUNET_log_skip (int n,
510                  int check_reset);
511
512
513 /**
514  * @ingroup logging
515  * Setup logging.
516  *
517  * @param comp default component to use
518  * @param loglevel what types of messages should be logged
519  * @param logfile change logging to logfile (use NULL to keep stderr)
520  * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
521  */
522 int
523 GNUNET_log_setup (const char *comp,
524                   const char *loglevel,
525                   const char *logfile);
526
527
528 /**
529  * @ingroup logging
530  * Add a custom logger.  Note that installing any custom logger
531  * will disable the standard logger.  When multiple custom loggers
532  * are installed, all will be called.  The standard logger will
533  * only be used if no custom loggers are present.
534  *
535  * @param logger log function
536  * @param logger_cls closure for @a logger
537  */
538 void
539 GNUNET_logger_add (GNUNET_Logger logger,
540                    void *logger_cls);
541
542
543 /**
544  * @ingroup logging
545  * Remove a custom logger.
546  *
547  * @param logger log function
548  * @param logger_cls closure for @a logger
549  */
550 void
551 GNUNET_logger_remove (GNUNET_Logger logger,
552                       void *logger_cls);
553
554
555 /**
556  * @ingroup logging
557  * Convert a hash value to a string (for printing debug messages).
558  * This is one of the very few calls in the entire API that is
559  * NOT reentrant!
560  *
561  * @param hc the hash code
562  * @return string
563  */
564 const char *
565 GNUNET_h2s (const struct GNUNET_HashCode * hc);
566
567
568 /**
569  * @ingroup logging
570  * Convert a hash value to a string (for printing debug messages).
571  * This prints all 104 characters of a hashcode!
572  * This is one of the very few calls in the entire API that is
573  * NOT reentrant!
574  *
575  * @param hc the hash code
576  * @return string
577  */
578 const char *
579 GNUNET_h2s_full (const struct GNUNET_HashCode * hc);
580
581
582 /**
583  * @ingroup logging
584  * Convert a peer identity to a string (for printing debug messages).
585  * This is one of the very few calls in the entire API that is
586  * NOT reentrant!
587  *
588  * @param pid the peer identity
589  * @return string form of the pid; will be overwritten by next
590  *         call to #GNUNET_i2s().
591  */
592 const char *
593 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
594
595
596 /**
597  * @ingroup logging
598  * Convert a peer identity to a string (for printing debug messages).
599  * This is one of the very few calls in the entire API that is
600  * NOT reentrant!
601  *
602  * @param pid the peer identity
603  * @return string form of the pid; will be overwritten by next
604  *         call to #GNUNET_i2s_full().
605  */
606 const char *
607 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
608
609
610 /**
611  * @ingroup logging
612  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
613  * (for printing debug messages).  This is one of the very few calls
614  * in the entire API that is NOT reentrant!
615  *
616  * @param addr the address
617  * @param addrlen the length of the @a addr
618  * @return nicely formatted string for the address
619  *  will be overwritten by next call to #GNUNET_a2s().
620  */
621 const char *
622 GNUNET_a2s (const struct sockaddr *addr,
623             socklen_t addrlen);
624
625
626 /**
627  * @ingroup logging
628  * Convert error type to string.
629  *
630  * @param kind type to convert
631  * @return string corresponding to the type
632  */
633 const char *
634 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
635
636
637 /**
638  * @ingroup logging
639  * Use this for fatal errors that cannot be handled
640  */
641 #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)
642
643
644 /**
645  * @ingroup logging
646  * Use this for fatal errors that cannot be handled
647  */
648 #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)
649
650
651 /**
652  * @ingroup logging
653  * Use this for internal assertion violations that are
654  * not fatal (can be handled) but should not occur.
655  */
656 #define GNUNET_break(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
657
658
659 /**
660  * @ingroup logging
661  * Use this for assertion violations caused by other
662  * peers (i.e. protocol violations).  We do not want to
663  * confuse end-users (say, some other peer runs an
664  * older, broken or incompatible GNUnet version), but
665  * we still want to see these problems during
666  * development and testing.  "OP == other peer".
667  */
668 #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)
669
670
671 /**
672  * @ingroup logging
673  * Log an error message at log-level 'level' that indicates
674  * a failure of the command 'cmd' with the message given
675  * by strerror(errno).
676  */
677 #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)
678
679
680 /**
681  * @ingroup logging
682  * Log an error message at log-level 'level' that indicates
683  * a failure of the command 'cmd' with the message given
684  * by strerror(errno).
685  */
686 #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)
687
688
689 /**
690  * @ingroup logging
691  * Log an error message at log-level 'level' that indicates
692  * a failure of the command 'cmd' with the message given
693  * by strerror(errno).
694  */
695 #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)
696
697
698 /**
699  * @ingroup logging
700  * Log an error message at log-level 'level' that indicates
701  * a failure of the command 'cmd' with the message given
702  * by strerror(errno).
703  */
704 #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)
705
706 /* ************************* endianess conversion ****************** */
707
708 /**
709  * Convert unsigned 64-bit integer to network byte order.
710  *
711  * @param n
712  *        The value in host byte order.
713  *
714  * @return The same value in network byte order.
715  */
716 uint64_t
717 GNUNET_htonll (uint64_t n);
718
719
720 /**
721  * Convert unsigned 64-bit integer to host byte order.
722  *
723  * @param n
724  *        The value in network byte order.
725  *
726  * @return The same value in host byte order.
727  */
728 uint64_t
729 GNUNET_ntohll (uint64_t n);
730
731
732 /**
733  * Convert double to network byte order.
734  *
735  * @param d
736  *        The value in host byte order.
737  *
738  * @return The same value in network byte order.
739  */
740 double
741 GNUNET_hton_double (double d);
742
743
744 /**
745  * Convert double to host byte order
746  *
747  * @param d
748  *        The value in network byte order.
749  *
750  * @return The same value in host byte order.
751  */
752 double
753 GNUNET_ntoh_double (double d);
754
755
756 /* ************************* allocation functions ****************** */
757
758 /**
759  * @ingroup memory
760  * Maximum allocation with GNUNET_malloc macro.
761  */
762 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
763
764 /**
765  * @ingroup memory
766  * Allocate a struct or union of the given @a type.
767  * Wrapper around #GNUNET_malloc that returns a pointer
768  * to the newly created object of the correct type.
769  *
770  * @param type name of the struct or union, i.e. pass 'struct Foo'.
771  */
772 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
773
774 /**
775  * @ingroup memory
776  * Allocate a size @a n array with structs or unions of the given @a type.
777  * Wrapper around #GNUNET_malloc that returns a pointer
778  * to the newly created objects of the correct type.
779  *
780  * @param n number of elements in the array
781  * @param type name of the struct or union, i.e. pass 'struct Foo'.
782  */
783 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
784
785 /**
786  * @ingroup memory
787  * Wrapper around malloc. Allocates size bytes of memory.
788  * The memory will be zero'ed out.
789  *
790  * @param size the number of bytes to allocate, must be
791  *        smaller than 40 MB.
792  * @return pointer to size bytes of memory, never NULL (!)
793  */
794 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
795
796 /**
797  * @ingroup memory
798  * Allocate and initialize a block of memory.
799  *
800  * @param buf data to initalize the block with
801  * @param size the number of bytes in buf (and size of the allocation)
802  * @return pointer to size bytes of memory, never NULL (!)
803  */
804 #define GNUNET_memdup(buf,size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__)
805
806 /**
807  * @ingroup memory
808  * Wrapper around malloc. Allocates size bytes of memory.
809  * The memory will be zero'ed out.
810  *
811  * @param size the number of bytes to allocate
812  * @return pointer to size bytes of memory, NULL if we do not have enough memory
813  */
814 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
815
816 /**
817  * @ingroup memory
818  * Wrapper around realloc. Rellocates size bytes of memory.
819  *
820  * @param ptr the pointer to reallocate
821  * @param size the number of bytes to reallocate
822  * @return pointer to size bytes of memory
823  */
824 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
825
826 /**
827  * @ingroup memory
828  * Wrapper around free. Frees the memory referred to by ptr.
829  * Note that it is generally better to free memory that was
830  * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
831  *
832  * @param ptr location where to free the memory. ptr must have
833  *     been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
834  */
835 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
836
837 /**
838  * @ingroup memory
839  * Free the memory pointed to by ptr if ptr is not NULL.
840  * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
841  *
842  * @param ptr the location in memory to free
843  */
844 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
845
846 /**
847  * @ingroup memory
848  * Wrapper around #GNUNET_xstrdup_.  Makes a copy of the zero-terminated string
849  * pointed to by a.
850  *
851  * @param a pointer to a zero-terminated string
852  * @return a copy of the string including zero-termination
853  */
854 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
855
856 /**
857  * @ingroup memory
858  * Wrapper around #GNUNET_xstrndup_.  Makes a partial copy of the string
859  * pointed to by a.
860  *
861  * @param a pointer to a string
862  * @param length of the string to duplicate
863  * @return a partial copy of the string including zero-termination
864  */
865 #define GNUNET_strndup(a,length) GNUNET_xstrndup_(a,length,__FILE__,__LINE__)
866
867 /**
868  * @ingroup memory
869  * Grow a well-typed (!) array.  This is a convenience
870  * method to grow a vector @a arr of size @a size
871  * to the new (target) size @a tsize.
872  * <p>
873  *
874  * Example (simple, well-typed stack):
875  *
876  * <pre>
877  * static struct foo * myVector = NULL;
878  * static int myVecLen = 0;
879  *
880  * static void push(struct foo * elem) {
881  *   GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
882  *   memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
883  * }
884  *
885  * static void pop(struct foo * elem) {
886  *   if (myVecLen == 0) die();
887  *   memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
888  *   GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
889  * }
890  * </pre>
891  *
892  * @param arr base-pointer of the vector, may be NULL if size is 0;
893  *        will be updated to reflect the new address. The TYPE of
894  *        arr is important since size is the number of elements and
895  *        not the size in bytes
896  * @param size the number of elements in the existing vector (number
897  *        of elements to copy over)
898  * @param tsize the target size for the resulting vector, use 0 to
899  *        free the vector (then, arr will be NULL afterwards).
900  */
901 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
902
903 /**
904  * @ingroup memory
905  * Append an element to a list (growing the
906  * list by one).
907  */
908 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
909
910 /**
911  * @ingroup memory
912  * Like snprintf, just aborts if the buffer is of insufficient size.
913  *
914  * @param buf pointer to buffer that is written to
915  * @param size number of bytes in @a buf
916  * @param format format strings
917  * @param ... data for format string
918  * @return number of bytes written to buf or negative value on error
919  */
920 int
921 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
922
923
924 /**
925  * @ingroup memory
926  * Like asprintf, just portable.
927  *
928  * @param buf set to a buffer of sufficient size (allocated, caller must free)
929  * @param format format string (see printf, fprintf, etc.)
930  * @param ... data for format string
931  * @return number of bytes in "*buf" excluding 0-termination
932  */
933 int
934 GNUNET_asprintf (char **buf, const char *format, ...);
935
936
937 /* ************** internal implementations, use macros above! ************** */
938
939 /**
940  * Allocate memory. Checks the return value, aborts if no more
941  * memory is available.  Don't use GNUNET_xmalloc_ directly. Use the
942  * #GNUNET_malloc macro.
943  * The memory will be zero'ed out.
944  *
945  * @param size number of bytes to allocate
946  * @param filename where is this call being made (for debugging)
947  * @param linenumber line where this call is being made (for debugging)
948  * @return allocated memory, never NULL
949  */
950 void *
951 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
952
953
954 /**
955  * Allocate and initialize memory. Checks the return value, aborts if no more
956  * memory is available.  Don't use GNUNET_xmemdup_ directly. Use the
957  * #GNUNET_memdup macro.
958  *
959  * @param buf buffer to initialize from (must contain size bytes)
960  * @param size number of bytes to allocate
961  * @param filename where is this call being made (for debugging)
962  * @param linenumber line where this call is being made (for debugging)
963  * @return allocated memory, never NULL
964  */
965 void *
966 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
967                  int linenumber);
968
969
970 /**
971  * Allocate memory.  This function does not check if the allocation
972  * request is within reasonable bounds, allowing allocations larger
973  * than 40 MB.  If you don't expect the possibility of very large
974  * allocations, use #GNUNET_malloc instead.  The memory will be zero'ed
975  * out.
976  *
977  * @param size number of bytes to allocate
978  * @param filename where is this call being made (for debugging)
979  * @param linenumber line where this call is being made (for debugging)
980  * @return pointer to size bytes of memory, NULL if we do not have enough memory
981  */
982 void *
983 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
984
985
986 /**
987  * Reallocate memory. Checks the return value, aborts if no more
988  * memory is available.
989  */
990 void *
991 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
992
993
994 /**
995  * Free memory. Merely a wrapper for the case that we
996  * want to keep track of allocations.  Don't use GNUNET_xfree_
997  * directly. Use the #GNUNET_free macro.
998  *
999  * @param ptr pointer to memory to free
1000  * @param filename where is this call being made (for debugging)
1001  * @param linenumber line where this call is being made (for debugging)
1002  */
1003 void
1004 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
1005
1006
1007 /**
1008  * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
1009  * @param str string to duplicate
1010  * @param filename where is this call being made (for debugging)
1011  * @param linenumber line where this call is being made (for debugging)
1012  * @return the duplicated string
1013  */
1014 char *
1015 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
1016
1017 /**
1018  * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
1019  *
1020  * @param str string to duplicate
1021  * @param len length of the string to duplicate
1022  * @param filename where is this call being made (for debugging)
1023  * @param linenumber line where this call is being made (for debugging)
1024  * @return the duplicated string
1025  */
1026 char *
1027 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
1028                   int linenumber);
1029
1030 /**
1031  * Grow an array, the new elements are zeroed out.
1032  * Grows old by (*oldCount-newCount)*elementSize
1033  * bytes and sets *oldCount to newCount.
1034  *
1035  * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
1036  *
1037  * @param old address of the pointer to the array
1038  *        *old may be NULL
1039  * @param elementSize the size of the elements of the array
1040  * @param oldCount address of the number of elements in the *old array
1041  * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
1042  * @param filename where is this call being made (for debugging)
1043  * @param linenumber line where this call is being made (for debugging)
1044  */
1045 void
1046 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
1047                unsigned int newCount, const char *filename, int linenumber);
1048
1049
1050 /**
1051  * @ingroup memory
1052  * Create a copy of the given message.
1053  *
1054  * @param msg message to copy
1055  * @return duplicate of the message
1056  */
1057 struct GNUNET_MessageHeader *
1058 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
1059
1060
1061 #if __STDC_VERSION__ < 199901L
1062 #if __GNUC__ >= 2
1063 #define __func__ __FUNCTION__
1064 #else
1065 #define __func__ "<unknown>"
1066 #endif
1067 #endif
1068
1069
1070 /**
1071  * Valid task priorities.  Use these, do not pass random integers!
1072  * For various reasons (#3862 -- building with QT Creator, and
1073  * our restricted cross-compilation with emscripten) this cannot
1074  * be in gnunet_scheduler_lib.h, but it works if we declare it here.
1075  * Naturally, logically this is part of the scheduler.
1076  */
1077 enum GNUNET_SCHEDULER_Priority
1078 {
1079   /**
1080    * Run with the same priority as the current job.
1081    */
1082   GNUNET_SCHEDULER_PRIORITY_KEEP = 0,
1083
1084   /**
1085    * Run when otherwise idle.
1086    */
1087   GNUNET_SCHEDULER_PRIORITY_IDLE = 1,
1088
1089   /**
1090    * Run as background job (higher than idle,
1091    * lower than default).
1092    */
1093   GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2,
1094
1095   /**
1096    * Run with the default priority (normal
1097    * P2P operations).  Any task that is scheduled
1098    * without an explicit priority being specified
1099    * will run with this priority.
1100    */
1101   GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3,
1102
1103   /**
1104    * Run with high priority (important requests).
1105    * Higher than DEFAULT.
1106    */
1107   GNUNET_SCHEDULER_PRIORITY_HIGH = 4,
1108
1109   /**
1110    * Run with priority for interactive tasks.
1111    * Higher than "HIGH".
1112    */
1113   GNUNET_SCHEDULER_PRIORITY_UI = 5,
1114
1115   /**
1116    * Run with priority for urgent tasks.  Use
1117    * for things like aborts and shutdowns that
1118    * need to preempt "UI"-level tasks.
1119    * Higher than "UI".
1120    */
1121   GNUNET_SCHEDULER_PRIORITY_URGENT = 6,
1122
1123   /**
1124    * This is an internal priority level that is only used for tasks
1125    * that are being triggered due to shutdown (they have automatically
1126    * highest priority).  User code must not use this priority level
1127    * directly.  Tasks run with this priority level that internally
1128    * schedule other tasks will see their original priority level
1129    * be inherited (unless otherwise specified).
1130    */
1131   GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7,
1132
1133   /**
1134    * Number of priorities (must be the last priority).
1135    * This priority must not be used by clients.
1136    */
1137   GNUNET_SCHEDULER_PRIORITY_COUNT = 8
1138 };
1139
1140
1141 #if 0                           /* keep Emacsens' auto-indent happy */
1142 {
1143 #endif
1144 #ifdef __cplusplus
1145 }
1146 #endif
1147
1148 #endif /* GNUNET_COMMON_H */