2 This file is part of GNUnet.
3 (C) 2006, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
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.
27 * @author Christian Grothoff
30 #ifndef GNUNET_COMMON_H
31 #define GNUNET_COMMON_H
34 #include <sys/socket.h>
37 #include <netinet/in.h>
47 * Version of the API (for entire gnunetutil.so library).
49 #define GNUNET_UTIL_VERSION 0x00000000
52 * Name used for "services" that are actually command-line
53 * programs invoked by the end user.
55 #define GNUNET_CLIENT_SERVICE_NAME "client"
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".
64 #define GNUNET_SYSERR -1
68 #define GNUNET_MIN(a,b) (((a) < (b)) ? (a) : (b))
70 #define GNUNET_MAX(a,b) (((a) > (b)) ? (a) : (b))
73 * gcc-ism to get packed structs.
75 #define GNUNET_PACKED __attribute__((packed))
78 /* ************************ super-general types *********************** */
81 * Header for all communications.
83 struct GNUNET_MessageHeader
87 * The length of the struct (in bytes, including the length field itself),
88 * in big-endian format.
90 uint16_t size GNUNET_PACKED;
93 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
95 uint16_t type GNUNET_PACKED;
101 * @brief 512-bit hashcode
105 uint32_t bits[512 / 8 / sizeof (uint32_t)]; /* = 16 */
111 * The identity of the host (basically the SHA-512 hashcode of
114 struct GNUNET_PeerIdentity
116 GNUNET_HashCode hashPubKey GNUNET_PACKED;
121 * Function called with a filename.
124 * @param filename complete filename (absolute path)
125 * @return GNUNET_OK to continue to iterate,
126 * GNUNET_SYSERR to abort iteration with error!
128 typedef int (*GNUNET_FileNameCallback) (void *cls, const char *filename);
131 /* ****************************** logging ***************************** */
136 enum GNUNET_ErrorType
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
147 * User-defined handler for log messages.
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
155 typedef void (*GNUNET_Logger) (void *cls,
156 enum GNUNET_ErrorType kind,
157 const char *component,
158 const char *date, const char *message);
163 * @param kind how serious is the error?
164 * @param message what is the message (format string)
165 * @param ... arguments for format string
167 void GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...);
172 * Log function that specifies an alternative component.
173 * This function should be used by plugins.
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
181 GNUNET_log_from (enum GNUNET_ErrorType kind,
182 const char *comp, const char *message, ...);
186 * Ignore the next n calls to the log function.
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
192 GNUNET_log_skip (unsigned int n, int check_reset);
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
204 GNUNET_log_setup (const char *comp,
205 const char *loglevel, const char *logfile);
208 * Add a custom logger.
210 * @param logger log function
211 * @param logger_cls closure for logger
213 void GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
216 * Remove a custom logger.
218 * @param logger log function
219 * @param logger_cls closure for logger
221 void GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
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
229 * @param hc the hash code
232 const char *GNUNET_h2s (const GNUNET_HashCode *hc);
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
240 * @param hc the hash code
243 const char *GNUNET_h2s_full (const GNUNET_HashCode *hc);
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
250 * @param pid the peer identity
251 * @return string form of the pid; will be overwritten by next
252 * call to GNUNET_i2s.
254 const char *GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
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!
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.
267 const char *GNUNET_a2s (const struct sockaddr *addr,
271 * Convert error type to string.
273 * @param kind type to convert
274 * @return string corresponding to the type
276 const char *GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
279 * Use this for fatal errors that cannot be handled
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)
284 * Use this for fatal errors that cannot be handled
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)
289 * Use this for internal assertion violations that are
290 * not fatal (can be handled) but should not occur.
292 #define GNUNET_break(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
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".
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)
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).
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)
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).
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)
318 /* ************************* endianess conversion ****************** */
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
325 unsigned long long GNUNET_ntohll (unsigned long long n);
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
332 unsigned long long GNUNET_htonll (unsigned long long n);
335 /* ************************* allocation functions ****************** */
338 * Maximum allocation with GNUNET_malloc macro.
340 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
343 * Wrapper around malloc. Allocates size bytes of memory.
344 * The memory will be zero'ed out.
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 (!)
350 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
353 * Wrapper around malloc. Allocates size bytes of memory.
354 * The memory will be zero'ed out.
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
359 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
362 * Wrapper around realloc. Rellocates size bytes of memory.
364 * @param ptr the pointer to reallocate
365 * @param size the number of bytes to reallocate
366 * @return pointer to size bytes of memory
368 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
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.
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.
378 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
381 * Free the memory pointed to by ptr if ptr is not NULL.
382 * Equivalent to if (ptr!=null)GNUNET_free(ptr).
384 * @param ptr the location in memory to free
386 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
389 * Wrapper around GNUNET_strdup. Makes a copy of the zero-terminated string
392 * @param a pointer to a zero-terminated string
393 * @return a copy of the string including zero-termination
395 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
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>.
403 * Example (simple, well-typed stack):
406 * static struct foo * myVector = NULL;
407 * static int myVecLen = 0;
409 * static void push(struct foo * elem) {
410 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
411 * memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
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);
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).
430 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
433 * Append an element to a list (growing the
436 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
439 * Like snprintf, just aborts if the buffer is of insufficient size.
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
447 int GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
451 * Like asprintf, just portable.
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
458 int GNUNET_asprintf (char **buf, const char *format, ...);
461 /* ************** internal implementations, use macros above! ************** */
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.
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
474 void *GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
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
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
489 void *GNUNET_xmalloc_unchecked_ (size_t size,
490 const char *filename, int linenumber);
493 * Reallocate memory. Checks the return value, aborts if no more
494 * memory is available.
496 void *GNUNET_xrealloc_ (void *ptr,
497 size_t n, const char *filename, int linenumber);
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.
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)
508 void GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
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
518 char *GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
521 * Grow an array, the new elements are zeroed out.
522 * Grows old by (*oldCount-newCount)*elementSize
523 * bytes and sets *oldCount to newCount.
525 * Don't call GNUNET_xgrow_ directly. Use the GNUNET_array_grow macro.
527 * @param old address of the pointer to the array
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)
535 void GNUNET_xgrow_ (void **old,
537 unsigned int *oldCount,
538 unsigned int newCount,
539 const char *filename, int linenumber);
544 #if __STDC_VERSION__ < 199901L
546 # define __func__ __FUNCTION__
548 # define __func__ "<unknown>"
552 #endif /*GNUNET_COMMON_H_ */