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