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