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]
111 __attribute__ ((nonstring));
114 * Type of the last bulk message.
116 static GNUNET_THREAD_LOCAL enum GNUNET_ErrorType last_bulk_kind;
119 * Time of the last bulk error message (0 for none)
121 static GNUNET_THREAD_LOCAL struct GNUNET_TIME_Absolute last_bulk_time;
124 * Number of times that bulk message has been repeated since.
126 static GNUNET_THREAD_LOCAL unsigned int last_bulk_repeat;
129 * Component when the last bulk was logged. Will be 0-terminated.
131 static GNUNET_THREAD_LOCAL char last_bulk_comp[COMP_TRACK_SIZE + 1];
136 static char *component;
139 * Running component (without pid).
141 static char *component_nopid;
144 * Format string describing the name of the log file.
146 static char *log_file_name;
151 static enum GNUNET_ErrorType min_level;
154 * Linked list of our custom loggres.
156 static struct CustomLogger *loggers;
159 * Number of log calls to ignore.
161 static GNUNET_THREAD_LOCAL int skip_log = 0;
164 * File descriptor to use for "stderr", or NULL for none.
166 static FILE *GNUNET_stderr;
169 * Represents a single logging definition
174 * Component name regex
176 regex_t component_regex;
184 * Function name regex
186 regex_t function_regex;
189 * Lowest line at which this definition matches.
190 * Defaults to 0. Must be <= to_line.
195 * Highest line at which this definition matches.
196 * Defaults to INT_MAX. Must be >= from_line.
201 * Maximal log level allowed for calls that match this definition.
202 * Calls with higher log level will be disabled.
208 * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
209 * overrides any configuration options. 0 otherwise.
215 #if ! defined(GNUNET_CULL_LOGGING)
217 * Dynamic array of logging definitions
219 static struct LogDef *logdefs;
222 * Allocated size of logdefs array (in units)
224 static int logdefs_size;
227 * The number of units used in logdefs array.
229 static int logdefs_len;
232 * #GNUNET_YES if GNUNET_LOG environment variable is already parsed.
234 static int gnunet_log_parsed;
237 * #GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
239 static int gnunet_force_log_parsed;
242 * #GNUNET_YES if at least one definition with forced == 1 is available.
244 static int gnunet_force_log_present;
249 * Contains the number of performance counts per second.
251 static LARGE_INTEGER performance_frequency;
256 * Convert a textual description of a loglevel
257 * to the respective GNUNET_GE_KIND.
259 * @param log loglevel to parse
260 * @return GNUNET_GE_INVALID if log does not parse
262 static enum GNUNET_ErrorType
263 get_type (const char *log)
266 return GNUNET_ERROR_TYPE_UNSPECIFIED;
267 if (0 == strcasecmp (log, _ ("DEBUG")))
268 return GNUNET_ERROR_TYPE_DEBUG;
269 if (0 == strcasecmp (log, _ ("INFO")))
270 return GNUNET_ERROR_TYPE_INFO;
271 if (0 == strcasecmp (log, _ ("MESSAGE")))
272 return GNUNET_ERROR_TYPE_MESSAGE;
273 if (0 == strcasecmp (log, _ ("WARNING")))
274 return GNUNET_ERROR_TYPE_WARNING;
275 if (0 == strcasecmp (log, _ ("ERROR")))
276 return GNUNET_ERROR_TYPE_ERROR;
277 if (0 == strcasecmp (log, _ ("NONE")))
278 return GNUNET_ERROR_TYPE_NONE;
279 return GNUNET_ERROR_TYPE_INVALID;
284 * Abort the process, generate a core dump if possible.
296 #if ! defined(GNUNET_CULL_LOGGING)
298 * Utility function - reallocates logdefs array to be twice as large.
303 logdefs_size = (logdefs_size + 1) * 2;
304 logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
308 #if ! TALER_WALLET_ONLY
310 * Rotate logs, deleting the oldest log.
312 * @param new_name new name to add to the rotation
315 log_rotate (const char *new_name)
317 static char *rotation[ROTATION_KEEP];
318 static unsigned int rotation_off;
321 if ('\0' == *new_name)
322 return; /* not a real log file name */
323 discard = rotation[rotation_off % ROTATION_KEEP];
326 /* Note: can't log errors during logging (recursion!), so this
327 operation MUST silently fail... */
328 (void) UNLINK (discard);
329 GNUNET_free (discard);
331 rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup (new_name);
337 * Setup the log file.
339 * @param tm timestamp for which we should setup logging
340 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
343 setup_log_file (const struct tm *tm)
345 static char last_fn[PATH_MAX + 1];
346 char fn[PATH_MAX + 1];
352 if (NULL == log_file_name)
353 return GNUNET_SYSERR;
354 if (0 == strftime (fn, sizeof (fn), log_file_name, tm))
355 return GNUNET_SYSERR;
356 leftsquare = strrchr (fn, '[');
357 if ((NULL != leftsquare) && (']' == leftsquare[1]))
359 char *logfile_copy = GNUNET_strdup (fn);
361 logfile_copy[leftsquare - fn] = '\0';
362 logfile_copy[leftsquare - fn + 1] = '\0';
368 &logfile_copy[leftsquare - fn + 2]);
369 GNUNET_free (logfile_copy);
371 if (0 == strcmp (fn, last_fn))
372 return GNUNET_OK; /* no change */
373 log_rotate (last_fn);
374 strcpy (last_fn, fn);
375 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (fn))
378 "Failed to create directory for `%s': %s\n",
381 return GNUNET_SYSERR;
385 OPEN (fn, O_APPEND | O_BINARY | O_WRONLY | O_CREAT, _S_IREAD | _S_IWRITE);
387 altlog_fd = OPEN (fn,
388 O_APPEND | O_WRONLY | O_CREAT,
389 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
393 if (NULL != GNUNET_stderr)
394 fclose (GNUNET_stderr);
395 dup_return = dup2 (altlog_fd, 2);
396 (void) close (altlog_fd);
397 if (-1 != dup_return)
399 altlog = fdopen (2, "ab");
413 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
414 return GNUNET_SYSERR;
416 GNUNET_stderr = altlog;
423 * Utility function - adds a parsed definition to logdefs array.
425 * @param component see struct LogDef, can't be NULL
426 * @param file see struct LogDef, can't be NULL
427 * @param function see struct LogDef, can't be NULL
428 * @param from_line see struct LogDef
429 * @param to_line see struct LogDef
430 * @param level see struct LogDef, must be >= 0
431 * @param force see struct LogDef
432 * @return 0 on success, regex-specific error otherwise
435 add_definition (const char *component,
437 const char *function,
446 if (logdefs_size == logdefs_len)
448 memset (&n, 0, sizeof (n));
449 if (0 == strlen (component))
450 component = (char *) ".*";
451 r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
456 if (0 == strlen (file))
457 file = (char *) ".*";
458 r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
461 regfree (&n.component_regex);
464 if ((NULL == function) || (0 == strlen (function)))
465 function = (char *) ".*";
466 r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
469 regfree (&n.component_regex);
470 regfree (&n.file_regex);
473 n.from_line = from_line;
477 logdefs[logdefs_len++] = n;
483 * Decides whether a particular logging call should or should not be allowed
484 * to be made. Used internally by GNUNET_log*()
486 * @param caller_level loglevel the caller wants to use
487 * @param comp component name the caller uses (NULL means that global
488 * component name is used)
489 * @param file file name containing the logging call, usually __FILE__
490 * @param function function which tries to make a logging call,
491 * usually __FUNCTION__
492 * @param line line at which the call is made, usually __LINE__
493 * @return 0 to disallow the call, 1 to allow it
496 GNUNET_get_log_call_status (int caller_level,
499 const char *function,
507 /* Use default component */
508 comp = component_nopid;
510 /* We have no definitions to override globally configured log level,
511 * so just use it right away.
513 if ((min_level >= 0) && (GNUNET_NO == gnunet_force_log_present))
514 return caller_level <= min_level;
516 /* Only look for forced definitions? */
517 force_only = min_level >= 0;
518 for (i = 0; i < logdefs_len; i++)
521 if (((! force_only) || ld->force) &&
522 (line >= ld->from_line && line <= ld->to_line) &&
523 (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
524 (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
525 (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
528 return caller_level <= ld->level;
531 /* No matches - use global level, if defined */
533 return caller_level <= min_level;
534 /* All programs/services previously defaulted to WARNING.
535 * Now *we* default to WARNING, and THEY default to NULL.
536 * Or rather we default to MESSAGE, since things aren't always bad.
538 return caller_level <= GNUNET_ERROR_TYPE_MESSAGE;
543 * Utility function - parses a definition
546 * component;file;function;from_line-to_line;level[/component...]
547 * All entries are mandatory, but may be empty.
548 * Empty entries for component, file and function are treated as
549 * "matches anything".
550 * Empty line entry is treated as "from 0 to INT_MAX"
551 * Line entry with only one line is treated as "this line only"
552 * Entry for level MUST NOT be empty.
553 * Entries for component, file and function that consist of a
554 * single character "*" are treated (at the moment) the same way
555 * empty entries are treated (wildcard matching is not implemented (yet?)).
556 * file entry is matched to the end of __FILE__. That is, it might be
557 * a base name, or a base name with leading directory names (some compilers
558 * define __FILE__ to absolute file path).
560 * @param constname name of the environment variable from which to get the
561 * string to be parsed
562 * @param force 1 if definitions found in constname are to be forced
563 * @return number of added definitions
566 parse_definitions (const char *constname, int force)
572 char *function = NULL;
578 int from_line, to_line;
580 int keep_looking = 1;
582 tmp = getenv (constname);
585 def = GNUNET_strdup (tmp);
588 for (p = def, state = 0, start = def; keep_looking; p++)
592 case ';': /* found a field separator */
596 case 0: /* within a component name */
599 case 1: /* within a file name */
602 case 2: /* within a function name */
603 /* after a file name there must be a function name */
606 case 3: /* within a from-to line range */
607 if (strlen (start) > 0)
610 from_line = strtol (start, &t, 10);
611 if ((0 != errno) || (from_line < 0))
616 if ((t < p) && ('-' == t[0]))
620 to_line = strtol (start, &t, 10);
621 if ((0 != errno) || (to_line < 0) || (t != p))
627 else /* one number means "match this line only" */
630 else /* default to 0-max */
639 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
646 case '\0': /* found EOL */
648 /* fall through to '/' */
649 case '/': /* found a definition separator */
652 case 4: /* within a log level */
655 level = get_type ((const char *) start);
656 if ((GNUNET_ERROR_TYPE_INVALID == level) ||
657 (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
658 (0 != add_definition (comp,
675 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
689 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
692 parse_all_definitions ()
694 if (GNUNET_NO == gnunet_force_log_parsed)
695 gnunet_force_log_present =
696 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
697 gnunet_force_log_parsed = GNUNET_YES;
699 if (GNUNET_NO == gnunet_log_parsed)
700 parse_definitions ("GNUNET_LOG", 0);
701 gnunet_log_parsed = GNUNET_YES;
709 * @param comp default component to use
710 * @param loglevel what types of messages should be logged
711 * @param logfile which file to write log messages to (can be NULL)
712 * @return #GNUNET_OK on success
715 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
717 const char *env_logfile;
719 min_level = get_type (loglevel);
720 #if ! defined(GNUNET_CULL_LOGGING)
721 parse_all_definitions ();
724 QueryPerformanceFrequency (&performance_frequency);
726 GNUNET_free_non_null (component);
727 GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
728 GNUNET_free_non_null (component_nopid);
729 component_nopid = GNUNET_strdup (comp);
731 env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
732 if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
733 logfile = env_logfile;
736 GNUNET_free_non_null (log_file_name);
737 log_file_name = GNUNET_STRINGS_filename_expand (logfile);
738 if (NULL == log_file_name)
739 return GNUNET_SYSERR;
740 #if TALER_WALLET_ONLY || defined(GNUNET_CULL_LOGGING)
741 /* log file option not allowed for wallet logic */
742 GNUNET_assert (NULL == logfile);
751 return setup_log_file (tm);
758 * Add a custom logger. Note that installing any custom logger
759 * will disable the standard logger. When multiple custom loggers
760 * are installed, all will be called. The standard logger will
761 * only be used if no custom loggers are present.
763 * @param logger log function
764 * @param logger_cls closure for @a logger
767 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
769 struct CustomLogger *entry;
771 entry = GNUNET_new (struct CustomLogger);
772 entry->logger = logger;
773 entry->logger_cls = logger_cls;
774 entry->next = loggers;
780 * Remove a custom logger.
782 * @param logger log function
783 * @param logger_cls closure for @a logger
786 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
788 struct CustomLogger *pos;
789 struct CustomLogger *prev;
793 while ((NULL != pos) &&
794 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
799 GNUNET_assert (NULL != pos);
803 prev->next = pos->next;
808 CRITICAL_SECTION output_message_cs;
813 * Actually output the log message.
815 * @param kind how severe was the issue
816 * @param comp component responsible
817 * @param datestr current date/time
818 * @param msg the actual message
821 output_message (enum GNUNET_ErrorType kind,
826 struct CustomLogger *pos;
829 EnterCriticalSection (&output_message_cs);
831 /* only use the standard logger if no custom loggers are present */
832 if ((NULL != GNUNET_stderr) && (NULL == loggers))
834 if (kind == GNUNET_ERROR_TYPE_MESSAGE)
836 /* The idea here is to produce "normal" output messages
837 * for end users while still having the power of the
838 * logging engine for developer needs. So ideally this
839 * is what it should look like when CLI tools are used
840 * interactively, yet the same message shouldn't look
841 * this way if the output is going to logfiles or robots
844 FPRINTF (GNUNET_stderr, "* %s", msg);
846 else if (GNUNET_YES == current_async_scope.have_scope)
848 static GNUNET_THREAD_LOCAL char id_buf[27];
851 /* We're logging, so skip_log must be currently 0. */
853 end = GNUNET_STRINGS_data_to_string (¤t_async_scope.scope_id,
854 sizeof (struct GNUNET_AsyncScopeId),
856 sizeof (id_buf) - 1);
857 GNUNET_assert (NULL != end);
860 FPRINTF (GNUNET_stderr,
865 GNUNET_error_type_to_string (kind),
870 FPRINTF (GNUNET_stderr,
874 GNUNET_error_type_to_string (kind),
877 fflush (GNUNET_stderr);
882 pos->logger (pos->logger_cls, kind, comp, datestr, msg);
886 LeaveCriticalSection (&output_message_cs);
892 * Flush an existing bulk report to the output.
894 * @param datestr our current timestamp
897 flush_bulk (const char *datestr)
899 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
904 if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat))
907 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
909 last = &last_bulk[BULK_TRACK_SIZE - 1];
910 else if (last != last_bulk)
918 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (
923 _ ("Message `%.*s' repeated %u times in the last %s\n"),
930 output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
931 last_bulk_time = GNUNET_TIME_absolute_get ();
932 last_bulk_repeat = 0;
937 * Ignore the next n calls to the log function.
939 * @param n number of log calls to ignore (could be negative)
940 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
943 GNUNET_log_skip (int n, int check_reset)
949 ok = (0 == skip_log);
962 * Get the number of log calls that are going to be skipped
964 * @return number of log calls to be ignored
967 GNUNET_get_log_skip ()
974 * Output a log message using the default mechanism.
976 * @param kind how severe was the issue
977 * @param comp component responsible
978 * @param message the actual message
979 * @param va arguments to the format string "message"
982 mylog (enum GNUNET_ErrorType kind,
987 char date[DATE_STR_SIZE];
988 char date2[DATE_STR_SIZE];
994 size = VSNPRINTF (NULL, 0, message, vacp) + 1;
995 GNUNET_assert (0 != size);
997 memset (date, 0, DATE_STR_SIZE);
1005 offset = GNUNET_TIME_get_offset ();
1007 timetmp += offset / 1000;
1008 tmptr = localtime (&timetmp);
1010 QueryPerformanceCounter (&pc);
1013 strcpy (date, "localtime error");
1018 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr))
1020 if (0 > snprintf (date,
1023 (long long) (pc.QuadPart /
1024 (performance_frequency.QuadPart / 1000))))
1028 struct timeval timeofday;
1030 gettimeofday (&timeofday, NULL);
1031 offset = GNUNET_TIME_get_offset ();
1034 timeofday.tv_sec += offset / 1000LL;
1035 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1036 if (timeofday.tv_usec > 1000000LL)
1038 timeofday.tv_usec -= 1000000LL;
1044 timeofday.tv_sec += offset / 1000LL;
1045 if (timeofday.tv_usec > -(offset % 1000LL) * 1000LL)
1047 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1051 timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
1055 tmptr = localtime (&timeofday.tv_sec);
1058 strcpy (date, "localtime error");
1062 if (0 == strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr))
1064 if (0 > snprintf (date, sizeof (date), date2, timeofday.tv_usec))
1068 VSNPRINTF (buf, size, message, va);
1069 #if ! (defined(GNUNET_CULL_LOGGING) || TALER_WALLET_ONLY)
1071 (void) setup_log_file (tmptr);
1073 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
1074 (0 != last_bulk_time.abs_value_us) &&
1075 (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
1078 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
1079 BULK_DELAY_THRESHOLD) ||
1080 (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
1085 strncpy (last_bulk, buf, sizeof (last_bulk));
1086 last_bulk_repeat = 0;
1087 last_bulk_kind = kind;
1088 last_bulk_time = GNUNET_TIME_absolute_get ();
1089 strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
1090 output_message (kind, comp, date, buf);
1096 * Main log function.
1098 * @param kind how serious is the error?
1099 * @param message what is the message (format string)
1100 * @param ... arguments for format string
1103 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
1107 va_start (va, message);
1108 mylog (kind, component, message, va);
1114 * Log function that specifies an alternative component.
1115 * This function should be used by plugins.
1117 * @param kind how serious is the error?
1118 * @param comp component responsible for generating the message
1119 * @param message what is the message (format string)
1120 * @param ... arguments for format string
1123 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
1125 const char *message,
1129 char comp_w_pid[128];
1132 comp = component_nopid;
1134 va_start (va, message);
1135 GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
1136 mylog (kind, comp_w_pid, message, va);
1142 * Convert error type to string.
1144 * @param kind type to convert
1145 * @return string corresponding to the type
1148 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1150 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1152 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1153 return _ ("WARNING");
1154 if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0)
1155 return _ ("MESSAGE");
1156 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1158 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1160 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1162 return _ ("INVALID");
1167 * Convert a hash to a string (for printing debug messages).
1169 * @param hc the hash code
1170 * @return string form; will be overwritten by next call to GNUNET_h2s.
1173 GNUNET_h2s (const struct GNUNET_HashCode *hc)
1175 static GNUNET_THREAD_LOCAL struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1177 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1178 ret.encoding[8] = '\0';
1179 return (const char *) ret.encoding;
1184 * Convert a hash to a string (for printing debug messages).
1185 * This is one of the very few calls in the entire API that is
1186 * NOT reentrant! Identical to #GNUNET_h2s(), except that another
1187 * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
1188 * used within the same log statement.
1190 * @param hc the hash code
1191 * @return string form; will be overwritten by next call to GNUNET_h2s.
1194 GNUNET_h2s2 (const struct GNUNET_HashCode *hc)
1196 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1198 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1199 ret.encoding[8] = '\0';
1200 return (const char *) ret.encoding;
1206 * Convert a public key value to a string (for printing debug messages).
1207 * This is one of the very few calls in the entire API that is
1210 * @param hc the hash code
1214 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1216 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1217 struct GNUNET_HashCode hc;
1219 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc);
1220 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1221 ret.encoding[6] = '\0';
1222 return (const char *) ret.encoding;
1228 * Convert a public key value to a string (for printing debug messages).
1229 * This is one of the very few calls in the entire API that is
1232 * @param hc the hash code
1236 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1238 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1239 struct GNUNET_HashCode hc;
1241 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc);
1242 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1243 ret.encoding[6] = '\0';
1244 return (const char *) ret.encoding;
1250 * Convert a public key value to a string (for printing debug messages).
1251 * This is one of the very few calls in the entire API that is
1254 * @param hc the hash code
1258 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1260 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1261 struct GNUNET_HashCode hc;
1263 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc);
1264 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1265 ret.encoding[6] = '\0';
1266 return (const char *) ret.encoding;
1272 * Convert a public key value to a string (for printing debug messages).
1273 * This is one of the very few calls in the entire API that is
1276 * @param hc the hash code
1280 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1282 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1283 struct GNUNET_HashCode hc;
1285 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc);
1286 GNUNET_CRYPTO_hash_to_enc (&hc, &ret);
1287 ret.encoding[6] = '\0';
1288 return (const char *) ret.encoding;
1294 * Convert a short hash value to a string (for printing debug messages).
1295 * This is one of the very few calls in the entire API that is
1298 * @param shc the hash code
1302 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc)
1304 static char buf[64];
1306 GNUNET_STRINGS_data_to_string (shc, sizeof (*shc), buf, sizeof (buf));
1308 return (const char *) buf;
1314 * Convert a UUID to a string (for printing debug messages).
1315 * This is one of the very few calls in the entire API that is
1318 * @param uuid the UUID
1322 GNUNET_uuid2s (const struct GNUNET_Uuid *uuid)
1324 static char buf[32];
1326 GNUNET_STRINGS_data_to_string (uuid, sizeof (*uuid), buf, sizeof (buf));
1328 return (const char *) buf;
1333 * Convert a hash to a string (for printing debug messages).
1334 * This is one of the very few calls in the entire API that is
1337 * @param hc the hash code
1338 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1341 GNUNET_h2s_full (const struct GNUNET_HashCode *hc)
1343 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1345 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1346 ret.encoding[sizeof (ret) - 1] = '\0';
1347 return (const char *) ret.encoding;
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.
1359 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1361 static GNUNET_THREAD_LOCAL char buf[5];
1366 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1367 strncpy (buf, ret, sizeof (buf) - 1);
1375 * Convert a peer identity to a string (for printing debug messages).
1376 * Identical to #GNUNET_i2s(), except that another
1377 * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
1378 * used within the same log statement.
1380 * @param pid the peer identity
1381 * @return string form of the pid; will be overwritten by next
1382 * call to #GNUNET_i2s.
1385 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid)
1387 static GNUNET_THREAD_LOCAL char buf[5];
1392 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1393 strncpy (buf, ret, sizeof (buf) - 1);
1401 * Convert a peer identity to a string (for printing debug messages).
1403 * @param pid the peer identity
1404 * @return string form of the pid; will be overwritten by next
1405 * call to #GNUNET_i2s_full.
1408 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1410 static GNUNET_THREAD_LOCAL char buf[256];
1413 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1421 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1422 * (for printing debug messages). This is one of the very few calls
1423 * in the entire API that is NOT reentrant!
1425 * @param addr the address
1426 * @param addrlen the length of the address in @a addr
1427 * @return nicely formatted string for the address
1428 * will be overwritten by next call to #GNUNET_a2s.
1431 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
1435 GNUNET_MAX ((INET6_ADDRSTRLEN + 8), \
1436 (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t)))
1438 #define LEN (INET6_ADDRSTRLEN + 8)
1440 static char buf[LEN];
1443 const struct sockaddr_in *v4;
1444 const struct sockaddr_un *un;
1445 const struct sockaddr_in6 *v6;
1449 return _ ("unknown address");
1450 switch (addr->sa_family)
1453 if (addrlen != sizeof (struct sockaddr_in))
1454 return "<invalid v4 address>";
1455 v4 = (const struct sockaddr_in *) addr;
1456 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1457 if (0 == ntohs (v4->sin_port))
1460 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
1464 if (addrlen != sizeof (struct sockaddr_in6))
1465 return "<invalid v4 address>";
1466 v6 = (const struct sockaddr_in6 *) addr;
1468 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1469 if (0 == ntohs (v6->sin6_port))
1472 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1476 if (addrlen <= sizeof (sa_family_t))
1477 return "<unbound UNIX client>";
1478 un = (const struct sockaddr_un *) addr;
1480 if ('\0' == un->sun_path[0])
1482 memset (buf, 0, sizeof (buf));
1483 GNUNET_snprintf (buf,
1486 (1 == off) ? "@" : "",
1487 (int) (addrlen - sizeof (sa_family_t) - off),
1488 &un->sun_path[off]);
1491 return _ ("invalid address");
1497 * Log error message about missing configuration option.
1499 * @param kind log level
1500 * @param section section with missing option
1501 * @param option name of missing option
1504 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1505 const char *section,
1510 "Configuration fails to specify option `%s' in section `%s'!\n"),
1517 * Log error message about invalid configuration option value.
1519 * @param kind log level
1520 * @param section section with invalid option
1521 * @param option name of invalid option
1522 * @param required what is required that is invalid about the option
1525 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1526 const char *section,
1528 const char *required)
1533 "Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1541 * Set the async scope for the current thread.
1543 * @param aid the async scope identifier
1544 * @param old_scope[out] location to save the old scope
1547 GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1548 struct GNUNET_AsyncScopeSave *old_scope)
1550 *old_scope = current_async_scope;
1551 current_async_scope.have_scope = GNUNET_YES;
1552 current_async_scope.scope_id = *aid;
1557 * Clear the current thread's async scope.
1559 * @param old_scope scope to restore
1562 GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope)
1564 current_async_scope = *old_scope;
1569 * Generate a fresh async scope identifier.
1571 * @param[out] aid_ret pointer to where the result is stored
1574 GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret)
1576 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
1578 sizeof (struct GNUNET_AsyncScopeId));
1583 * Get the current async scope.
1585 * @param[out] scope_ret pointer to where the result is stored
1588 GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret)
1590 *scope_ret = current_async_scope;
1597 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
1599 GNUNET_stderr = stderr;
1601 GNInitWinEnv (NULL);
1604 if (! InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400))
1613 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
1616 DeleteCriticalSection (&output_message_cs);
1619 GNShutdownWinEnv ();
1623 /* end of common_logging.c */