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