gnunet_common.h (58002B)
1 /* 2 This file is part of GNUnet. 3 Copyright (C) 2006-2022 GNUnet e.V. 4 5 GNUnet is free software: you can redistribute it and/or modify it 6 under the terms of the GNU Affero General Public License as published 7 by the Free Software Foundation, either version 3 of the License, 8 or (at your 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 Affero General Public License for more details. 14 15 You should have received a copy of the GNU Affero General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 SPDX-License-Identifier: AGPL3.0-or-later 19 */ 20 21 /** 22 * @addtogroup libgnunetutil 23 * Multi-function utilities library for GNUnet programs 24 * @{ 25 * 26 * @file include/gnunet_common.h 27 * @brief commonly used definitions; globals in this file 28 * are exempt from the rule that the module name ("common") 29 * must be part of the symbol name. 30 * 31 * @author Christian Grothoff 32 * @author Nils Durner 33 * @author Martin Schanzenbach 34 * 35 * @defgroup logging Logging 36 * @see [Documentation](https://gnunet.org/logging) 37 * 38 * @defgroup memory Memory management 39 */ 40 #ifndef GNUNET_COMMON_H 41 #define GNUNET_COMMON_H 42 43 #include "gnunet_config.h" 44 45 #include <stdbool.h> 46 #include <stdlib.h> 47 #include <sys/socket.h> 48 #include <sys/un.h> 49 #include <netinet/in.h> 50 #include <arpa/inet.h> 51 #include <stdint.h> 52 #include <stdarg.h> 53 #include <sys/types.h> 54 55 #if defined(__FreeBSD__) 56 57 #include <sys/endian.h> 58 #define bswap_32(x) bswap32 (x) 59 #define bswap_64(x) bswap64 (x) 60 61 #elif defined(__OpenBSD__) 62 63 #define bswap_32(x) swap32 (x) 64 #define bswap_64(x) swap64 (x) 65 66 #elif defined(__NetBSD__) 67 68 #include <machine/bswap.h> 69 #if defined(__BSWAP_RENAME) && ! defined(__bswap_32) 70 #define bswap_32(x) bswap32 (x) 71 #define bswap_64(x) bswap64 (x) 72 #endif 73 74 #elif defined(__linux__) || defined(GNU) 75 #include <byteswap.h> 76 #endif 77 78 79 /* This is also included in platform.h, but over there a couple of 80 GNUnet-specific gettext-related macros are defined in addition to including 81 the header file. Because this header file uses gettext, this include 82 statement makes sure gettext macros are defined even when platform.h is 83 unavailable. */ 84 #ifndef _LIBGETTEXT_H 85 #include "gettext.h" 86 #endif 87 88 #ifdef __cplusplus 89 extern "C" { 90 #if 0 /* keep Emacsens' auto-indent happy */ 91 } 92 #endif 93 #endif 94 95 /** 96 * Version of the API (for entire gnunetutil.so library). 97 */ 98 #define GNUNET_UTIL_VERSION 0x000A0104 99 100 101 /** 102 * Named constants for return values. The following invariants hold: 103 * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK != 104 * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO != 105 * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`. 106 */ 107 enum GNUNET_GenericReturnValue 108 { 109 GNUNET_SYSERR = -1, 110 GNUNET_NO = 0, 111 GNUNET_OK = 1, 112 /* intentionally identical to #GNUNET_OK! */ 113 GNUNET_YES = 1, 114 }; 115 116 117 #define GNUNET_MIN(a, b) (((a) < (b)) ? (a) : (b)) 118 119 #define GNUNET_MAX(a, b) (((a) > (b)) ? (a) : (b)) 120 121 /* some systems use one underscore only, and mingw uses no underscore... */ 122 #ifndef __BYTE_ORDER 123 #ifdef _BYTE_ORDER 124 #define __BYTE_ORDER _BYTE_ORDER 125 #else 126 #ifdef BYTE_ORDER 127 #define __BYTE_ORDER BYTE_ORDER 128 #endif 129 #endif 130 #endif 131 #ifndef __BIG_ENDIAN 132 #ifdef _BIG_ENDIAN 133 #define __BIG_ENDIAN _BIG_ENDIAN 134 #else 135 #ifdef BIG_ENDIAN 136 #define __BIG_ENDIAN BIG_ENDIAN 137 #endif 138 #endif 139 #endif 140 #ifndef __LITTLE_ENDIAN 141 #ifdef _LITTLE_ENDIAN 142 #define __LITTLE_ENDIAN _LITTLE_ENDIAN 143 #else 144 #ifdef LITTLE_ENDIAN 145 #define __LITTLE_ENDIAN LITTLE_ENDIAN 146 #endif 147 #endif 148 #endif 149 150 /** 151 * @ingroup logging 152 * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source 153 * tree where gnunet_config.h is unavailable 154 */ 155 #ifndef GNUNET_EXTRA_LOGGING 156 #define GNUNET_EXTRA_LOGGING 1 157 #endif 158 159 /** 160 * Endian operations 161 */ 162 163 #if defined(bswap_16) || defined(bswap_32) || defined(bswap_64) 164 #define BYTE_SWAP_16(x) bswap_16 (x) 165 #define BYTE_SWAP_32(x) bswap_32 (x) 166 #define BYTE_SWAP_64(x) bswap_64 (x) 167 #else 168 #define BYTE_SWAP_16(x) ((((x) & 0x00ff) << 8) | (((x) & 0xff00) >> 8)) 169 170 #define BYTE_SWAP_32(x) \ 171 ((((x) & 0x000000ffU) << 24) | (((x) & 0x0000ff00U) << 8) \ 172 | (((x) & 0x00ff0000U) >> 8) | (((x) & 0xff000000U) >> 24)) 173 174 #define BYTE_SWAP_64(x) \ 175 ((((x) & 0x00000000000000ffUL) << 56) | (((x) & 0x000000000000ff00UL) << \ 176 40) \ 177 | (((x) & 0x0000000000ff0000UL) << 24) | (((x) & 0x00000000ff000000UL) \ 178 << 8) \ 179 | (((x) & 0x000000ff00000000UL) >> 8) | (((x) & 0x0000ff0000000000UL) \ 180 >> 24) \ 181 | (((x) & 0x00ff000000000000UL) >> 40) | (((x) & 0xff00000000000000UL) \ 182 >> \ 183 56)) 184 #endif 185 186 #if __BYTE_ORDER == __LITTLE_ENDIAN 187 #define GNUNET_htobe16(x) BYTE_SWAP_16 (x) 188 #define GNUNET_htole16(x) (x) 189 #define GNUNET_be16toh(x) BYTE_SWAP_16 (x) 190 #define GNUNET_le16toh(x) (x) 191 192 #define GNUNET_htobe32(x) BYTE_SWAP_32 (x) 193 #define GNUNET_htole32(x) (x) 194 #define GNUNET_be32toh(x) BYTE_SWAP_32 (x) 195 #define GNUNET_le32toh(x) (x) 196 197 #define GNUNET_htobe64(x) BYTE_SWAP_64 (x) 198 #define GNUNET_htole64(x) (x) 199 #define GNUNET_be64toh(x) BYTE_SWAP_64 (x) 200 #define GNUNET_le64toh(x) (x) 201 #endif 202 #if __BYTE_ORDER == __BIG_ENDIAN 203 #define GNUNET_htobe16(x) (x) 204 #define GNUNET_htole16(x) BYTE_SWAP_16 (x) 205 #define GNUNET_be16toh(x) (x) 206 #define GNUNET_le16toh(x) BYTE_SWAP_16 (x) 207 208 #define GNUNET_htobe32(x) (x) 209 #define GNUNET_htole32(x) BYTE_SWAP_32 (x) 210 #define GNUNET_be32toh(x) (x) 211 #define GNUNET_le32toh(x) BYTE_SWAP_32 (x) 212 213 #define GNUNET_htobe64(x) (x) 214 #define GNUNET_htole64(x) BYTE_SWAP_64 (x) 215 #define GNUNET_be64toh(x) (x) 216 #define GNUNET_le64toh(x) BYTE_SWAP_64 (x) 217 #endif 218 219 220 /** 221 * Macro used to avoid using 0 for the length of a variable-size 222 * array (Non-Zero-Length). 223 * 224 * Basically, C standard says that "int[n] x;" is undefined if n=0. 225 * This was supposed to prevent issues with pointer aliasing. 226 * However, C compilers may conclude that n!=0 as n=0 would be 227 * undefined, and then optimize under the assumption n!=0, which 228 * could cause actual issues. Hence, when initializing an array 229 * on the stack with a variable-length that might be zero, write 230 * "int[GNUNET_NZL(n)] x;" instead of "int[n] x". 231 */ 232 #define GNUNET_NZL(l) GNUNET_MAX (1, l) 233 234 235 /** 236 * gcc-ism to get packed structs. 237 */ 238 #define GNUNET_PACKED __attribute__ ((packed)) 239 240 /** 241 * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields 242 */ 243 #define GNUNET_GCC_STRUCT_LAYOUT 244 245 /** 246 * gcc-ism to force alignment; we use this to align char-arrays 247 * that may then be cast to 'struct's. See also gcc 248 * bug #33594. 249 */ 250 #ifdef __BIGGEST_ALIGNMENT__ 251 #define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__))) 252 #else 253 #define GNUNET_ALIGN __attribute__ ((aligned (8))) 254 #endif 255 256 /** 257 * gcc-ism to document unused arguments 258 */ 259 #define GNUNET_UNUSED __attribute__ ((unused)) 260 261 /** 262 * gcc-ism to document functions that don't return 263 */ 264 #define GNUNET_NORETURN __attribute__ ((noreturn)) 265 266 /** 267 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32 268 */ 269 #define GNUNET_NETWORK_STRUCT_BEGIN 270 271 /** 272 * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32; 273 */ 274 #define GNUNET_NETWORK_STRUCT_END 275 276 /* ************************ super-general types *********************** */ 277 278 GNUNET_NETWORK_STRUCT_BEGIN 279 280 /** 281 * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512. 282 */ 283 struct GNUNET_HashCode 284 { 285 uint32_t bits[512 / 8 / sizeof(uint32_t)]; /* = 16 */ 286 }; 287 288 289 /** 290 * @brief A 256-bit hashcode. Used under special conditions, like when space 291 * is critical and security is not impacted by it. 292 */ 293 struct GNUNET_ShortHashCode 294 { 295 uint32_t bits[256 / 8 / sizeof(uint32_t)]; /* = 8 */ 296 }; 297 298 299 /** 300 * A UUID, a 128 bit "random" value. We OFTEN use 301 * timeflakes (see: https://github.com/anthonynsimon/timeflake), 302 * where only 80 bits are random and the rest encodes 303 * a timestamp to improve database access. 304 * 305 * See #GNUNET_CRYPTO_random_timeflake(). 306 */ 307 struct GNUNET_Uuid 308 { 309 /** 310 * 128 random bits. 311 */ 312 uint32_t value[4]; 313 }; 314 315 316 /** 317 * Header for all communications. 318 */ 319 struct GNUNET_MessageHeader 320 { 321 /** 322 * The length of the struct (in bytes, including the length field itself), 323 * in big-endian format. 324 */ 325 uint16_t size GNUNET_PACKED; 326 327 /** 328 * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format. 329 */ 330 uint16_t type GNUNET_PACKED; 331 }; 332 333 334 /** 335 * Identifier for an asynchronous execution context. 336 */ 337 struct GNUNET_AsyncScopeId 338 { 339 uint32_t bits[16 / sizeof(uint32_t)]; /* = 16 bytes */ 340 }; 341 342 GNUNET_NETWORK_STRUCT_END 343 344 345 /** 346 * Saved async scope identifier or root scope. 347 */ 348 struct GNUNET_AsyncScopeSave 349 { 350 /** 351 * Saved scope. Unused if 'have_scope==GNUNET_NO'. 352 */ 353 struct GNUNET_AsyncScopeId scope_id; 354 355 /** 356 * GNUNET_YES unless this saved scope is the unnamed root scope. 357 */ 358 int have_scope; 359 }; 360 361 362 /** 363 * Function called with a filename. 364 * 365 * @param cls closure 366 * @param filename complete filename (absolute path) 367 * @return #GNUNET_OK to continue to iterate, 368 * #GNUNET_NO to stop iteration with no error, 369 * #GNUNET_SYSERR to abort iteration with error! 370 */ 371 typedef enum GNUNET_GenericReturnValue 372 (*GNUNET_FileNameCallback) (void *cls, 373 const char *filename); 374 375 376 /** 377 * Generic continuation callback. 378 * 379 * @param cls Closure. 380 */ 381 typedef void 382 (*GNUNET_ContinuationCallback) (void *cls); 383 384 385 /** 386 * Function called with the result of an asynchronous operation. 387 * 388 * @param cls 389 * Closure. 390 * @param result_code 391 * Result code for the operation. 392 * @param data 393 * Data result for the operation. 394 * @param data_size 395 * Size of @a data. 396 */ 397 typedef void 398 (*GNUNET_ResultCallback) (void *cls, 399 int64_t result_code, 400 const void *data, 401 uint16_t data_size); 402 403 404 /* ****************************** logging ***************************** */ 405 406 /** 407 * @ingroup logging 408 * Types of errors. 409 */ 410 enum GNUNET_ErrorType 411 { 412 GNUNET_ERROR_TYPE_UNSPECIFIED = -1, 413 GNUNET_ERROR_TYPE_NONE = 0, 414 GNUNET_ERROR_TYPE_ERROR = 1, 415 GNUNET_ERROR_TYPE_WARNING = 2, 416 /* UX: We need a message type that is output by 417 * default without looking like there is a problem. 418 */ 419 GNUNET_ERROR_TYPE_MESSAGE = 4, 420 GNUNET_ERROR_TYPE_INFO = 8, 421 GNUNET_ERROR_TYPE_DEBUG = 16, 422 GNUNET_ERROR_TYPE_INVALID = 32, 423 GNUNET_ERROR_TYPE_BULK = 64 424 }; 425 426 427 /** 428 * @ingroup logging 429 * User-defined handler for log messages. 430 * 431 * @param cls closure 432 * @param kind severeity 433 * @param component what component is issuing the message? 434 * @param date when was the message logged? 435 * @param message what is the message 436 */ 437 typedef void 438 (*GNUNET_Logger) (void *cls, 439 enum GNUNET_ErrorType kind, 440 const char *component, 441 const char *date, 442 const char *message); 443 444 445 /** 446 * @ingroup logging 447 * Get the number of log calls that are going to be skipped 448 * 449 * @return number of log calls to be ignored 450 */ 451 int 452 GNUNET_get_log_skip (void); 453 454 455 #if ! defined(GNUNET_CULL_LOGGING) 456 int 457 GNUNET_get_log_call_status (int caller_level, 458 const char *comp, 459 const char *file, 460 const char *function, 461 int line); 462 463 #endif 464 465 /* *INDENT-OFF* */ 466 /** 467 * @ingroup logging 468 * Main log function. 469 * 470 * @param kind how serious is the error? 471 * @param message what is the message (format string) 472 * @param ... arguments for format string 473 */ 474 void 475 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, 476 const char *message, 477 ...) 478 __attribute__ ((format (printf, 2, 3))); 479 480 /* from glib */ 481 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__) 482 #define _GNUNET_BOOLEAN_EXPR(expr) \ 483 __extension__ ({ \ 484 int _gnunet_boolean_var_; \ 485 if (expr) \ 486 _gnunet_boolean_var_ = 1; \ 487 else \ 488 _gnunet_boolean_var_ = 0; \ 489 _gnunet_boolean_var_; \ 490 }) 491 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1)) 492 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0)) 493 #else 494 #define GN_LIKELY(expr) (expr) 495 #define GN_UNLIKELY(expr) (expr) 496 #endif 497 498 #if ! defined(GNUNET_LOG_CALL_STATUS) 499 #define GNUNET_LOG_CALL_STATUS -1 500 #endif 501 /* *INDENT-ON* */ 502 503 504 /** 505 * @ingroup logging 506 * Log function that specifies an alternative component. 507 * This function should be used by plugins. 508 * 509 * @param kind how serious is the error? 510 * @param comp component responsible for generating the message 511 * @param message what is the message (format string) 512 * @param ... arguments for format string 513 */ 514 void 515 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, 516 const char *comp, 517 const char *message, 518 ...) 519 __attribute__ ((format (printf, 3, 4))); 520 521 #if ! defined(GNUNET_CULL_LOGGING) 522 #define GNUNET_log_from(kind, comp, ...) \ 523 do \ 524 { \ 525 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \ 526 if ((GNUNET_EXTRA_LOGGING > 0) || \ 527 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \ 528 { \ 529 if (GN_UNLIKELY (log_call_enabled == -1)) \ 530 log_call_enabled = \ 531 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ 532 (comp), \ 533 __FILE__, \ 534 __func__, \ 535 __LINE__); \ 536 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \ 537 { \ 538 GNUNET_log_skip (-1, GNUNET_NO); \ 539 } \ 540 else \ 541 { \ 542 if (GN_UNLIKELY (log_call_enabled)) \ 543 GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \ 544 } \ 545 } \ 546 } while (0) 547 548 #define GNUNET_log(kind, ...) \ 549 do \ 550 { \ 551 static int log_call_enabled = GNUNET_LOG_CALL_STATUS; \ 552 if ((GNUNET_EXTRA_LOGGING > 0) || \ 553 ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \ 554 { \ 555 if (GN_UNLIKELY (log_call_enabled == -1)) \ 556 log_call_enabled = \ 557 GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ 558 NULL, \ 559 __FILE__, \ 560 __func__, \ 561 __LINE__); \ 562 if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \ 563 { \ 564 GNUNET_log_skip (-1, GNUNET_NO); \ 565 } \ 566 else \ 567 { \ 568 if (GN_UNLIKELY (log_call_enabled)) \ 569 GNUNET_log_nocheck ((kind), __VA_ARGS__); \ 570 } \ 571 } \ 572 } while (0) 573 #else 574 #define GNUNET_log(...) 575 #define GNUNET_log_from(...) 576 #endif 577 578 579 /** 580 * @ingroup logging 581 * Log error message about missing configuration option. 582 * 583 * @param kind log level 584 * @param section section with missing option 585 * @param option name of missing option 586 */ 587 void 588 GNUNET_log_config_missing (enum GNUNET_ErrorType kind, 589 const char *section, 590 const char *option); 591 592 593 /** 594 * @ingroup logging 595 * Log error message about invalid configuration option value. 596 * 597 * @param kind log level 598 * @param section section with invalid option 599 * @param option name of invalid option 600 * @param required what is required that is invalid about the option 601 */ 602 void 603 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind, 604 const char *section, 605 const char *option, 606 const char *required); 607 608 609 /** 610 * @ingroup logging 611 * Abort the process, generate a core dump if possible. 612 * Most code should use `GNUNET_assert (0)` instead to 613 * first log the location of the failure. 614 */ 615 void 616 GNUNET_abort_ (void) GNUNET_NORETURN; 617 618 619 /** 620 * Convert a buffer to an 8-character string 621 * representative of the contents. This is used 622 * for logging binary data when debugging. 623 * 624 * @param buf buffer to log 625 * @param buf_size number of bytes in @a buf 626 * @return text representation of buf, valid until next 627 * call to this function 628 */ 629 const char * 630 GNUNET_b2s (const void *buf, 631 size_t buf_size); 632 633 634 /** 635 * Convert a fixed-sized object to a string using 636 * #GNUNET_b2s(). 637 * 638 * @param obj address of object to convert 639 * @return string representing the binary obj buffer 640 */ 641 #define GNUNET_B2S(obj) GNUNET_b2s ((obj), sizeof (*(obj))) 642 643 644 /** 645 * @ingroup logging 646 * Ignore the next @a n calls to the log function. 647 * 648 * @param n number of log calls to ignore (could be negative) 649 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero 650 */ 651 void 652 GNUNET_log_skip (int n, int check_reset); 653 654 655 /** 656 * @ingroup logging 657 * Setup logging. 658 * 659 * @param comp default component to use 660 * @param loglevel what types of messages should be logged 661 * @param logfile change logging to logfile (use NULL to keep stderr) 662 * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened 663 */ 664 enum GNUNET_GenericReturnValue 665 GNUNET_log_setup (const char *comp, 666 const char *loglevel, 667 const char *logfile); 668 669 670 /** 671 * @ingroup logging 672 * Add a custom logger. Note that installing any custom logger 673 * will disable the standard logger. When multiple custom loggers 674 * are installed, all will be called. The standard logger will 675 * only be used if no custom loggers are present. 676 * 677 * @param logger log function 678 * @param logger_cls closure for @a logger 679 */ 680 void 681 GNUNET_logger_add (GNUNET_Logger logger, 682 void *logger_cls); 683 684 685 /** 686 * @ingroup logging 687 * Remove a custom logger. 688 * 689 * @param logger log function 690 * @param logger_cls closure for @a logger 691 */ 692 void 693 GNUNET_logger_remove (GNUNET_Logger logger, 694 void *logger_cls); 695 696 697 /** 698 * @ingroup logging 699 * Convert a short hash value to a string (for printing debug messages). 700 * This is one of the very few calls in the entire API that is 701 * NOT reentrant! 702 * 703 * @param shc the hash code 704 * @return string 705 */ 706 const char * 707 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc); 708 709 710 /** 711 * @ingroup logging 712 * Convert a UUID to a string (for printing debug messages). 713 * This is one of the very few calls in the entire API that is 714 * NOT reentrant! 715 * 716 * @param uuid the UUID 717 * @return string 718 */ 719 const char * 720 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid); 721 722 723 /** 724 * @ingroup logging 725 * Convert a hash value to a string (for printing debug messages). 726 * This is one of the very few calls in the entire API that is 727 * NOT reentrant! 728 * 729 * @param hc the hash code 730 * @return string 731 */ 732 const char * 733 GNUNET_h2s (const struct GNUNET_HashCode *hc); 734 735 736 /** 737 * @ingroup logging 738 * Convert a hash value to a string (for printing debug messages). 739 * This is one of the very few calls in the entire API that is 740 * NOT reentrant! Identical to #GNUNET_h2s(), except that another 741 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be 742 * used within the same log statement. 743 * 744 * @param hc the hash code 745 * @return string 746 */ 747 const char * 748 GNUNET_h2s2 (const struct GNUNET_HashCode *hc); 749 750 751 /** 752 * @ingroup logging 753 * Convert a hash value to a string (for printing debug messages). 754 * This prints all 104 characters of a hashcode! 755 * This is one of the very few calls in the entire API that is 756 * NOT reentrant! 757 * 758 * @param hc the hash code 759 * @return string 760 */ 761 const char * 762 GNUNET_h2s_full (const struct GNUNET_HashCode *hc); 763 764 765 /** 766 * Public key. Details in gnunet_util_crypto.h. 767 */ 768 struct GNUNET_CRYPTO_EddsaPublicKey; 769 770 771 /** 772 * Public key. Details in gnunet_util_crypto.h. 773 */ 774 struct GNUNET_CRYPTO_EcdhePublicKey; 775 776 777 /** 778 * @ingroup logging 779 * Convert a public key value to a string (for printing debug messages). 780 * This is one of the very few calls in the entire API that is 781 * NOT reentrant! 782 * 783 * @param hc the hash code 784 * @return string 785 */ 786 const char * 787 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p); 788 789 790 /** 791 * @ingroup logging 792 * Convert a public key value to a string (for printing debug messages). 793 * This is one of the very few calls in the entire API that is 794 * NOT reentrant! 795 * 796 * @param hc the hash code 797 * @return string 798 */ 799 const char * 800 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p); 801 802 803 /** 804 * @ingroup logging 805 * Convert a public key value to a string (for printing debug messages). 806 * This is one of the very few calls in the entire API that is 807 * NOT reentrant! 808 * 809 * @param hc the hash code 810 * @return string 811 */ 812 const char * 813 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p); 814 815 816 /** 817 * @ingroup logging 818 * Convert a public key value to a string (for printing debug messages). 819 * This is one of the very few calls in the entire API that is 820 * NOT reentrant! 821 * 822 * @param hc the hash code 823 * @return string 824 */ 825 const char * 826 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p); 827 828 829 /** 830 * Forward declaration to make compiler happy depending on include order. 831 */ 832 struct GNUNET_PeerIdentity; 833 834 835 /** 836 * @ingroup logging 837 * Convert a peer identity to a string (for printing debug messages). 838 * This is one of the very few calls in the entire API that is 839 * NOT reentrant! 840 * 841 * @param pid the peer identity 842 * @return string form of the pid; will be overwritten by next 843 * call to #GNUNET_i2s(). 844 */ 845 const char * 846 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid); 847 848 849 /** 850 * @ingroup logging 851 * Convert a peer identity to a string (for printing debug messages). 852 * This is one of the very few calls in the entire API that is 853 * NOT reentrant! Identical to #GNUNET_i2s(), except that another 854 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be 855 * used within the same log statement. 856 * 857 * @param pid the peer identity 858 * @return string form of the pid; will be overwritten by next 859 * call to #GNUNET_i2s(). 860 */ 861 const char * 862 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid); 863 864 865 /** 866 * @ingroup logging 867 * Convert a peer identity to a string (for printing debug messages). 868 * This is one of the very few calls in the entire API that is 869 * NOT reentrant! 870 * 871 * @param pid the peer identity 872 * @return string form of the pid; will be overwritten by next 873 * call to #GNUNET_i2s_full(). 874 */ 875 const char * 876 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid); 877 878 879 /** 880 * @ingroup logging 881 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string 882 * (for printing debug messages). This is one of the very few calls 883 * in the entire API that is NOT reentrant! 884 * 885 * @param addr the address 886 * @param addrlen the length of the @a addr 887 * @return nicely formatted string for the address 888 * will be overwritten by next call to #GNUNET_a2s(). 889 */ 890 const char * 891 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen); 892 893 /** 894 * @ingroup logging 895 * Parse an ascii-encoded hexadecimal string into the 896 * buffer. The buffer must be (strlen (src) / 2) bytes 897 * in length. 898 * 899 * @param src the string 900 * @param dst the destination buffer 901 * @param dst_len the length of the @a dst buffer 902 * @param invert read from @a src in inverted direction. 903 * @return number of bytes written. 904 */ 905 size_t 906 GNUNET_hex2b (const char *src, void *dst, size_t dstlen, int invert); 907 908 /** 909 * @ingroup logging 910 * Print a byte string in hexadecimal ascii notation 911 * 912 * @param buf the byte string 913 * @param buf_len the length of the @a buf buffer 914 * @param fold insert newline after this number of bytes 915 (0 for no folding) 916 * @param in_be Output byte string in NBO 917 */ 918 void 919 GNUNET_print_bytes (const void *buf, 920 size_t buf_len, 921 int fold, 922 int in_be); 923 924 /** 925 * @ingroup logging 926 * Convert error type to string. 927 * 928 * @param kind type to convert 929 * @return string corresponding to the type 930 */ 931 const char * 932 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); 933 934 935 /** 936 * @ingroup logging 937 * Use this for fatal errors that cannot be handled 938 */ 939 #if __GNUC__ >= 6 || __clang_major__ >= 6 940 #define GNUNET_assert(cond) \ 941 do \ 942 { \ 943 _Pragma("GCC diagnostic push") \ 944 _Pragma("GCC diagnostic ignored \"-Wtautological-compare\"") \ 945 if (! (cond)) \ 946 { \ 947 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ 948 dgettext ("gnunet", "Assertion failed at %s:%d. Aborting.\n"), \ 949 __FILE__, \ 950 __LINE__); \ 951 GNUNET_abort_ (); \ 952 } \ 953 _Pragma("GCC diagnostic pop") \ 954 } while (0) 955 #else 956 /* older GCC/clangs do not support -Wtautological-compare */ 957 #define GNUNET_assert(cond) \ 958 do \ 959 { \ 960 if (! (cond)) \ 961 { \ 962 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ 963 dgettext ("gnunet", \ 964 "Assertion failed at %s:%d. Aborting.\n"), \ 965 __FILE__, \ 966 __LINE__); \ 967 GNUNET_abort_ (); \ 968 } \ 969 } while (0) 970 #endif 971 972 /** 973 * @ingroup logging 974 * Use this for fatal errors that cannot be handled 975 */ 976 #define GNUNET_assert_at(cond, f, l) \ 977 do \ 978 { \ 979 if (! (cond)) \ 980 { \ 981 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ 982 dgettext ("gnunet", \ 983 "Assertion failed at %s:%d. Aborting.\n"), \ 984 f, \ 985 l); \ 986 GNUNET_abort_ (); \ 987 } \ 988 } while (0) 989 990 991 /** 992 * @ingroup logging 993 * Use this for fatal errors that cannot be handled 994 * 995 * @param cond Condition to evaluate 996 * @param comp Component string to use for logging 997 */ 998 #define GNUNET_assert_from(cond, comp) \ 999 do \ 1000 { \ 1001 if (! (cond)) \ 1002 { \ 1003 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \ 1004 comp, \ 1005 dgettext ("gnunet", \ 1006 "Assertion failed at %s:%d. Aborting.\n") \ 1007 , \ 1008 __FILE__, \ 1009 __LINE__); \ 1010 GNUNET_abort_ (); \ 1011 } \ 1012 } while (0) 1013 1014 1015 #ifdef _Static_assert 1016 /** 1017 * Assertion to be checked (if supported by C compiler) at 1018 * compile time, otherwise checked at runtime and resulting 1019 * in an abort() on failure. 1020 * 1021 * @param cond condition to test, 0 implies failure 1022 */ 1023 #define GNUNET_static_assert(cond) _Static_assert (cond, "") 1024 #else 1025 /** 1026 * Assertion to be checked (if supported by C compiler) at 1027 * compile time, otherwise checked at runtime and resulting 1028 * in an abort() on failure. This is the case where the 1029 * compiler does not support static assertions. 1030 * 1031 * @param cond condition to test, 0 implies failure 1032 */ 1033 #define GNUNET_static_assert(cond) GNUNET_assert (cond) 1034 #endif 1035 1036 1037 /** 1038 * @ingroup logging 1039 * Use this for internal assertion violations that are 1040 * not fatal (can be handled) but should not occur. 1041 */ 1042 #define GNUNET_break(cond) \ 1043 do \ 1044 { \ 1045 if (! (cond)) \ 1046 { \ 1047 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ 1048 dgettext ("gnunet", "Assertion failed at %s:%d.\n"), \ 1049 __FILE__, \ 1050 __LINE__); \ 1051 } \ 1052 } while (0) 1053 1054 1055 /** 1056 * @ingroup logging 1057 * Use this for assertion violations caused by other 1058 * peers (i.e. protocol violations). We do not want to 1059 * confuse end-users (say, some other peer runs an 1060 * older, broken or incompatible GNUnet version), but 1061 * we still want to see these problems during 1062 * development and testing. "OP == other peer". 1063 */ 1064 #define GNUNET_break_op(cond) \ 1065 do \ 1066 { \ 1067 if (! (cond)) \ 1068 { \ 1069 GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \ 1070 dgettext ("gnunet", \ 1071 "External protocol violation detected at %s:%d.\n"), \ 1072 __FILE__, \ 1073 __LINE__); \ 1074 } \ 1075 } while (0) 1076 1077 1078 /** 1079 * @ingroup logging 1080 * Log an error message at log-level 'level' that indicates 1081 * a failure of the command 'cmd' with the message given 1082 * by strerror(errno). 1083 */ 1084 #define GNUNET_log_strerror(level, cmd) \ 1085 do \ 1086 { \ 1087 GNUNET_log (level, \ 1088 dgettext ("gnunet", \ 1089 "`%s' failed at %s:%d with error: %s\n"), \ 1090 cmd, \ 1091 __FILE__, \ 1092 __LINE__, \ 1093 strerror (errno)); \ 1094 } while (0) 1095 1096 1097 /** 1098 * @ingroup logging 1099 * Log an error message at log-level 'level' that indicates 1100 * a failure of the command 'cmd' with the message given 1101 * by strerror(errno). 1102 */ 1103 #define GNUNET_log_from_strerror(level, component, cmd) \ 1104 do \ 1105 { \ 1106 GNUNET_log_from (level, \ 1107 component, \ 1108 dgettext ("gnunet", \ 1109 "`%s' failed at %s:%d with error: %s\n"), \ 1110 cmd, \ 1111 __FILE__, \ 1112 __LINE__, \ 1113 strerror (errno)); \ 1114 } while (0) 1115 1116 1117 /** 1118 * @ingroup logging 1119 * Log an error message at log-level 'level' that indicates 1120 * a failure of the command 'cmd' with the message given 1121 * by strerror(errno). 1122 */ 1123 #define GNUNET_log_strerror_file(level, cmd, filename) \ 1124 do \ 1125 { \ 1126 GNUNET_log (level, \ 1127 dgettext ("gnunet", \ 1128 "`%s' failed on file `%s' at %s:%d with error: %s\n"), \ 1129 cmd, \ 1130 filename, \ 1131 __FILE__, \ 1132 __LINE__, \ 1133 strerror (errno)); \ 1134 } while (0) 1135 1136 1137 /** 1138 * @ingroup logging 1139 * Log an error message at log-level 'level' that indicates 1140 * a failure of the command 'cmd' with the message given 1141 * by strerror(errno). 1142 */ 1143 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) \ 1144 do \ 1145 { \ 1146 GNUNET_log_from (level, \ 1147 component, \ 1148 dgettext ("gnunet", \ 1149 "`%s' failed on file `%s' at %s:%d with error: %s\n"), \ 1150 cmd, \ 1151 filename, \ 1152 __FILE__, \ 1153 __LINE__, \ 1154 strerror (errno)); \ 1155 } while (0) 1156 1157 /* ************************* endianness conversion ****************** */ 1158 1159 #ifdef htobe64 1160 1161 #define GNUNET_htonll(n) htobe64 (n) 1162 1163 #else 1164 /** 1165 * Convert unsigned 64-bit integer to network byte order. 1166 * 1167 * @param n 1168 * The value in host byte order. 1169 * 1170 * @return The same value in network byte order. 1171 */ 1172 uint64_t 1173 GNUNET_htonll (uint64_t n); 1174 1175 #endif 1176 1177 1178 #ifdef be64toh 1179 1180 #define GNUNET_ntohll(n) be64toh (n) 1181 1182 #else 1183 /** 1184 * Convert unsigned 64-bit integer to host byte order. 1185 * 1186 * @param n 1187 * The value in network byte order. 1188 * 1189 * @return The same value in host byte order. 1190 */ 1191 uint64_t 1192 GNUNET_ntohll (uint64_t n); 1193 1194 #endif 1195 1196 1197 /** 1198 * Convert double to network byte order. 1199 * 1200 * @param d 1201 * The value in host byte order. 1202 * 1203 * @return The same value in network byte order. 1204 */ 1205 double 1206 GNUNET_hton_double (double d); 1207 1208 1209 /** 1210 * Convert double to host byte order 1211 * 1212 * @param d 1213 * The value in network byte order. 1214 * 1215 * @return The same value in host byte order. 1216 */ 1217 double 1218 GNUNET_ntoh_double (double d); 1219 1220 1221 /* ************************* allocation functions ****************** */ 1222 1223 /** 1224 * @ingroup memory 1225 * Maximum allocation with GNUNET_malloc macro. 1226 */ 1227 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40) 1228 1229 /** 1230 * @ingroup memory 1231 * Allocate a struct or union of the given @a type. 1232 * Wrapper around #GNUNET_malloc that returns a pointer 1233 * to the newly created object of the correct type. 1234 * 1235 * @param type name of the struct or union, i.e. pass 'struct Foo'. 1236 */ 1237 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof(type)) 1238 1239 1240 /** 1241 * Compare memory in @a a and @a b, where both must be of 1242 * the same pointer type. 1243 * 1244 * Do NOT use this function on arrays, it would only compare 1245 * the first element! 1246 */ 1247 #define GNUNET_memcmp(a, b) \ 1248 ({ \ 1249 const typeof (*b) * _a = (a); \ 1250 const typeof (*a) * _b = (b); \ 1251 memcmp (_a, _b, sizeof(*a)); \ 1252 }) 1253 1254 1255 /** 1256 * Compare memory in @a b1 and @a b2 in constant time, suitable for private 1257 * data. 1258 * 1259 * @param b1 some buffer of size @a len 1260 * @param b2 another buffer of size @a len 1261 * @param len number of bytes in @a b1 and @a b2 1262 * @return 0 if buffers are equal, 1263 */ 1264 int 1265 GNUNET_memcmp_ct_ (const void *b1, 1266 const void *b2, 1267 size_t len); 1268 1269 /** 1270 * Compare memory in @a a and @a b in constant time, suitable for private 1271 * data. Both @a a and @a b must be of the same pointer type. 1272 * 1273 * Do NOT use this function on arrays, it would only compare 1274 * the first element! 1275 */ 1276 #define GNUNET_memcmp_priv(a, b) \ 1277 ({ \ 1278 const typeof (*b) * _a = (a); \ 1279 const typeof (*a) * _b = (b); \ 1280 GNUNET_memcmp_ct_ (_a, _b, sizeof(*a)); \ 1281 }) 1282 1283 1284 /** 1285 * Check that memory in @a a is all zeros. @a a must be a pointer. 1286 * 1287 * @param a pointer to @a n bytes which should be tested for the 1288 * entire memory being zero'ed out. 1289 * @param n number of bytes in @a to be tested 1290 * @return true if @a a is zero, false_NO otherwise 1291 */ 1292 bool 1293 GNUNET_is_zero_ (const void *a, 1294 size_t n); 1295 1296 1297 /** 1298 * Check that memory in @a a is all zeros. @a a must be a pointer. 1299 * 1300 * @param a pointer to a struct which should be tested for the 1301 * entire memory being zero'ed out. 1302 * @return GNUNET_YES if a is zero, GNUNET_NO otherwise 1303 */ 1304 #define GNUNET_is_zero(a) \ 1305 GNUNET_is_zero_ ((a), sizeof (*(a))) 1306 1307 1308 /** 1309 * Call memcpy() but check for @a n being 0 first. In the latter 1310 * case, it is now safe to pass NULL for @a src or @a dst. 1311 * Unlike traditional memcpy(), returns nothing. 1312 * 1313 * @param dst destination of the copy, may be NULL if @a n is zero 1314 * @param src source of the copy, may be NULL if @a n is zero 1315 * @param n number of bytes to copy 1316 */ 1317 #define GNUNET_memcpy(dst, src, n) \ 1318 do \ 1319 { \ 1320 if (0 != n) \ 1321 { \ 1322 (void) memcpy (dst, src, n); \ 1323 } \ 1324 } while (0) 1325 1326 1327 /* *INDENT-OFF* */ 1328 /** 1329 * @ingroup memory 1330 * Allocate a size @a n array with structs or unions of the given @a type. 1331 * Wrapper around #GNUNET_malloc that returns a pointer 1332 * to the newly created objects of the correct type. 1333 * 1334 * @param n number of elements in the array 1335 * @param type name of the struct or union, i.e. pass 'struct Foo'. 1336 */ 1337 #define GNUNET_new_array(n, type) ({ \ 1338 GNUNET_assert (SIZE_MAX / sizeof (type) >= n); \ 1339 (type *) GNUNET_malloc ((n) * sizeof(type)); \ 1340 }) 1341 /* *INDENT-ON* */ 1342 1343 /** 1344 * @ingroup memory 1345 * Wrapper around malloc. Allocates size bytes of memory. 1346 * The memory will be zero'ed out. 1347 * 1348 * @param size the number of bytes to allocate, must be 1349 * smaller than 40 MB. 1350 * @return pointer to size bytes of memory, never NULL (!) 1351 */ 1352 #define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__) 1353 1354 /** 1355 * @ingroup memory 1356 * Allocate and initialize a block of memory. 1357 * 1358 * @param buf data to initialize the block with 1359 * @param size the number of bytes in buf (and size of the allocation) 1360 * @return pointer to size bytes of memory, never NULL (!) 1361 */ 1362 #define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__) 1363 1364 /** 1365 * @ingroup memory 1366 * Wrapper around malloc. Allocates size bytes of memory. 1367 * The memory will be zero'ed out. 1368 * 1369 * @param size the number of bytes to allocate 1370 * @return pointer to size bytes of memory, NULL if we do not have enough memory 1371 */ 1372 #define GNUNET_malloc_large(size) \ 1373 GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__) 1374 1375 1376 /** 1377 * @ingroup memory 1378 * Wrapper around realloc. Reallocates size bytes of memory. 1379 * The content of the intersection of the new and old size will be unchanged. 1380 * 1381 * @param ptr the pointer to reallocate 1382 * @param size the number of bytes to reallocate 1383 * @return pointer to size bytes of memory 1384 */ 1385 #define GNUNET_realloc(ptr, size) \ 1386 GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__) 1387 1388 1389 /** 1390 * @ingroup memory 1391 * Wrapper around free. Frees the memory referred to by ptr. 1392 * Note that it is generally better to free memory that was 1393 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free_nz. 1394 * 1395 * @param ptr location where to free the memory. ptr must have 1396 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier. NULL is allowed. 1397 */ 1398 #define GNUNET_free_nz(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__) 1399 1400 1401 /** 1402 * @ingroup memory 1403 * Wrapper around free. Frees the memory referred to by ptr and sets ptr to NULL. 1404 * Note that it is generally better to free memory that was 1405 * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free. 1406 * 1407 * @a ptr will be set to NULL. Use #GNUNET_free_nz() if @a ptr is not an L-value. 1408 * 1409 * @param ptr location where to free the memory. ptr must have 1410 * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier. NULL is allowed. 1411 */ 1412 #define GNUNET_free(ptr) do { \ 1413 GNUNET_xfree_ (ptr, __FILE__, __LINE__); \ 1414 ptr = NULL; \ 1415 } while (0) 1416 1417 1418 /** 1419 * @ingroup memory 1420 * Wrapper around #GNUNET_xstrdup_. Makes a copy of the zero-terminated string 1421 * pointed to by a. 1422 * 1423 * @param a pointer to a zero-terminated string 1424 * @return a copy of the string including zero-termination 1425 */ 1426 #define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__) 1427 1428 1429 /** 1430 * @ingroup memory 1431 * Wrapper around #GNUNET_xstrndup_. Makes a partial copy of the string 1432 * pointed to by a. 1433 * 1434 * @param a pointer to a string 1435 * @param length of the string to duplicate 1436 * @return a partial copy of the string including zero-termination 1437 */ 1438 #define GNUNET_strndup(a, length) \ 1439 GNUNET_xstrndup_ (a, length, __FILE__, __LINE__) 1440 1441 /** 1442 * @ingroup memory 1443 * Grow a well-typed (!) array. This is a convenience 1444 * method to grow a vector @a arr of size @a size 1445 * to the new (target) size @a tsize. 1446 * <p> 1447 * 1448 * Example (simple, well-typed stack): 1449 * 1450 * <pre> 1451 * static struct foo * myVector = NULL; 1452 * static int myVecLen = 0; 1453 * 1454 * static void push(struct foo * elem) { 1455 * GNUNET_array_grow(myVector, myVecLen, myVecLen+1); 1456 * GNUNET_memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo)); 1457 * } 1458 * 1459 * static void pop(struct foo * elem) { 1460 * if (myVecLen == 0) die(); 1461 * GNUNET_memcpy(elem, myVector[myVecLen-1], sizeof(struct foo)); 1462 * GNUNET_array_grow(myVector, myVecLen, myVecLen-1); 1463 * } 1464 * </pre> 1465 * 1466 * @param arr base-pointer of the vector, may be NULL if size is 0; 1467 * will be updated to reflect the new address. The TYPE of 1468 * arr is important since size is the number of elements and 1469 * not the size in bytes 1470 * @param size the number of elements in the existing vector (number 1471 * of elements to copy over), will be updated with the new 1472 * array size 1473 * @param tsize the target size for the resulting vector, use 0 to 1474 * free the vector (then, arr will be NULL afterwards). 1475 */ 1476 #define GNUNET_array_grow(arr, size, tsize) \ 1477 GNUNET_xgrow_ ((void **) &(arr), \ 1478 sizeof((arr)[0]), \ 1479 &size, \ 1480 tsize, \ 1481 __FILE__, \ 1482 __LINE__) 1483 1484 /** 1485 * @ingroup memory 1486 * Append an element to an array (growing the array by one). 1487 * 1488 * @param arr base-pointer of the vector, may be NULL if @a len is 0; 1489 * will be updated to reflect the new address. The TYPE of 1490 * arr is important since size is the number of elements and 1491 * not the size in bytes 1492 * @param len the number of elements in the existing vector (number 1493 * of elements to copy over), will be updated with the new 1494 * array length 1495 * @param element the element that will be appended to the array 1496 */ 1497 #define GNUNET_array_append(arr, len, element) \ 1498 do \ 1499 { \ 1500 GNUNET_assert ((len) + 1 > (len)); \ 1501 GNUNET_array_grow (arr, len, len + 1); \ 1502 (arr) [len - 1] = element; \ 1503 } while (0) 1504 1505 1506 /** 1507 * @ingroup memory 1508 * Append @a arr2 to @a arr1 (growing @a arr1 1509 * as needed). The @a arr2 array is left unchanged. Naturally 1510 * this function performs a shallow copy. Both arrays must have 1511 * the same type for their elements. 1512 * 1513 * @param arr1 base-pointer of the vector, may be NULL if @a len is 0; 1514 * will be updated to reflect the new address. The TYPE of 1515 * arr is important since size is the number of elements and 1516 * not the size in bytes 1517 * @param len1 the number of elements in the existing vector (number 1518 * of elements to copy over), will be updated with the new 1519 * array size 1520 * @param arr2 base-pointer a second array to concatenate, may be NULL if @a len2 is 0; 1521 * will be updated to reflect the new address. The TYPE of 1522 * arr is important since size is the number of elements and 1523 * not the size in bytes 1524 * @param len2 the number of elements in the existing vector (number 1525 * of elements to copy over), will be updated with the new 1526 * array size 1527 1528 */ 1529 #define GNUNET_array_concatenate(arr1, len1, arr2, len2) \ 1530 do \ 1531 { \ 1532 const typeof (*arr2) * _a1 = (arr1); \ 1533 const typeof (*arr1) * _a2 = (arr2); \ 1534 GNUNET_assert ((len1) + (len2) >= (len1)); \ 1535 GNUNET_assert (SIZE_MAX / sizeof (*_a1) >= ((len1) + (len2))); \ 1536 GNUNET_array_grow (arr1, len1, (len1) + (len2)); \ 1537 memcpy (&(arr1) [(len1) - (len2)], _a2, (len2) * sizeof (*arr1)); \ 1538 } while (0) 1539 1540 1541 /** 1542 * @ingroup memory 1543 * Like snprintf, just aborts if the buffer is of insufficient size. 1544 * 1545 * @param buf pointer to buffer that is written to 1546 * @param size number of bytes in @a buf 1547 * @param format format strings 1548 * @param ... data for format string 1549 * @return number of bytes written to buf or negative value on error 1550 */ 1551 int 1552 GNUNET_snprintf (char *buf, 1553 size_t size, 1554 const char *format, 1555 ...) 1556 __attribute__ ((format (printf, 3, 4))); 1557 1558 1559 /** 1560 * @ingroup memory 1561 * Like asprintf, just portable. 1562 * 1563 * @param buf set to a buffer of sufficient size (allocated, caller must free) 1564 * @param format format string (see printf, fprintf, etc.) 1565 * @param ... data for format string 1566 * @return number of bytes in "*buf" excluding 0-termination 1567 */ 1568 int 1569 GNUNET_asprintf (char **buf, 1570 const char *format, 1571 ...) 1572 __attribute__ ((format (printf, 2, 3))); 1573 1574 1575 /* ************** internal implementations, use macros above! ************** */ 1576 1577 /** 1578 * Allocate memory. Checks the return value, aborts if no more 1579 * memory is available. Don't use GNUNET_xmalloc_ directly. Use the 1580 * #GNUNET_malloc macro. 1581 * The memory will be zero'ed out. 1582 * 1583 * @param size number of bytes to allocate 1584 * @param filename where is this call being made (for debugging) 1585 * @param linenumber line where this call is being made (for debugging) 1586 * @return allocated memory, never NULL 1587 */ 1588 void * 1589 GNUNET_xmalloc_ (size_t size, 1590 const char *filename, 1591 int linenumber); 1592 1593 1594 /** 1595 * Allocate and initialize memory. Checks the return value, aborts if no more 1596 * memory is available. Don't use GNUNET_xmemdup_ directly. Use the 1597 * #GNUNET_memdup macro. 1598 * 1599 * @param buf buffer to initialize from (must contain size bytes) 1600 * @param size number of bytes to allocate 1601 * @param filename where is this call being made (for debugging) 1602 * @param linenumber line where this call is being made (for debugging) 1603 * @return allocated memory, never NULL 1604 */ 1605 void * 1606 GNUNET_xmemdup_ (const void *buf, 1607 size_t size, 1608 const char *filename, 1609 int linenumber); 1610 1611 1612 /** 1613 * Allocate memory. This function does not check if the allocation 1614 * request is within reasonable bounds, allowing allocations larger 1615 * than 40 MB. If you don't expect the possibility of very large 1616 * allocations, use #GNUNET_malloc instead. The memory will be zero'ed 1617 * out. 1618 * 1619 * @param size number of bytes to allocate 1620 * @param filename where is this call being made (for debugging) 1621 * @param linenumber line where this call is being made (for debugging) 1622 * @return pointer to size bytes of memory, NULL if we do not have enough memory 1623 */ 1624 void * 1625 GNUNET_xmalloc_unchecked_ (size_t size, 1626 const char *filename, 1627 int linenumber); 1628 1629 1630 /** 1631 * Reallocate memory. Checks the return value, aborts if no more 1632 * memory is available. 1633 */ 1634 void * 1635 GNUNET_xrealloc_ (void *ptr, 1636 size_t n, 1637 const char *filename, 1638 int linenumber); 1639 1640 1641 /** 1642 * Free memory. Merely a wrapper for the case that we 1643 * want to keep track of allocations. Don't use GNUNET_xfree_ 1644 * directly. Use the #GNUNET_free macro. 1645 * 1646 * @param ptr pointer to memory to free 1647 * @param filename where is this call being made (for debugging) 1648 * @param linenumber line where this call is being made (for debugging) 1649 */ 1650 void 1651 GNUNET_xfree_ (void *ptr, 1652 const char *filename, 1653 int linenumber); 1654 1655 1656 /** 1657 * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro. 1658 * @param str string to duplicate 1659 * @param filename where is this call being made (for debugging) 1660 * @param linenumber line where this call is being made (for debugging) 1661 * @return the duplicated string 1662 */ 1663 char * 1664 GNUNET_xstrdup_ (const char *str, 1665 const char *filename, 1666 int linenumber); 1667 1668 /** 1669 * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro. 1670 * 1671 * @param str string to duplicate 1672 * @param len length of the string to duplicate 1673 * @param filename where is this call being made (for debugging) 1674 * @param linenumber line where this call is being made (for debugging) 1675 * @return the duplicated string 1676 */ 1677 char * 1678 GNUNET_xstrndup_ (const char *str, 1679 size_t len, 1680 const char *filename, 1681 int linenumber); 1682 1683 /** 1684 * Grow an array, the new elements are zeroed out. 1685 * Grows old by (*oldCount-newCount)*elementSize 1686 * bytes and sets *oldCount to newCount. 1687 * 1688 * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro. 1689 * 1690 * @param old address of the pointer to the array 1691 * *old may be NULL 1692 * @param elementSize the size of the elements of the array 1693 * @param oldCount address of the number of elements in the *old array 1694 * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards) 1695 * @param filename where is this call being made (for debugging) 1696 * @param linenumber line where this call is being made (for debugging) 1697 */ 1698 void 1699 GNUNET_xgrow_ (void **old, 1700 size_t elementSize, 1701 unsigned int *oldCount, 1702 unsigned int newCount, 1703 const char *filename, 1704 int linenumber); 1705 1706 1707 /** 1708 * @ingroup memory 1709 * Create a copy of the given message. 1710 * 1711 * @param msg message to copy 1712 * @return duplicate of the message 1713 */ 1714 struct GNUNET_MessageHeader * 1715 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg); 1716 1717 1718 /** 1719 * Set the async scope for the current thread. 1720 * 1721 * @param aid the async scope identifier 1722 * @param[out] old_scope location to save the old scope 1723 */ 1724 void 1725 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid, 1726 struct GNUNET_AsyncScopeSave *old_scope); 1727 1728 1729 /** 1730 * Clear the current thread's async scope. 1731 * 1732 * @param old_scope scope to restore 1733 */ 1734 void 1735 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope); 1736 1737 1738 /** 1739 * Get the current async scope. 1740 * 1741 * @param[out] scope_ret pointer to where the result is stored 1742 */ 1743 void 1744 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret); 1745 1746 1747 /** 1748 * Generate a fresh async scope identifier. 1749 * 1750 * @param[out] aid_ret pointer to where the result is stored 1751 */ 1752 void 1753 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret); 1754 1755 1756 #if __STDC_VERSION__ < 199901L 1757 #if __GNUC__ >= 2 1758 #define __func__ __FUNCTION__ 1759 #else 1760 #define __func__ "<unknown>" 1761 #endif 1762 #endif 1763 1764 1765 /** 1766 * Valid task priorities. Use these, do not pass random integers! 1767 * For various reasons (#3862 -- building with QT Creator, and 1768 * our restricted cross-compilation with emscripten) this cannot 1769 * be in gnunet_scheduler_lib.h, but it works if we declare it here. 1770 * Naturally, logically this is part of the scheduler. 1771 */ 1772 enum GNUNET_SCHEDULER_Priority 1773 { 1774 /** 1775 * Run with the same priority as the current job. 1776 */ 1777 GNUNET_SCHEDULER_PRIORITY_KEEP = 0, 1778 1779 /** 1780 * Run when otherwise idle. 1781 */ 1782 GNUNET_SCHEDULER_PRIORITY_IDLE = 1, 1783 1784 /** 1785 * Run as background job (higher than idle, 1786 * lower than default). 1787 */ 1788 GNUNET_SCHEDULER_PRIORITY_BACKGROUND = 2, 1789 1790 /** 1791 * Run with the default priority (normal 1792 * P2P operations). Any task that is scheduled 1793 * without an explicit priority being specified 1794 * will run with this priority. 1795 */ 1796 GNUNET_SCHEDULER_PRIORITY_DEFAULT = 3, 1797 1798 /** 1799 * Run with high priority (important requests). 1800 * Higher than DEFAULT. 1801 */ 1802 GNUNET_SCHEDULER_PRIORITY_HIGH = 4, 1803 1804 /** 1805 * Run with priority for interactive tasks. 1806 * Higher than "HIGH". 1807 */ 1808 GNUNET_SCHEDULER_PRIORITY_UI = 5, 1809 1810 /** 1811 * Run with priority for urgent tasks. Use 1812 * for things like aborts and shutdowns that 1813 * need to preempt "UI"-level tasks. 1814 * Higher than "UI". 1815 */ 1816 GNUNET_SCHEDULER_PRIORITY_URGENT = 6, 1817 1818 /** 1819 * This is an internal priority level that is only used for tasks 1820 * that are being triggered due to shutdown (they have automatically 1821 * highest priority). User code must not use this priority level 1822 * directly. Tasks run with this priority level that internally 1823 * schedule other tasks will see their original priority level 1824 * be inherited (unless otherwise specified). 1825 */ 1826 GNUNET_SCHEDULER_PRIORITY_SHUTDOWN = 7, 1827 1828 /** 1829 * Number of priorities (must be the last priority). 1830 * This priority must not be used by clients. 1831 */ 1832 GNUNET_SCHEDULER_PRIORITY_COUNT = 8 1833 }; 1834 1835 1836 /* *INDENT-OFF* */ 1837 1838 #if 0 /* keep Emacsens' auto-indent happy */ 1839 { 1840 #endif 1841 #ifdef __cplusplus 1842 } 1843 #endif 1844 1845 #endif /* GNUNET_COMMON_H */