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