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