2d13d0ecc1855f8de8fd24e4baa1646f177b48b0
[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
40 /**
41  * Version of the API (for entire gnunetutil.so library).
42  */
43 #define GNUNET_UTIL_VERSION 0x00000000
44
45 /**
46  * Name used for "services" that are actually command-line
47  * programs invoked by the end user.
48  */
49 #define GNUNET_CLIENT_SERVICE_NAME "client"
50
51 /**
52  * Named constants for return values.  The following
53  * invariants hold: "GNUNET_NO == 0" (to allow "if (GNUNET_NO)")
54  * "GNUNET_OK != GNUNET_SYSERR", "GNUNET_OK != GNUNET_NO", "GNUNET_NO != GNUNET_SYSERR"
55  * and finally "GNUNET_YES != GNUNET_NO".
56  */
57 #define GNUNET_OK      1
58 #define GNUNET_SYSERR -1
59 #define GNUNET_YES     1
60 #define GNUNET_NO      0
61
62 #define GNUNET_MIN(a,b) (((a) < (b)) ? (a) : (b))
63
64 #define GNUNET_MAX(a,b) (((a) > (b)) ? (a) : (b))
65
66 /**
67  * gcc-ism to get packed structs.
68  */
69 #define GNUNET_PACKED __attribute__((packed))
70
71
72 /* ************************ super-general types *********************** */
73
74 /**
75  * Header for all communications.
76  */
77 struct GNUNET_MessageHeader
78 {
79
80   /**
81    * The length of the struct (in bytes, including the length field itself),
82    * in big-endian format.
83    */
84   uint16_t size GNUNET_PACKED;
85
86   /**
87    * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
88    */
89   uint16_t type GNUNET_PACKED;
90
91 };
92
93
94 /**
95  * @brief 512-bit hashcode
96  */
97 typedef struct
98 {
99   uint32_t bits[512 / 8 / sizeof (uint32_t)];   /* = 16 */
100 }
101 GNUNET_HashCode;
102
103
104 /**
105  * The identity of the host (basically the SHA-512 hashcode of
106  * it's public key).
107  */
108 struct GNUNET_PeerIdentity
109 {
110   GNUNET_HashCode hashPubKey GNUNET_PACKED;
111 };
112
113
114 /**
115  * Function called with a filename.
116  *
117  * @param cls closure
118  * @param filename complete filename (absolute path)
119  * @return GNUNET_OK to continue to iterate,
120  *  GNUNET_SYSERR to abort iteration with error!
121  */
122 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
123
124
125 /* ****************************** logging ***************************** */
126
127 /**
128  * Types of errors.
129  */
130 enum GNUNET_ErrorType
131 {
132   GNUNET_ERROR_TYPE_ERROR = 1,
133   GNUNET_ERROR_TYPE_WARNING = 2,
134   GNUNET_ERROR_TYPE_INFO = 4,
135   GNUNET_ERROR_TYPE_DEBUG = 8,
136   GNUNET_ERROR_TYPE_INVALID = 16,
137   GNUNET_ERROR_TYPE_BULK = 32
138 };
139
140 /**
141  * User-defined handler for log messages.
142  *
143  * @param cls closure
144  * @param kind severeity
145  * @param component what component is issuing the message?
146  * @param date when was the message logged?
147  * @param message what is the message
148  */
149 typedef void (*GNUNET_Logger) (void *cls,
150                                enum GNUNET_ErrorType kind,
151                                const char *component,
152                                const char *date, const char *message);
153
154 /**
155  * Main log function.
156  *
157  * @param kind how serious is the error?
158  * @param message what is the message (format string)
159  * @param ... arguments for format string
160  */
161 void GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...);
162
163
164
165 /**
166  * Log function that specifies an alternative component.
167  * This function should be used by plugins.
168  *
169  * @param kind how serious is the error?
170  * @param comp component responsible for generating the message
171  * @param message what is the message (format string)
172  * @param ... arguments for format string
173  */
174 void
175 GNUNET_log_from (enum GNUNET_ErrorType kind,
176                  const char *comp, const char *message, ...);
177
178
179 /**
180  * Ignore the next n calls to the log function.
181  *
182  * @param n number of log calls to ignore
183  * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
184  */
185 void
186 GNUNET_log_skip (unsigned int n, int check_reset);
187
188
189 /**
190  * Setup logging.
191  *
192  * @param comp default component to use
193  * @param loglevel what types of messages should be logged
194  * @param logfile change logging to logfile (use NULL to keep stderr)
195  * @return GNUNET_OK on success, GNUNET_SYSERR if logfile could not be opened
196  */
197 int
198 GNUNET_log_setup (const char *comp,
199                   const char *loglevel, const char *logfile);
200
201 /**
202  * Add a custom logger.
203  *
204  * @param logger log function
205  * @param logger_cls closure for logger
206  */
207 void GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
208
209 /**
210  * Remove a custom logger.
211  *
212  * @param logger log function
213  * @param logger_cls closure for logger
214  */
215 void GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
216
217
218 /**
219  * Convert a hash value to a string (for printing debug messages).
220  * This is one of the very few calls in the entire API that is
221  * NOT reentrant!
222  *
223  * @param hc the hash code
224  * @return string 
225  */
226 const char *GNUNET_h2s (const GNUNET_HashCode *hc);
227
228
229 /**
230  * Convert a peer identity to a string (for printing debug messages).
231  * This is one of the very few calls in the entire API that is
232  * NOT reentrant!
233  *
234  * @param pid the peer identity
235  * @return string form of the pid; will be overwritten by next
236  *         call to GNUNET_i2s.
237  */
238 const char *GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
239
240
241 /**
242  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
243  * (for printing debug messages).  This is one of the very few calls
244  * in the entire API that is NOT reentrant!
245  *
246  * @param addr the address
247  * @param addrlen the length of the address
248  * @return nicely formatted string for the address
249  *  will be overwritten by next call to GNUNET_a2s.
250  */
251 const char *GNUNET_a2s (const struct sockaddr *addr,
252                         socklen_t addrlen);
253
254 /**
255  * Convert error type to string.
256  *
257  * @param kind type to convert
258  * @return string corresponding to the type
259  */
260 const char *GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
261
262 /**
263  * Use this for fatal errors that cannot be handled
264  */
265 #define GNUNET_assert(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); abort(); } } while(0)
266
267 /**
268  * Use this for fatal errors that cannot be handled
269  */
270 #define GNUNET_assert_at(cond, f, l) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), f, l); abort(); } } while(0)
271
272 /**
273  * Use this for internal assertion violations that are
274  * not fatal (can be handled) but should not occur.
275  */
276 #define GNUNET_break(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
277
278 /**
279  * Use this for assertion violations caused by other
280  * peers (i.e. protocol violations).  We do not want to
281  * confuse end-users (say, some other peer runs an
282  * older, broken or incompatible GNUnet version), but
283  * we still want to see these problems during
284  * development and testing.  "OP == other peer".
285  */
286 #define GNUNET_break_op(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("External protocol violation detected at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
287
288 /**
289  * Log an error message at log-level 'level' that indicates
290  * a failure of the command 'cmd' with the message given
291  * by strerror(errno).
292  */
293 #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)
294
295 /**
296  * Log an error message at log-level 'level' that indicates
297  * a failure of the command 'cmd' with the message given
298  * by strerror(errno).
299  */
300 #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)
301
302 /* ************************* endianess conversion ****************** */
303
304 /**
305  * Convert a long-long to host-byte-order.
306  * @param n the value in network byte order
307  * @return the same value in host byte order
308  */
309 unsigned long long GNUNET_ntohll (unsigned long long n);
310
311 /**
312  * Convert a long long to network-byte-order.
313  * @param n the value in host byte order
314  * @return the same value in network byte order
315  */
316 unsigned long long GNUNET_htonll (unsigned long long n);
317
318
319 /* ************************* allocation functions ****************** */
320
321 /**
322  * Maximum allocation with GNUNET_malloc macro.
323  */
324 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
325
326 /**
327  * Wrapper around malloc. Allocates size bytes of memory.
328  * The memory will be zero'ed out.
329  *
330  * @param size the number of bytes to allocate, must be
331  *        smaller than 40 MB.
332  * @return pointer to size bytes of memory, never NULL (!)
333  */
334 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
335
336 /**
337  * Wrapper around malloc. Allocates size bytes of memory.
338  * The memory will be zero'ed out.
339  *
340  * @param size the number of bytes to allocate
341  * @return pointer to size bytes of memory, NULL if we do not have enough memory
342  */
343 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
344
345 /**
346  * Wrapper around realloc. Rellocates size bytes of memory.
347  *
348  * @param ptr the pointer to reallocate
349  * @param size the number of bytes to reallocate
350  * @return pointer to size bytes of memory
351  */
352 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
353
354 /**
355  * Wrapper around free. Frees the memory referred to by ptr.
356  * Note that is is generally better to free memory that was
357  * allocated with GNUNET_array_grow using GNUNET_array_grow(mem, size, 0) instead of GNUNET_free.
358  *
359  * @param ptr location where to free the memory. ptr must have
360  *     been returned by GNUNET_strdup, GNUNET_malloc or GNUNET_array_grow earlier.
361  */
362 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
363
364 /**
365  * Free the memory pointed to by ptr if ptr is not NULL.
366  * Equivalent to if (ptr!=null)GNUNET_free(ptr).
367  *
368  * @param ptr the location in memory to free
369  */
370 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
371
372 /**
373  * Wrapper around GNUNET_strdup.  Makes a copy of the zero-terminated string
374  * pointed to by a.
375  *
376  * @param a pointer to a zero-terminated string
377  * @return a copy of the string including zero-termination
378  */
379 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
380
381 /**
382  * Grow a well-typed (!) array.  This is a convenience
383  * method to grow a vector <tt>arr</tt> of size <tt>size</tt>
384  * to the new (target) size <tt>tsize</tt>.
385  * <p>
386  *
387  * Example (simple, well-typed stack):
388  *
389  * <pre>
390  * static struct foo * myVector = NULL;
391  * static int myVecLen = 0;
392  *
393  * static void push(struct foo * elem) {
394  *   GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
395  *   memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
396  * }
397  *
398  * static void pop(struct foo * elem) {
399  *   if (myVecLen == 0) die();
400  *   memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
401  *   GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
402  * }
403  * </pre>
404  *
405  * @param arr base-pointer of the vector, may be NULL if size is 0;
406  *        will be updated to reflect the new address. The TYPE of
407  *        arr is important since size is the number of elements and
408  *        not the size in bytes
409  * @param size the number of elements in the existing vector (number
410  *        of elements to copy over)
411  * @param tsize the target size for the resulting vector, use 0 to
412  *        free the vector (then, arr will be NULL afterwards).
413  */
414 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
415
416 /**
417  * Append an element to a list (growing the
418  * list by one).
419  */
420 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
421
422 /**
423  * Like snprintf, just aborts if the buffer is of insufficient size.
424  *
425  * @param buf pointer to buffer that is written to
426  * @param size number of bytes in buf
427  * @param format format strings
428  * @param ... data for format string
429  * @return number of bytes written to buf or negative value on error
430  */
431 int GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
432
433
434 /**
435  * Like asprintf, just portable.
436  *
437  * @param buf set to a buffer of sufficient size (allocated, caller must free)
438  * @param format format string (see printf, fprintf, etc.)
439  * @param ... data for format string
440  * @return number of bytes in "*buf" excluding 0-termination
441  */
442 int GNUNET_asprintf (char **buf, const char *format, ...);
443
444
445 /* ************** internal implementations, use macros above! ************** */
446
447 /**
448  * Allocate memory. Checks the return value, aborts if no more
449  * memory is available.  Don't use GNUNET_xmalloc_ directly. Use the
450  * GNUNET_malloc macro.
451  * The memory will be zero'ed out.
452  *
453  * @param size number of bytes to allocate
454  * @param filename where is this call being made (for debugging)
455  * @param linenumber line where this call is being made (for debugging)
456  * @return allocated memory, never NULL
457  */
458 void *GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
459
460
461 /**
462  * Allocate memory.  This function does not check if the allocation
463  * request is within reasonable bounds, allowing allocations larger
464  * than 40 MB.  If you don't expect the possibility of very large
465  * allocations, use GNUNET_malloc instead.  The memory will be zero'ed
466  * out.
467  *
468  * @param size number of bytes to allocate
469  * @param filename where is this call being made (for debugging)
470  * @param linenumber line where this call is being made (for debugging)
471  * @return pointer to size bytes of memory, NULL if we do not have enough memory
472  */
473 void *GNUNET_xmalloc_unchecked_ (size_t size,
474                                  const char *filename, int linenumber);
475
476 /**
477  * Reallocate memory. Checks the return value, aborts if no more
478  * memory is available.
479  */
480 void *GNUNET_xrealloc_ (void *ptr,
481                         const size_t n, const char *filename, int linenumber);
482
483 /**
484  * Free memory. Merely a wrapper for the case that we
485  * want to keep track of allocations.  Don't use GNUNET_xfree_
486  * directly. Use the GNUNET_free macro.
487  *
488  * @param ptr pointer to memory to free
489  * @param filename where is this call being made (for debugging)
490  * @param linenumber line where this call is being made (for debugging)
491  */
492 void GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
493
494
495 /**
496  * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the GNUNET_strdup macro.
497  * @param str string to duplicate
498  * @param filename where is this call being made (for debugging)
499  * @param linenumber line where this call is being made (for debugging)
500  * @return the duplicated string
501  */
502 char *GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
503
504 /**
505  * Grow an array, the new elements are zeroed out.
506  * Grows old by (*oldCount-newCount)*elementSize
507  * bytes and sets *oldCount to newCount.
508  *
509  * Don't call GNUNET_xgrow_ directly. Use the GNUNET_array_grow macro.
510  *
511  * @param old address of the pointer to the array
512  *        *old may be NULL
513  * @param elementSize the size of the elements of the array
514  * @param oldCount address of the number of elements in the *old array
515  * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
516  * @param filename where is this call being made (for debugging)
517  * @param linenumber line where this call is being made (for debugging)
518  */
519 void GNUNET_xgrow_ (void **old,
520                     size_t elementSize,
521                     unsigned int *oldCount,
522                     unsigned int newCount,
523                     const char *filename, int linenumber);
524
525
526
527
528 #if __STDC_VERSION__ < 199901L
529 # if __GNUC__ >= 2
530 #  define __func__ __FUNCTION__
531 # else
532 #  define __func__ "<unknown>"
533 # endif
534 #endif
535
536 #endif /*GNUNET_COMMON_H_ */