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