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