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