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