2 This file is part of GNUnet.
3 (C) 2006, 2008, 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/common_logging.c
23 * @brief error handling API
25 * @author Christian Grothoff
28 #include "gnunet_common.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_strings_lib.h"
31 #include "gnunet_time_lib.h"
36 * After how many milliseconds do we always print
37 * that "message X was repeated N times"? Use 12h.
39 #define BULK_DELAY_THRESHOLD (12 * 60 * 60 * 1000)
42 * After how many repetitions do we always print
43 * that "message X was repeated N times"? (even if
44 * we have not yet reached the delay threshold)
46 #define BULK_REPEAT_THRESHOLD 1000
49 * How many characters do we use for matching of
52 #define BULK_TRACK_SIZE 256
55 * How many characters do we use for matching of
58 #define COMP_TRACK_SIZE 32
61 * How many characters can a date/time string
64 #define DATE_STR_SIZE 64
67 * Linked list of active loggers.
72 * This is a linked list.
74 struct CustomLogger *next;
88 * The last "bulk" error message that we have been logging.
89 * Note that this message maybe truncated to the first BULK_TRACK_SIZE
90 * characters, in which case it is NOT 0-terminated!
92 static char last_bulk[BULK_TRACK_SIZE];
95 * Type of the last bulk message.
97 static enum GNUNET_ErrorType last_bulk_kind;
100 * Time of the last bulk error message (0 for none)
102 static struct GNUNET_TIME_Absolute last_bulk_time;
105 * Number of times that bulk message has been repeated since.
107 static unsigned int last_bulk_repeat;
110 * Component when the last bulk was logged. Will be 0-terminated.
112 static char last_bulk_comp[COMP_TRACK_SIZE + 1];
117 static char *component;
120 * Running component (without pid).
122 static char *component_nopid;
127 static enum GNUNET_ErrorType min_level;
130 * Linked list of our custom loggres.
132 static struct CustomLogger *loggers;
135 * Number of log calls to ignore.
137 unsigned int skip_log;
140 * File descriptor to use for "stderr", or NULL for none.
142 static FILE *GNUNET_stderr;
145 * Represents a single logging definition
150 * Component name regex
152 regex_t component_regex;
160 * Function name regex
162 regex_t function_regex;
165 * Lowest line at which this definition matches.
166 * Defaults to 0. Must be <= to_line.
171 * Highest line at which this definition matches.
172 * Defaults to INT_MAX. Must be >= from_line.
177 * Maximal log level allowed for calls that match this definition.
178 * Calls with higher log level will be disabled.
184 * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
185 * overrides any configuration options. 0 otherwise.
191 * Dynamic array of logging definitions
193 struct LogDef *logdefs = NULL;
196 * Allocated size of logdefs array (in units)
198 int logdefs_size = 0;
201 * The number of units used in logdefs array.
206 * GNUNET_YES if GNUNET_LOG environment variable is already parsed.
208 int gnunet_log_parsed = GNUNET_NO;
211 * GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
213 int gnunet_force_log_parsed = GNUNET_NO;
216 * GNUNET_YES if at least one definition with forced == 1 is available.
218 int gnunet_force_log_present = GNUNET_NO;
222 * Contains the number of performance counts per second.
224 LARGE_INTEGER performance_frequency;
228 * Convert a textual description of a loglevel
229 * to the respective GNUNET_GE_KIND.
231 * @param log loglevel to parse
232 * @return GNUNET_GE_INVALID if log does not parse
234 static enum GNUNET_ErrorType
235 get_type (const char *log)
238 return GNUNET_ERROR_TYPE_UNSPECIFIED;
239 if (0 == strcasecmp (log, _("DEBUG")))
240 return GNUNET_ERROR_TYPE_DEBUG;
241 if (0 == strcasecmp (log, _("INFO")))
242 return GNUNET_ERROR_TYPE_INFO;
243 if (0 == strcasecmp (log, _("WARNING")))
244 return GNUNET_ERROR_TYPE_WARNING;
245 if (0 == strcasecmp (log, _("ERROR")))
246 return GNUNET_ERROR_TYPE_ERROR;
247 if (0 == strcasecmp (log, _("NONE")))
248 return GNUNET_ERROR_TYPE_NONE;
249 return GNUNET_ERROR_TYPE_INVALID;
252 #if !defined(GNUNET_CULL_LOGGING)
254 * Utility function - reallocates logdefs array to be twice as large.
259 logdefs_size = (logdefs_size + 1) * 2;
260 logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
265 * Abort the process, generate a core dump if possible.
278 * Utility function - adds a parsed definition to logdefs array.
280 * @param component see struct LogDef, can't be NULL
281 * @param file see struct LogDef, can't be NULL
282 * @param function see struct LogDef, can't be NULL
283 * @param from_line see struct LogDef
284 * @param to_line see struct LogDef
285 * @param level see struct LogDef, must be >= 0
286 * @param force see struct LogDef
287 * @return 0 on success, regex-specific error otherwise
290 add_definition (char *component, char *file, char *function, int from_line,
291 int to_line, int level, int force)
296 if (logdefs_size == logdefs_len)
298 memset (&n, 0, sizeof (n));
299 if (strlen (component) == 0)
300 component = (char *) ".*";
301 r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
306 if (strlen (file) == 0)
307 file = (char *) ".*";
308 r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
311 regfree (&n.component_regex);
314 if ((NULL == function) || (strlen (function) == 0))
315 function = (char *) ".*";
316 r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
319 regfree (&n.component_regex);
320 regfree (&n.file_regex);
323 n.from_line = from_line;
327 logdefs[logdefs_len++] = n;
333 * Decides whether a particular logging call should or should not be allowed
334 * to be made. Used internally by GNUNET_log*()
336 * @param caller_level loglevel the caller wants to use
337 * @param comp component name the caller uses (NULL means that global
338 * component name is used)
339 * @param file file name containing the logging call, usually __FILE__
340 * @param function function which tries to make a logging call,
341 * usually __FUNCTION__
342 * @param line line at which the call is made, usually __LINE__
343 * @return 0 to disallow the call, 1 to allow it
346 GNUNET_get_log_call_status (int caller_level, const char *comp,
347 const char *file, const char *function, int line)
354 /* Use default component */
355 comp = component_nopid;
357 /* We have no definitions to override globally configured log level,
358 * so just use it right away.
360 if (min_level >= 0 && gnunet_force_log_present == GNUNET_NO)
361 return caller_level <= min_level;
363 /* Only look for forced definitions? */
364 force_only = min_level >= 0;
365 for (i = 0; i < logdefs_len; i++)
368 if ((!force_only || ld->force) &&
369 (line >= ld->from_line && line <= ld->to_line) &&
370 (regexec (&ld->component_regex, comp, 0, NULL, 0) == 0) &&
371 (regexec (&ld->file_regex, file, 0, NULL, 0) == 0) &&
372 (regexec (&ld->function_regex, function, 0, NULL, 0) == 0))
375 return caller_level <= ld->level;
378 /* No matches - use global level, if defined */
380 return caller_level <= min_level;
381 /* All programs/services previously defaulted to WARNING.
382 * Now WE default to WARNING, and THEY default to NULL.
384 return caller_level <= GNUNET_ERROR_TYPE_WARNING;
389 * Utility function - parses a definition
392 * component;file;function;from_line-to_line;level[/component...]
393 * All entries are mandatory, but may be empty.
394 * Empty entries for component, file and function are treated as
395 * "matches anything".
396 * Empty line entry is treated as "from 0 to INT_MAX"
397 * Line entry with only one line is treated as "this line only"
398 * Entry for level MUST NOT be empty.
399 * Entries for component, file and function that consist of a
400 * single character "*" are treated (at the moment) the same way
401 * empty entries are treated (wildcard matching is not implemented (yet?)).
402 * file entry is matched to the end of __FILE__. That is, it might be
403 * a base name, or a base name with leading directory names (some compilers
404 * define __FILE__ to absolute file path).
406 * @param constname name of the environment variable from which to get the
407 * string to be parsed
408 * @param force 1 if definitions found in constname are to be forced
409 * @return number of added definitions
412 parse_definitions (const char *constname, int force)
418 char *function = NULL;
424 int from_line, to_line;
426 int keep_looking = 1;
428 tmp = getenv (constname);
431 def = GNUNET_strdup (tmp);
434 for (p = def, state = 0, start = def; keep_looking; p++)
438 case ';': /* found a field separator */
442 case 0: /* within a component name */
445 case 1: /* within a file name */
448 case 2: /* within a function name */
449 /* after a file name there must be a function name */
452 case 3: /* within a from-to line range */
453 if (strlen (start) > 0)
456 from_line = strtol (start, &t, 10);
457 if (errno != 0 || from_line < 0)
462 if (t < p && t[0] == '-')
466 to_line = strtol (start, &t, 10);
467 if (errno != 0 || to_line < 0 || t != p)
473 else /* one number means "match this line only" */
476 else /* default to 0-max */
486 case '\0': /* found EOL */
488 /* fall through to '/' */
489 case '/': /* found a definition separator */
492 case 4: /* within a log level */
495 level = get_type ((const char *) start);
496 if (level == GNUNET_ERROR_TYPE_INVALID ||
497 level == GNUNET_ERROR_TYPE_UNSPECIFIED ||
498 0 != add_definition (comp, file, function, from_line, to_line,
519 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
522 parse_all_definitions ()
524 if (gnunet_log_parsed == GNUNET_NO)
525 parse_definitions ("GNUNET_LOG", 0);
526 gnunet_log_parsed = GNUNET_YES;
527 if (gnunet_force_log_parsed == GNUNET_NO)
528 gnunet_force_log_present =
529 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
530 gnunet_force_log_parsed = GNUNET_YES;
536 * @param comp default component to use
537 * @param loglevel what types of messages should be logged
538 * @param logfile which file to write log messages to (can be NULL)
539 * @return GNUNET_OK on success
542 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
547 const char *env_logfile = NULL;
550 min_level = get_type (loglevel);
551 #if !defined(GNUNET_CULL_LOGGING)
552 parse_all_definitions ();
555 QueryPerformanceFrequency (&performance_frequency);
557 GNUNET_free_non_null (component);
558 GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
559 GNUNET_free_non_null (component_nopid);
560 component_nopid = GNUNET_strdup (comp);
562 env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
563 if ((env_logfile != NULL) && (strlen (env_logfile) > 0))
564 logfile = env_logfile;
568 fn = GNUNET_STRINGS_filename_expand (logfile);
570 return GNUNET_SYSERR;
571 dirwarn = (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn));
572 altlog_fd = OPEN (fn, O_APPEND |
580 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
586 if (GNUNET_stderr != NULL)
587 fclose (GNUNET_stderr);
588 dup_return = dup2 (altlog_fd, 2);
590 if (dup_return != -1)
592 altlog = fdopen (2, "ab");
606 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
608 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
609 _("Failed to create or access directory for log file `%s'\n"),
612 return GNUNET_SYSERR;
615 GNUNET_stderr = altlog;
620 * Add a custom logger.
622 * @param logger log function
623 * @param logger_cls closure for logger
626 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
628 struct CustomLogger *entry;
630 entry = GNUNET_malloc (sizeof (struct CustomLogger));
631 entry->logger = logger;
632 entry->logger_cls = logger_cls;
633 entry->next = loggers;
638 * Remove a custom logger.
640 * @param logger log function
641 * @param logger_cls closure for logger
644 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
646 struct CustomLogger *pos;
647 struct CustomLogger *prev;
651 while ((pos != NULL) &&
652 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
657 GNUNET_assert (pos != NULL);
661 prev->next = pos->next;
667 * Actually output the log message.
669 * @param kind how severe was the issue
670 * @param comp component responsible
671 * @param datestr current date/time
672 * @param msg the actual message
675 output_message (enum GNUNET_ErrorType kind, const char *comp,
676 const char *datestr, const char *msg)
678 struct CustomLogger *pos;
680 if (GNUNET_stderr != NULL)
682 FPRINTF (GNUNET_stderr, "%s %s %s %s", datestr, comp,
683 GNUNET_error_type_to_string (kind), msg);
684 fflush (GNUNET_stderr);
689 pos->logger (pos->logger_cls, kind, comp, datestr, msg);
696 * Flush an existing bulk report to the output.
698 * @param datestr our current timestamp
701 flush_bulk (const char *datestr)
703 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
708 if ((last_bulk_time.abs_value == 0) || (last_bulk_repeat == 0))
711 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
713 last = &last_bulk[BULK_TRACK_SIZE - 1];
714 else if (last != last_bulk)
721 ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
723 snprintf (msg, sizeof (msg),
724 _("Message `%.*s' repeated %u times in the last %s\n"),
725 BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
729 output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
730 last_bulk_time = GNUNET_TIME_absolute_get ();
731 last_bulk_repeat = 0;
736 * Ignore the next n calls to the log function.
738 * @param n number of log calls to ignore
739 * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
742 GNUNET_log_skip (unsigned int n, int check_reset)
748 ok = (0 == skip_log);
759 * Output a log message using the default mechanism.
761 * @param kind how severe was the issue
762 * @param comp component responsible
763 * @param message the actual message
764 * @param va arguments to the format string "message"
767 mylog (enum GNUNET_ErrorType kind, const char *comp, const char *message,
770 char date[DATE_STR_SIZE];
771 char date2[DATE_STR_SIZE];
773 struct timeval timeofday;
779 size = VSNPRINTF (NULL, 0, message, vacp) + 1;
780 GNUNET_assert (0 != size);
785 VSNPRINTF (buf, size, message, va);
787 memset (date, 0, DATE_STR_SIZE);
788 tmptr = localtime (&timetmp);
789 gettimeofday (&timeofday, NULL);
796 QueryPerformanceCounter (&pc);
797 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
798 snprintf (date, sizeof (date), date2,
799 (long long) (pc.QuadPart /
800 (performance_frequency.QuadPart / 1000)));
802 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
803 snprintf (date, sizeof (date), date2, timeofday.tv_usec);
807 strcpy (date, "localtime error");
808 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
809 (last_bulk_time.abs_value != 0) &&
810 (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
813 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value >
814 BULK_DELAY_THRESHOLD) || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
819 strncpy (last_bulk, buf, sizeof (last_bulk));
820 last_bulk_repeat = 0;
821 last_bulk_kind = kind;
822 last_bulk_time = GNUNET_TIME_absolute_get ();
823 strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
824 output_message (kind, comp, date, buf);
832 * @param kind how serious is the error?
833 * @param message what is the message (format string)
834 * @param ... arguments for format string
837 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
841 va_start (va, message);
842 mylog (kind, component, message, va);
848 * Log function that specifies an alternative component.
849 * This function should be used by plugins.
851 * @param kind how serious is the error?
852 * @param comp component responsible for generating the message
853 * @param message what is the message (format string)
854 * @param ... arguments for format string
857 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
858 const char *message, ...)
861 char comp_w_pid[128];
864 comp = component_nopid;
866 va_start (va, message);
867 GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
868 mylog (kind, comp_w_pid, message, va);
874 * Convert error type to string.
876 * @param kind type to convert
877 * @return string corresponding to the type
880 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
882 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
884 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
886 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
888 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
890 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
897 * Convert a hash to a string (for printing debug messages).
898 * This is one of the very few calls in the entire API that is
901 * @param hc the hash code
902 * @return string form; will be overwritten by next call to GNUNET_h2s.
905 GNUNET_h2s (const GNUNET_HashCode * hc)
907 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
909 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
910 ret.encoding[8] = '\0';
911 return (const char *) ret.encoding;
915 * Convert a hash to a string (for printing debug messages).
916 * This is one of the very few calls in the entire API that is
919 * @param hc the hash code
920 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
923 GNUNET_h2s_full (const GNUNET_HashCode * hc)
925 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
927 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
928 ret.encoding[sizeof (ret) - 1] = '\0';
929 return (const char *) ret.encoding;
933 * Convert a peer identity to a string (for printing debug messages).
934 * This is one of the very few calls in the entire API that is
937 * @param pid the peer identity
938 * @return string form of the pid; will be overwritten by next
939 * call to GNUNET_i2s.
942 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
944 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
946 GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
947 ret.encoding[4] = '\0';
948 return (const char *) ret.encoding;
954 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
955 * (for printing debug messages). This is one of the very few calls
956 * in the entire API that is NOT reentrant!
958 * @param addr the address
959 * @param addrlen the length of the address
960 * @return nicely formatted string for the address
961 * will be overwritten by next call to GNUNET_a2s.
964 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
966 static char buf[INET6_ADDRSTRLEN + 8];
968 const struct sockaddr_in *v4;
969 const struct sockaddr_un *un;
970 const struct sockaddr_in6 *v6;
974 return _("unknown address");
975 switch (addr->sa_family)
978 if (addrlen != sizeof (struct sockaddr_in))
979 return "<invalid v4 address>";
980 v4 = (const struct sockaddr_in *) addr;
981 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
982 if (0 == ntohs (v4->sin_port))
985 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
989 if (addrlen != sizeof (struct sockaddr_in6))
990 return "<invalid v4 address>";
991 v6 = (const struct sockaddr_in6 *) addr;
993 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
994 if (0 == ntohs (v6->sin6_port))
997 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1001 if (addrlen <= sizeof (sa_family_t))
1002 return "<unbound UNIX client>";
1003 un = (const struct sockaddr_un *) addr;
1005 if (un->sun_path[0] == '\0')
1007 snprintf (buf, sizeof (buf), "%s%.*s", (off == 1) ? "@" : "",
1008 (int) (addrlen - sizeof (sa_family_t) - 1 - off),
1009 &un->sun_path[off]);
1012 return _("invalid address");
1020 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
1022 GNUNET_stderr = stderr;
1024 GNInitWinEnv (NULL);
1032 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
1035 GNShutdownWinEnv ();
1039 /* end of common_logging.c */