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"
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 * 1000)
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 * Linked list of active loggers.
70 * This is a linked list.
72 struct CustomLogger *next;
86 * The last "bulk" error message that we have been logging.
87 * Note that this message maybe truncated to the first BULK_TRACK_SIZE
88 * characters, in which case it is NOT 0-terminated!
90 static char last_bulk[BULK_TRACK_SIZE];
93 * Type of the last bulk message.
95 static enum GNUNET_ErrorType last_bulk_kind;
98 * Time of the last bulk error message (0 for none)
100 static struct GNUNET_TIME_Absolute last_bulk_time;
103 * Number of times that bulk message has been repeated since.
105 static unsigned int last_bulk_repeat;
108 * Component when the last bulk was logged. Will be 0-terminated.
110 static char last_bulk_comp[COMP_TRACK_SIZE + 1];
115 static char *component;
118 * Running component (without pid).
120 static char *component_nopid;
125 static enum GNUNET_ErrorType min_level;
128 * Linked list of our custom loggres.
130 static struct CustomLogger *loggers;
133 * Number of log calls to ignore.
135 unsigned int skip_log;
138 * File descriptor to use for "stderr", or NULL for none.
140 static FILE *GNUNET_stderr;
143 * Represents a single logging definition
148 * Component name. NULL means that this definition matches any component
153 * File name. NULL means that this definition matches any file
158 * Stores strlen(file)
163 * Function name. NULL means that this definition matches any function
168 * Lowest line at which this definition matches.
169 * Defaults to 0. Must be <= to_line.
174 * Highest line at which this definition matches.
175 * Defaults to INT_MAX. Must be >= from_line.
180 * Maximal log level allowed for calls that match this definition.
181 * Calls with higher log level will be disabled.
187 * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
188 * overrides any configuration options. 0 otherwise.
194 * Dynamic array of logging definitions
196 struct LogDef *logdefs = NULL;
199 * Allocated size of logdefs array (in units)
201 int logdefs_size = 0;
204 * The number of units used in logdefs array.
209 * GNUNET_YES if GNUNET_LOG environment variable is already parsed.
211 int gnunet_log_parsed = GNUNET_NO;
214 * GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
216 int gnunet_force_log_parsed = GNUNET_NO;
219 * GNUNET_YES if at least one definition with forced == 1 is available.
221 int gnunet_force_log_present = GNUNET_NO;
225 * Contains the number of performance counts per second.
227 LARGE_INTEGER performance_frequency;
231 * Convert a textual description of a loglevel
232 * to the respective GNUNET_GE_KIND.
234 * @param log loglevel to parse
235 * @return GNUNET_GE_INVALID if log does not parse
237 static enum GNUNET_ErrorType
238 get_type (const char *log)
241 return GNUNET_ERROR_TYPE_UNSPECIFIED;
242 if (0 == strcasecmp (log, _("DEBUG")))
243 return GNUNET_ERROR_TYPE_DEBUG;
244 if (0 == strcasecmp (log, _("INFO")))
245 return GNUNET_ERROR_TYPE_INFO;
246 if (0 == strcasecmp (log, _("WARNING")))
247 return GNUNET_ERROR_TYPE_WARNING;
248 if (0 == strcasecmp (log, _("ERROR")))
249 return GNUNET_ERROR_TYPE_ERROR;
250 if (0 == strcasecmp (log, _("NONE")))
251 return GNUNET_ERROR_TYPE_NONE;
252 return GNUNET_ERROR_TYPE_INVALID;
255 #if !defined(GNUNET_CULL_LOGGING)
257 * Utility function - reallocates logdefs array to be twice as large.
262 logdefs_size = (logdefs_size + 1) * 2;
263 logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
267 * Utility function - adds a parsed definition to logdefs array.
269 * @param component see struct LogDef, can't be NULL
270 * @param file see struct LogDef, can't be NULL
271 * @param function see struct LogDef, can't be NULL
272 * @param from_line see struct LogDef
273 * @param to_line see struct LogDef
274 * @param level see struct LogDef, must be >= 0
275 * @param force see struct LogDef
278 add_definition (char *component, char *file, char *function, int from_line,
279 int to_line, int level, int force)
281 if (logdefs_size == logdefs_len)
285 memset (&n, 0, sizeof (n));
286 if (strlen (component) > 0 && component[0] != '*')
287 n.component = GNUNET_strdup (component);
288 if (strlen (file) > 0 && file[0] != '*')
290 n.file = GNUNET_strdup (file);
291 n.strlen_file = strlen (file);
293 if ((NULL != function) && (strlen (function) > 0) && (function[0] != '*'))
294 n.function = GNUNET_strdup (function);
295 n.from_line = from_line;
299 logdefs[logdefs_len++] = n;
304 * Decides whether a particular logging call should or should not be allowed
305 * to be made. Used internally by GNUNET_log*()
307 * @param caller_level loglevel the caller wants to use
308 * @param comp component name the caller uses (NULL means that global
309 * component name is used)
310 * @param file file name containing the logging call, usually __FILE__
311 * @param function function which tries to make a logging call,
312 * usually __FUNCTION__
313 * @param line line at which the call is made, usually __LINE__
314 * @return 0 to disallow the call, 1 to allow it
317 GNUNET_get_log_call_status (int caller_level, const char *comp,
318 const char *file, const char *function, int line)
326 /* Use default component */
327 comp = component_nopid;
329 /* We have no definitions to override globally configured log level,
330 * so just use it right away.
332 if (min_level >= 0 && gnunet_force_log_present == GNUNET_NO)
333 return caller_level <= min_level;
335 /* Only look for forced definitions? */
336 force_only = min_level >= 0;
337 strlen_file = strlen (file);
338 for (i = 0; i < logdefs_len; i++)
341 if ((!force_only || ld->force) &&
342 (line >= ld->from_line && line <= ld->to_line) && (ld->component == NULL
347 (ld->strlen_file <= strlen_file &&
348 strcmp (&file[strlen_file - ld->strlen_file], ld->file) == 0)) &&
349 (ld->function == NULL || strcmp (function, ld->function) == 0))
352 return caller_level <= ld->level;
355 /* No matches - use global level, if defined */
357 return caller_level <= min_level;
358 /* All programs/services previously defaulted to WARNING.
359 * Now WE default to WARNING, and THEY default to NULL.
361 return caller_level <= GNUNET_ERROR_TYPE_WARNING;
366 * Utility function - parses a definition
369 * component;file;function;from_line-to_line;level[/component...]
370 * All entries are mandatory, but may be empty.
371 * Empty entries for component, file and function are treated as
372 * "matches anything".
373 * Empty line entry is treated as "from 0 to INT_MAX"
374 * Line entry with only one line is treated as "this line only"
375 * Entry for level MUST NOT be empty.
376 * Entries for component, file and function that consist of a
377 * single character "*" are treated (at the moment) the same way
378 * empty entries are treated (wildcard matching is not implemented (yet?)).
379 * file entry is matched to the end of __FILE__. That is, it might be
380 * a base name, or a base name with leading directory names (some compilers
381 * define __FILE__ to absolute file path).
383 * @param constname name of the environment variable from which to get the
384 * string to be parsed
385 * @param force 1 if definitions found in @constname are to be forced
386 * @return number of added definitions
389 parse_definitions (const char *constname, int force)
395 char *function = NULL;
401 int from_line, to_line;
403 int keep_looking = 1;
405 tmp = getenv (constname);
408 def = GNUNET_strdup (tmp);
412 for (p = def, state = 0, start = def; keep_looking; p++)
416 case ';': /* found a field separator */
420 case 0: /* within a component name */
423 case 1: /* within a file name */
426 case 2: /* within a function name */
427 /* after a file name there must be a function name */
430 case 3: /* within a from-to line range */
431 if (strlen (start) > 0)
434 from_line = strtol (start, &t, 10);
435 if (errno != 0 || from_line < 0)
440 if (t < p && t[0] == '-')
444 to_line = strtol (start, &t, 10);
445 if (errno != 0 || to_line < 0 || t != p)
451 else /* one number means "match this line only" */
454 else /* default to 0-max */
464 case '\0': /* found EOL */
466 /* fall through to '/' */
467 case '/': /* found a definition separator */
470 case 4: /* within a log level */
473 level = get_type ((const char *) start);
474 if (level == GNUNET_ERROR_TYPE_INVALID ||
475 level == GNUNET_ERROR_TYPE_UNSPECIFIED)
480 add_definition (comp, file, function, from_line, to_line, level, force);
496 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
499 parse_all_definitions ()
501 if (gnunet_log_parsed == GNUNET_NO)
502 parse_definitions ("GNUNET_LOG", 0);
503 gnunet_log_parsed = GNUNET_YES;
504 if (gnunet_force_log_parsed == GNUNET_NO)
505 gnunet_force_log_present =
506 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
507 gnunet_force_log_parsed = GNUNET_YES;
513 * @param comp default component to use
514 * @param loglevel what types of messages should be logged
515 * @param logfile which file to write log messages to (can be NULL)
516 * @return GNUNET_OK on success
519 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
524 const char *env_logfile = NULL;
526 min_level = get_type (loglevel);
527 #if !defined(GNUNET_CULL_LOGGING)
528 parse_all_definitions ();
531 QueryPerformanceFrequency (&performance_frequency);
533 GNUNET_free_non_null (component);
534 GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
535 GNUNET_free_non_null (component_nopid);
536 component_nopid = GNUNET_strdup (comp);
538 env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
539 if (env_logfile != NULL)
540 logfile = env_logfile;
544 fn = GNUNET_STRINGS_filename_expand (logfile);
546 return GNUNET_SYSERR;
547 dirwarn = (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn));
548 altlog = FOPEN (fn, "a");
551 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", fn);
553 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
554 _("Failed to create or access directory for log file `%s'\n"),
557 return GNUNET_SYSERR;
560 if (GNUNET_stderr != NULL)
561 fclose (GNUNET_stderr);
562 GNUNET_stderr = altlog;
567 * Add a custom logger.
569 * @param logger log function
570 * @param logger_cls closure for logger
573 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
575 struct CustomLogger *entry;
577 entry = GNUNET_malloc (sizeof (struct CustomLogger));
578 entry->logger = logger;
579 entry->logger_cls = logger_cls;
580 entry->next = loggers;
585 * Remove a custom logger.
587 * @param logger log function
588 * @param logger_cls closure for logger
591 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
593 struct CustomLogger *pos;
594 struct CustomLogger *prev;
598 while ((pos != NULL) &&
599 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
604 GNUNET_assert (pos != NULL);
608 prev->next = pos->next;
614 * Actually output the log message.
616 * @param kind how severe was the issue
617 * @param comp component responsible
618 * @param datestr current date/time
619 * @param msg the actual message
622 output_message (enum GNUNET_ErrorType kind, const char *comp,
623 const char *datestr, const char *msg)
625 struct CustomLogger *pos;
627 if (GNUNET_stderr != NULL)
629 fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp,
630 GNUNET_error_type_to_string (kind), msg);
631 fflush (GNUNET_stderr);
636 pos->logger (pos->logger_cls, kind, comp, datestr, msg);
643 * Flush an existing bulk report to the output.
645 * @param datestr our current timestamp
648 flush_bulk (const char *datestr)
650 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
655 if ((last_bulk_time.abs_value == 0) || (last_bulk_repeat == 0))
658 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
660 last = &last_bulk[BULK_TRACK_SIZE - 1];
661 else if (last != last_bulk)
668 ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
670 snprintf (msg, sizeof (msg),
671 _("Message `%.*s' repeated %u times in the last %s\n"),
672 BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
676 output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
677 last_bulk_time = GNUNET_TIME_absolute_get ();
678 last_bulk_repeat = 0;
683 * Ignore the next n calls to the log function.
685 * @param n number of log calls to ignore
686 * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
689 GNUNET_log_skip (unsigned int n, int check_reset)
695 ok = (0 == skip_log);
706 * Output a log message using the default mechanism.
708 * @param kind how severe was the issue
709 * @param comp component responsible
710 * @param message the actual message
711 * @param va arguments to the format string "message"
714 mylog (enum GNUNET_ErrorType kind, const char *comp, const char *message,
717 char date[DATE_STR_SIZE];
718 char date2[DATE_STR_SIZE];
720 struct timeval timeofday;
726 size = VSNPRINTF (NULL, 0, message, vacp) + 1;
727 GNUNET_assert (0 != size);
732 VSNPRINTF (buf, size, message, va);
734 memset (date, 0, DATE_STR_SIZE);
735 tmptr = localtime (&timetmp);
736 gettimeofday (&timeofday, NULL);
743 QueryPerformanceCounter (&pc);
744 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
745 snprintf (date, sizeof (date), date2,
746 (long long) (pc.QuadPart /
747 (performance_frequency.QuadPart / 1000)));
749 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
750 snprintf (date, sizeof (date), date2, timeofday.tv_usec);
754 strcpy (date, "localtime error");
755 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
756 (last_bulk_time.abs_value != 0) &&
757 (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
760 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value >
761 BULK_DELAY_THRESHOLD) || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
766 strncpy (last_bulk, buf, sizeof (last_bulk));
767 last_bulk_repeat = 0;
768 last_bulk_kind = kind;
769 last_bulk_time = GNUNET_TIME_absolute_get ();
770 strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
771 output_message (kind, comp, date, buf);
779 * @param kind how serious is the error?
780 * @param message what is the message (format string)
781 * @param ... arguments for format string
784 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
788 va_start (va, message);
789 mylog (kind, component, message, va);
795 * Log function that specifies an alternative component.
796 * This function should be used by plugins.
798 * @param kind how serious is the error?
799 * @param comp component responsible for generating the message
800 * @param message what is the message (format string)
801 * @param ... arguments for format string
804 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
805 const char *message, ...)
808 char comp_w_pid[128];
811 comp = component_nopid;
813 va_start (va, message);
814 GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
815 mylog (kind, comp_w_pid, message, va);
821 * Convert error type to string.
823 * @param kind type to convert
824 * @return string corresponding to the type
827 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
829 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
831 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
833 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
835 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
837 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
844 * Convert a hash to a string (for printing debug messages).
845 * This is one of the very few calls in the entire API that is
848 * @param hc the hash code
849 * @return string form; will be overwritten by next call to GNUNET_h2s.
852 GNUNET_h2s (const GNUNET_HashCode * hc)
854 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
856 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
857 ret.encoding[8] = '\0';
858 return (const char *) ret.encoding;
862 * Convert a hash to a string (for printing debug messages).
863 * This is one of the very few calls in the entire API that is
866 * @param hc the hash code
867 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
870 GNUNET_h2s_full (const GNUNET_HashCode * hc)
872 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
874 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
875 ret.encoding[sizeof (ret) - 1] = '\0';
876 return (const char *) ret.encoding;
880 * Convert a peer identity to a string (for printing debug messages).
881 * This is one of the very few calls in the entire API that is
884 * @param pid the peer identity
885 * @return string form of the pid; will be overwritten by next
886 * call to GNUNET_i2s.
889 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
891 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
893 GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
894 ret.encoding[4] = '\0';
895 return (const char *) ret.encoding;
901 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
902 * (for printing debug messages). This is one of the very few calls
903 * in the entire API that is NOT reentrant!
905 * @param addr the address
906 * @param addrlen the length of the address
907 * @return nicely formatted string for the address
908 * will be overwritten by next call to GNUNET_a2s.
911 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
913 static char buf[INET6_ADDRSTRLEN + 8];
915 const struct sockaddr_in *v4;
916 const struct sockaddr_un *un;
917 const struct sockaddr_in6 *v6;
921 return _("unknown address");
922 switch (addr->sa_family)
925 if (addrlen != sizeof (struct sockaddr_in))
926 return "<invalid v4 address>";
927 v4 = (const struct sockaddr_in *) addr;
928 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
929 if (0 == ntohs (v4->sin_port))
932 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
936 if (addrlen != sizeof (struct sockaddr_in6))
937 return "<invalid v4 address>";
938 v6 = (const struct sockaddr_in6 *) addr;
940 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
941 if (0 == ntohs (v6->sin6_port))
944 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
948 if (addrlen <= sizeof (sa_family_t))
949 return "<unbound UNIX client>";
950 un = (const struct sockaddr_un *) addr;
952 if (un->sun_path[0] == '\0')
954 snprintf (buf, sizeof (buf), "%s%.*s", (off == 1) ? "@" : "",
955 (int) (addrlen - sizeof (sa_family_t) - 1 - off),
959 return _("invalid address");
967 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
969 GNUNET_stderr = stderr;
979 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
986 /* end of common_logging.c */