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