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