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