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