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