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