2 This file is part of GNUnet.
3 Copyright (C) 2006-2013 GNUnet e.V.
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.
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.
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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/common_logging.c
23 * @brief error handling API
24 * @author Christian Grothoff
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_disk_lib.h"
29 #include "gnunet_strings_lib.h"
34 * After how many milliseconds do we always print
35 * that "message X was repeated N times"? Use 12h.
37 #define BULK_DELAY_THRESHOLD (12 * 60 * 60 * 1000LL * 1000LL)
40 * After how many repetitions do we always print
41 * that "message X was repeated N times"? (even if
42 * we have not yet reached the delay threshold)
44 #define BULK_REPEAT_THRESHOLD 1000
47 * How many characters do we use for matching of
50 #define BULK_TRACK_SIZE 256
53 * How many characters do we use for matching of
56 #define COMP_TRACK_SIZE 32
59 * How many characters can a date/time string
62 #define DATE_STR_SIZE 64
65 * How many log files to keep?
67 #define ROTATION_KEEP 3
71 * Assumed maximum path length (for the log file name).
78 * Linked list of active loggers.
83 * This is a linked list.
85 struct CustomLogger *next;
100 * Asynchronous scope of the current thread, or NULL if we have not
101 * entered an async scope yet.
103 static __thread struct GNUNET_AsyncScopeSave current_async_scope;
106 * The last "bulk" error message that we have been logging.
107 * Note that this message maybe truncated to the first BULK_TRACK_SIZE
108 * characters, in which case it is NOT 0-terminated!
110 static GNUNET_THREAD_LOCAL char last_bulk[BULK_TRACK_SIZE] __nonstring;
113 * Type of the last bulk message.
115 static GNUNET_THREAD_LOCAL enum GNUNET_ErrorType last_bulk_kind;
118 * Time of the last bulk error message (0 for none)
120 static GNUNET_THREAD_LOCAL struct GNUNET_TIME_Absolute last_bulk_time;
123 * Number of times that bulk message has been repeated since.
125 static GNUNET_THREAD_LOCAL unsigned int last_bulk_repeat;
128 * Component when the last bulk was logged. Will be 0-terminated.
130 static GNUNET_THREAD_LOCAL char last_bulk_comp[COMP_TRACK_SIZE + 1];
135 static char *component;
138 * Running component (without pid).
140 static char *component_nopid;
143 * Format string describing the name of the log file.
145 static char *log_file_name;
150 static enum GNUNET_ErrorType min_level;
153 * Linked list of our custom loggres.
155 static struct CustomLogger *loggers;
158 * Number of log calls to ignore.
160 static GNUNET_THREAD_LOCAL int skip_log = 0;
163 * File descriptor to use for "stderr", or NULL for none.
165 static FILE *GNUNET_stderr;
168 * Represents a single logging definition
173 * Component name regex
175 regex_t component_regex;
183 * Function name regex
185 regex_t function_regex;
188 * Lowest line at which this definition matches.
189 * Defaults to 0. Must be <= to_line.
194 * Highest line at which this definition matches.
195 * Defaults to INT_MAX. Must be >= from_line.
200 * Maximal log level allowed for calls that match this definition.
201 * Calls with higher log level will be disabled.
207 * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
208 * overrides any configuration options. 0 otherwise.
214 #if ! defined(GNUNET_CULL_LOGGING)
216 * Dynamic array of logging definitions
218 static struct LogDef *logdefs;
221 * Allocated size of logdefs array (in units)
223 static int logdefs_size;
226 * The number of units used in logdefs array.
228 static int logdefs_len;
231 * #GNUNET_YES if GNUNET_LOG environment variable is already parsed.
233 static int gnunet_log_parsed;
236 * #GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
238 static int gnunet_force_log_parsed;
241 * #GNUNET_YES if at least one definition with forced == 1 is available.
243 static int gnunet_force_log_present;
248 * Convert a textual description of a loglevel
249 * to the respective GNUNET_GE_KIND.
251 * @param log loglevel to parse
252 * @return GNUNET_GE_INVALID if log does not parse
254 static enum GNUNET_ErrorType
255 get_type (const char *log)
258 return GNUNET_ERROR_TYPE_UNSPECIFIED;
259 if (0 == strcasecmp (log, _ ("DEBUG")))
260 return GNUNET_ERROR_TYPE_DEBUG;
261 if (0 == strcasecmp (log, _ ("INFO")))
262 return GNUNET_ERROR_TYPE_INFO;
263 if (0 == strcasecmp (log, _ ("MESSAGE")))
264 return GNUNET_ERROR_TYPE_MESSAGE;
265 if (0 == strcasecmp (log, _ ("WARNING")))
266 return GNUNET_ERROR_TYPE_WARNING;
267 if (0 == strcasecmp (log, _ ("ERROR")))
268 return GNUNET_ERROR_TYPE_ERROR;
269 if (0 == strcasecmp (log, _ ("NONE")))
270 return GNUNET_ERROR_TYPE_NONE;
271 return GNUNET_ERROR_TYPE_INVALID;
276 * Abort the process, generate a core dump if possible.
285 #if ! defined(GNUNET_CULL_LOGGING)
287 * Utility function - reallocates logdefs array to be twice as large.
292 logdefs_size = (logdefs_size + 1) * 2;
293 logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof(struct LogDef));
298 * Rotate logs, deleting the oldest log.
300 * @param new_name new name to add to the rotation
303 log_rotate (const char *new_name)
305 static char *rotation[ROTATION_KEEP];
306 static unsigned int rotation_off;
309 if ('\0' == *new_name)
310 return; /* not a real log file name */
311 discard = rotation[rotation_off % ROTATION_KEEP];
314 /* Note: can't log errors during logging (recursion!), so this
315 operation MUST silently fail... */
316 (void) unlink (discard);
317 GNUNET_free (discard);
319 rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup (new_name);
325 * Setup the log file.
327 * @param tm timestamp for which we should setup logging
328 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
331 setup_log_file (const struct tm *tm)
333 static char last_fn[PATH_MAX + 1];
334 char fn[PATH_MAX + 1];
340 if (NULL == log_file_name)
341 return GNUNET_SYSERR;
342 if (0 == strftime (fn, sizeof(fn), log_file_name, tm))
343 return GNUNET_SYSERR;
344 leftsquare = strrchr (fn, '[');
345 if ((NULL != leftsquare) && (']' == leftsquare[1]))
347 char *logfile_copy = GNUNET_strdup (fn);
349 logfile_copy[leftsquare - fn] = '\0';
350 logfile_copy[leftsquare - fn + 1] = '\0';
356 &logfile_copy[leftsquare - fn + 2]);
357 GNUNET_free (logfile_copy);
359 if (0 == strcmp (fn, last_fn))
360 return GNUNET_OK; /* no change */
361 log_rotate (last_fn);
362 strcpy (last_fn, fn);
363 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (fn))
366 "Failed to create directory for `%s': %s\n",
369 return GNUNET_SYSERR;
371 altlog_fd = open (fn,
372 O_APPEND | O_WRONLY | O_CREAT,
373 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
377 if (NULL != GNUNET_stderr)
378 fclose (GNUNET_stderr);
379 dup_return = dup2 (altlog_fd, 2);
380 (void) close (altlog_fd);
381 if (-1 != dup_return)
383 altlog = fdopen (2, "ab");
397 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
398 return GNUNET_SYSERR;
400 GNUNET_stderr = altlog;
406 * Utility function - adds a parsed definition to logdefs array.
408 * @param component see struct LogDef, can't be NULL
409 * @param file see struct LogDef, can't be NULL
410 * @param function see struct LogDef, can't be NULL
411 * @param from_line see struct LogDef
412 * @param to_line see struct LogDef
413 * @param level see struct LogDef, must be >= 0
414 * @param force see struct LogDef
415 * @return 0 on success, regex-specific error otherwise
418 add_definition (const char *component,
420 const char *function,
429 if (logdefs_size == logdefs_len)
431 memset (&n, 0, sizeof(n));
432 if (0 == strlen (component))
433 component = (char *) ".*";
434 r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
439 if (0 == strlen (file))
440 file = (char *) ".*";
441 r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
444 regfree (&n.component_regex);
447 if ((NULL == function) || (0 == strlen (function)))
448 function = (char *) ".*";
449 r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
452 regfree (&n.component_regex);
453 regfree (&n.file_regex);
456 n.from_line = from_line;
460 logdefs[logdefs_len++] = n;
466 * Decides whether a particular logging call should or should not be allowed
467 * to be made. Used internally by GNUNET_log*()
469 * @param caller_level loglevel the caller wants to use
470 * @param comp component name the caller uses (NULL means that global
471 * component name is used)
472 * @param file file name containing the logging call, usually __FILE__
473 * @param function function which tries to make a logging call,
474 * usually __FUNCTION__
475 * @param line line at which the call is made, usually __LINE__
476 * @return 0 to disallow the call, 1 to allow it
479 GNUNET_get_log_call_status (int caller_level,
482 const char *function,
490 /* Use default component */
491 comp = component_nopid;
493 /* We have no definitions to override globally configured log level,
494 * so just use it right away.
496 if ((min_level >= 0) && (GNUNET_NO == gnunet_force_log_present))
497 return caller_level <= min_level;
499 /* Only look for forced definitions? */
500 force_only = min_level >= 0;
501 for (i = 0; i < logdefs_len; i++)
504 if (((! force_only) || ld->force) &&
505 ((line >= ld->from_line) && (line <= ld->to_line) ) &&
506 (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
507 (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
508 (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
511 return caller_level <= ld->level;
514 /* No matches - use global level, if defined */
516 return caller_level <= min_level;
517 /* All programs/services previously defaulted to WARNING.
518 * Now *we* default to WARNING, and THEY default to NULL.
519 * Or rather we default to MESSAGE, since things aren't always bad.
521 return caller_level <= GNUNET_ERROR_TYPE_MESSAGE;
526 * Utility function - parses a definition
529 * component;file;function;from_line-to_line;level[/component...]
530 * All entries are mandatory, but may be empty.
531 * Empty entries for component, file and function are treated as
532 * "matches anything".
533 * Empty line entry is treated as "from 0 to INT_MAX"
534 * Line entry with only one line is treated as "this line only"
535 * Entry for level MUST NOT be empty.
536 * Entries for component, file and function that consist of a
537 * single character "*" are treated (at the moment) the same way
538 * empty entries are treated (wildcard matching is not implemented (yet?)).
539 * file entry is matched to the end of __FILE__. That is, it might be
540 * a base name, or a base name with leading directory names (some compilers
541 * define __FILE__ to absolute file path).
543 * @param constname name of the environment variable from which to get the
544 * string to be parsed
545 * @param force 1 if definitions found in constname are to be forced
546 * @return number of added definitions
549 parse_definitions (const char *constname, int force)
555 char *function = NULL;
561 int from_line, to_line;
563 int keep_looking = 1;
565 tmp = getenv (constname);
568 def = GNUNET_strdup (tmp);
571 for (p = def, state = 0, start = def; keep_looking; p++)
575 case ';': /* found a field separator */
579 case 0: /* within a component name */
583 case 1: /* within a file name */
587 case 2: /* within a function name */
588 /* after a file name there must be a function name */
592 case 3: /* within a from-to line range */
593 if (strlen (start) > 0)
596 from_line = strtol (start, &t, 10);
597 if ((0 != errno) || (from_line < 0))
602 if ((t < p) && ('-' == t[0]))
606 to_line = strtol (start, &t, 10);
607 if ((0 != errno) || (to_line < 0) || (t != p))
613 else /* one number means "match this line only" */
616 else /* default to 0-max */
626 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
634 case '\0': /* found EOL */
637 /* fall through to '/' */
638 case '/': /* found a definition separator */
641 case 4: /* within a log level */
644 level = get_type ((const char *) start);
645 if ((GNUNET_ERROR_TYPE_INVALID == level) ||
646 (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
647 (0 != add_definition (comp,
665 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
680 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
683 parse_all_definitions ()
685 if (GNUNET_NO == gnunet_force_log_parsed)
686 gnunet_force_log_present =
687 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
688 gnunet_force_log_parsed = GNUNET_YES;
690 if (GNUNET_NO == gnunet_log_parsed)
691 parse_definitions ("GNUNET_LOG", 0);
692 gnunet_log_parsed = GNUNET_YES;
702 * @param comp default component to use
703 * @param loglevel what types of messages should be logged
704 * @param logfile which file to write log messages to (can be NULL)
705 * @return #GNUNET_OK on success
708 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
710 const char *env_logfile;
712 min_level = get_type (loglevel);
713 #if ! defined(GNUNET_CULL_LOGGING)
714 parse_all_definitions ();
716 GNUNET_free_non_null (component);
717 GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
718 GNUNET_free_non_null (component_nopid);
719 component_nopid = GNUNET_strdup (comp);
721 env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
722 if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
723 logfile = env_logfile;
726 GNUNET_free_non_null (log_file_name);
727 log_file_name = GNUNET_STRINGS_filename_expand (logfile);
728 if (NULL == log_file_name)
729 return GNUNET_SYSERR;
730 #if defined(GNUNET_CULL_LOGGING)
731 /* log file option not allowed for wallet logic */
732 GNUNET_assert (NULL == logfile);
741 return setup_log_file (tm);
748 * Add a custom logger. Note that installing any custom logger
749 * will disable the standard logger. When multiple custom loggers
750 * are installed, all will be called. The standard logger will
751 * only be used if no custom loggers are present.
753 * @param logger log function
754 * @param logger_cls closure for @a logger
757 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
759 struct CustomLogger *entry;
761 entry = GNUNET_new (struct CustomLogger);
762 entry->logger = logger;
763 entry->logger_cls = logger_cls;
764 entry->next = loggers;
770 * Remove a custom logger.
772 * @param logger log function
773 * @param logger_cls closure for @a logger
776 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
778 struct CustomLogger *pos;
779 struct CustomLogger *prev;
783 while ((NULL != pos) &&
784 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
789 GNUNET_assert (NULL != pos);
793 prev->next = pos->next;
799 * Actually output the log message.
801 * @param kind how severe was the issue
802 * @param comp component responsible
803 * @param datestr current date/time
804 * @param msg the actual message
807 output_message (enum GNUNET_ErrorType kind,
812 struct CustomLogger *pos;
814 /* only use the standard logger if no custom loggers are present */
815 if ((NULL != GNUNET_stderr) && (NULL == loggers))
817 if (kind == GNUNET_ERROR_TYPE_MESSAGE)
819 /* The idea here is to produce "normal" output messages
820 * for end users while still having the power of the
821 * logging engine for developer needs. So ideally this
822 * is what it should look like when CLI tools are used
823 * interactively, yet the same message shouldn't look
824 * this way if the output is going to logfiles or robots
826 */fprintf (GNUNET_stderr, "* %s", msg);
828 else if (GNUNET_YES == current_async_scope.have_scope)
830 static GNUNET_THREAD_LOCAL char id_buf[27];
833 /* We're logging, so skip_log must be currently 0. */
835 end = GNUNET_STRINGS_data_to_string (¤t_async_scope.scope_id,
836 sizeof(struct GNUNET_AsyncScopeId),
839 GNUNET_assert (NULL != end);
842 fprintf (GNUNET_stderr,
847 GNUNET_error_type_to_string (kind),
852 fprintf (GNUNET_stderr,
856 GNUNET_error_type_to_string (kind),
859 fflush (GNUNET_stderr);
864 pos->logger (pos->logger_cls, kind, comp, datestr, msg);
871 * Flush an existing bulk report to the output.
873 * @param datestr our current timestamp
876 flush_bulk (const char *datestr)
878 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
883 if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat))
886 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
888 last = &last_bulk[BULK_TRACK_SIZE - 1];
889 else if (last != last_bulk)
897 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (
902 _ ("Message `%.*s' repeated %u times in the last %s\n"),
909 output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
910 last_bulk_time = GNUNET_TIME_absolute_get ();
911 last_bulk_repeat = 0;
916 * Ignore the next n calls to the log function.
918 * @param n number of log calls to ignore (could be negative)
919 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
922 GNUNET_log_skip (int n, int check_reset)
928 ok = (0 == skip_log);
941 * Get the number of log calls that are going to be skipped
943 * @return number of log calls to be ignored
946 GNUNET_get_log_skip ()
953 * Output a log message using the default mechanism.
955 * @param kind how severe was the issue
956 * @param comp component responsible
957 * @param message the actual message
958 * @param va arguments to the format string "message"
961 mylog (enum GNUNET_ErrorType kind,
966 char date[DATE_STR_SIZE];
967 char date2[DATE_STR_SIZE];
973 size = vsnprintf (NULL, 0, message, vacp) + 1;
974 GNUNET_assert (0 != size);
976 memset (date, 0, DATE_STR_SIZE);
981 struct timeval timeofday;
983 gettimeofday (&timeofday, NULL);
984 offset = GNUNET_TIME_get_offset ();
987 timeofday.tv_sec += offset / 1000LL;
988 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
989 if (timeofday.tv_usec > 1000000LL)
991 timeofday.tv_usec -= 1000000LL;
997 timeofday.tv_sec += offset / 1000LL;
998 if (timeofday.tv_usec > -(offset % 1000LL) * 1000LL)
1000 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1004 timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
1008 tmptr = localtime (&timeofday.tv_sec);
1011 strcpy (date, "localtime error");
1015 if (0 == strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr))
1017 if (0 > snprintf (date, sizeof(date), date2, timeofday.tv_usec))
1021 vsnprintf (buf, size, message, va);
1022 #if ! defined(GNUNET_CULL_LOGGING)
1024 (void) setup_log_file (tmptr);
1026 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
1027 (0 != last_bulk_time.abs_value_us) &&
1028 (0 == strncmp (buf, last_bulk, sizeof(last_bulk))))
1031 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
1032 BULK_DELAY_THRESHOLD) ||
1033 (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
1038 GNUNET_strlcpy (last_bulk, buf, sizeof(last_bulk));
1039 last_bulk_repeat = 0;
1040 last_bulk_kind = kind;
1041 last_bulk_time = GNUNET_TIME_absolute_get ();
1042 GNUNET_strlcpy (last_bulk_comp, comp, sizeof(last_bulk_comp));
1043 output_message (kind, comp, date, buf);
1049 * Main log function.
1051 * @param kind how serious is the error?
1052 * @param message what is the message (format string)
1053 * @param ... arguments for format string
1056 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
1060 va_start (va, message);
1061 mylog (kind, component, message, va);
1067 * Log function that specifies an alternative component.
1068 * This function should be used by plugins.
1070 * @param kind how serious is the error?
1071 * @param comp component responsible for generating the message
1072 * @param message what is the message (format string)
1073 * @param ... arguments for format string
1076 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
1078 const char *message,
1082 char comp_w_pid[128];
1085 comp = component_nopid;
1087 va_start (va, message);
1088 GNUNET_snprintf (comp_w_pid, sizeof(comp_w_pid), "%s-%d", comp, getpid ());
1089 mylog (kind, comp_w_pid, message, va);
1095 * Convert error type to string.
1097 * @param kind type to convert
1098 * @return string corresponding to the type
1101 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1103 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1105 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1106 return _ ("WARNING");
1107 if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0)
1108 return _ ("MESSAGE");
1109 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1111 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1113 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1115 return _ ("INVALID");
1120 * Convert a hash to a string (for printing debug messages).
1122 * @param hc the hash code
1123 * @return string form; will be overwritten by next call to GNUNET_h2s.
1126 GNUNET_h2s (const struct GNUNET_HashCode *hc)
1128 static GNUNET_THREAD_LOCAL struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1130 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1131 ret.encoding[8] = '\0';
1132 return (const char *) ret.encoding;
1137 * Convert a hash to a string (for printing debug messages).
1138 * This is one of the very few calls in the entire API that is
1139 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
1140 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
1141 * used within the same log statement.
1143 * @param hc the hash code
1144 * @return string form; will be overwritten by next call to GNUNET_h2s.
1147 GNUNET_h2s2 (const struct GNUNET_HashCode *hc)
1149 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1151 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1152 ret.encoding[8] = '\0';
1153 return (const char *) ret.encoding;
1159 * Convert a public key value to a string (for printing debug messages).
1160 * This is one of the very few calls in the entire API that is
1163 * @param hc the hash code
1167 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1169 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1170 struct GNUNET_HashCode hc;
1172 GNUNET_CRYPTO_hash (p, sizeof(*p), &hc);
1173 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1174 ret.encoding[6] = '\0';
1175 return (const char *) ret.encoding;
1181 * Convert a public key value to a string (for printing debug messages).
1182 * This is one of the very few calls in the entire API that is
1185 * @param hc the hash code
1189 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1191 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1192 struct GNUNET_HashCode hc;
1194 GNUNET_CRYPTO_hash (p, sizeof(*p), &hc);
1195 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1196 ret.encoding[6] = '\0';
1197 return (const char *) ret.encoding;
1203 * Convert a public key value to a string (for printing debug messages).
1204 * This is one of the very few calls in the entire API that is
1207 * @param hc the hash code
1211 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1213 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1214 struct GNUNET_HashCode hc;
1216 GNUNET_CRYPTO_hash (p, sizeof(*p), &hc);
1217 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1218 ret.encoding[6] = '\0';
1219 return (const char *) ret.encoding;
1225 * Convert a public key value to a string (for printing debug messages).
1226 * This is one of the very few calls in the entire API that is
1229 * @param hc the hash code
1233 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1235 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1236 struct GNUNET_HashCode hc;
1238 GNUNET_CRYPTO_hash (p, sizeof(*p), &hc);
1239 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1240 ret.encoding[6] = '\0';
1241 return (const char *) ret.encoding;
1247 * Convert a short hash value to a string (for printing debug messages).
1248 * This is one of the very few calls in the entire API that is
1251 * @param shc the hash code
1255 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc)
1257 static char buf[64];
1259 GNUNET_STRINGS_data_to_string (shc, sizeof(*shc), buf, sizeof(buf));
1261 return (const char *) buf;
1267 * Convert a UUID to a string (for printing debug messages).
1268 * This is one of the very few calls in the entire API that is
1271 * @param uuid the UUID
1275 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid)
1277 static char buf[32];
1279 GNUNET_STRINGS_data_to_string (uuid, sizeof(*uuid), buf, sizeof(buf));
1281 return (const char *) buf;
1286 * Convert a hash to a string (for printing debug messages).
1287 * This is one of the very few calls in the entire API that is
1290 * @param hc the hash code
1291 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1294 GNUNET_h2s_full (const struct GNUNET_HashCode *hc)
1296 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1298 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1299 ret.encoding[sizeof(ret) - 1] = '\0';
1300 return (const char *) ret.encoding;
1305 * Convert a peer identity to a string (for printing debug messages).
1307 * @param pid the peer identity
1308 * @return string form of the pid; will be overwritten by next
1309 * call to #GNUNET_i2s.
1312 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1314 static GNUNET_THREAD_LOCAL char buf[5];
1319 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1320 GNUNET_strlcpy (buf, ret, sizeof(buf));
1327 * Convert a peer identity to a string (for printing debug messages).
1328 * Identical to #GNUNET_i2s(), except that another
1329 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
1330 * used within the same log statement.
1332 * @param pid the peer identity
1333 * @return string form of the pid; will be overwritten by next
1334 * call to #GNUNET_i2s.
1337 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid)
1339 static GNUNET_THREAD_LOCAL char buf[5];
1344 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1345 GNUNET_strlcpy (buf, ret, sizeof(buf));
1352 * Convert a peer identity to a string (for printing debug messages).
1354 * @param pid the peer identity
1355 * @return string form of the pid; will be overwritten by next
1356 * call to #GNUNET_i2s_full.
1359 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1361 static GNUNET_THREAD_LOCAL char buf[256];
1364 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1372 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1373 * (for printing debug messages). This is one of the very few calls
1374 * in the entire API that is NOT reentrant!
1376 * @param addr the address
1377 * @param addrlen the length of the address in @a addr
1378 * @return nicely formatted string for the address
1379 * will be overwritten by next call to #GNUNET_a2s.
1382 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
1385 GNUNET_MAX ((INET6_ADDRSTRLEN + 8), \
1386 (1 + sizeof(struct sockaddr_un) - sizeof(sa_family_t)))
1387 static char buf[LEN];
1390 const struct sockaddr_in *v4;
1391 const struct sockaddr_un *un;
1392 const struct sockaddr_in6 *v6;
1396 return _ ("unknown address");
1397 switch (addr->sa_family)
1400 if (addrlen != sizeof(struct sockaddr_in))
1401 return "<invalid v4 address>";
1402 v4 = (const struct sockaddr_in *) addr;
1403 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1404 if (0 == ntohs (v4->sin_port))
1407 GNUNET_snprintf (b2, sizeof(b2), "%u", ntohs (v4->sin_port));
1412 if (addrlen != sizeof(struct sockaddr_in6))
1413 return "<invalid v6 address>";
1414 v6 = (const struct sockaddr_in6 *) addr;
1416 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1417 if (0 == ntohs (v6->sin6_port))
1420 GNUNET_snprintf (b2, sizeof(b2), "%u", ntohs (v6->sin6_port));
1425 if (addrlen <= sizeof(sa_family_t))
1426 return "<unbound UNIX client>";
1427 un = (const struct sockaddr_un *) addr;
1429 if ('\0' == un->sun_path[0])
1431 memset (buf, 0, sizeof(buf));
1432 GNUNET_snprintf (buf,
1435 (1 == off) ? "@" : "",
1436 (int) (addrlen - sizeof(sa_family_t) - off),
1437 &un->sun_path[off]);
1441 return _ ("invalid address");
1447 * Log error message about missing configuration option.
1449 * @param kind log level
1450 * @param section section with missing option
1451 * @param option name of missing option
1454 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1455 const char *section,
1460 "Configuration fails to specify option `%s' in section `%s'!\n"),
1467 * Log error message about invalid configuration option value.
1469 * @param kind log level
1470 * @param section section with invalid option
1471 * @param option name of invalid option
1472 * @param required what is required that is invalid about the option
1475 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1476 const char *section,
1478 const char *required)
1483 "Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1491 * Set the async scope for the current thread.
1493 * @param aid the async scope identifier
1494 * @param old_scope[out] location to save the old scope
1497 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1498 struct GNUNET_AsyncScopeSave *old_scope)
1500 *old_scope = current_async_scope;
1501 current_async_scope.have_scope = GNUNET_YES;
1502 current_async_scope.scope_id = *aid;
1507 * Clear the current thread's async scope.
1509 * @param old_scope scope to restore
1512 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope)
1514 current_async_scope = *old_scope;
1519 * Generate a fresh async scope identifier.
1521 * @param[out] aid_ret pointer to where the result is stored
1524 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret)
1526 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1528 sizeof(struct GNUNET_AsyncScopeId));
1533 * Get the current async scope.
1535 * @param[out] scope_ret pointer to where the result is stored
1538 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret)
1540 *scope_ret = current_async_scope;
1547 void __attribute__ ((constructor))
1548 GNUNET_util_cl_init ()
1550 GNUNET_stderr = stderr;
1557 void __attribute__ ((destructor))
1558 GNUNET_util_cl_fini ()
1564 /* end of common_logging.c */