gnunet_common.h 18 KB

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