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));
264 * Utility function - adds a parsed definition to logdefs array.
266 * @param component see struct LogDef, can't be NULL
267 * @param file see struct LogDef, can't be NULL
268 * @param function see struct LogDef, can't be NULL
269 * @param from_line see struct LogDef
270 * @param to_line see struct LogDef
271 * @param level see struct LogDef, must be >= 0
272 * @param force see struct LogDef
273 * @return 0 on success, regex-specific error otherwise
276 add_definition (char *component, char *file, char *function, int from_line,
277 int to_line, int level, int force)
281 if (logdefs_size == logdefs_len)
283 memset (&n, 0, sizeof (n));
284 if (strlen (component) == 0)
285 component = (char *) ".*";
286 r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
291 if (strlen (file) == 0)
292 file = (char *) ".*";
293 r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
296 regfree (&n.component_regex);
299 if ( (NULL == function) ||
300 (strlen (function) == 0))
301 function = (char *) ".*";
302 r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
305 regfree (&n.component_regex);
306 regfree (&n.file_regex);
309 n.from_line = from_line;
313 logdefs[logdefs_len++] = n;
319 * Decides whether a particular logging call should or should not be allowed
320 * to be made. Used internally by GNUNET_log*()
322 * @param caller_level loglevel the caller wants to use
323 * @param comp component name the caller uses (NULL means that global
324 * component name is used)
325 * @param file file name containing the logging call, usually __FILE__
326 * @param function function which tries to make a logging call,
327 * usually __FUNCTION__
328 * @param line line at which the call is made, usually __LINE__
329 * @return 0 to disallow the call, 1 to allow it
332 GNUNET_get_log_call_status (int caller_level, const char *comp,
333 const char *file, const char *function, int line)
340 /* Use default component */
341 comp = component_nopid;
343 /* We have no definitions to override globally configured log level,
344 * so just use it right away.
346 if (min_level >= 0 && gnunet_force_log_present == GNUNET_NO)
347 return caller_level <= min_level;
349 /* Only look for forced definitions? */
350 force_only = min_level >= 0;
351 for (i = 0; i < logdefs_len; i++)
354 if ((!force_only || ld->force) &&
355 (line >= ld->from_line && line <= ld->to_line) &&
356 (regexec (&ld->component_regex, comp, 0, NULL, 0) == 0) &&
357 (regexec (&ld->file_regex, file, 0, NULL, 0) == 0) &&
358 (regexec (&ld->function_regex, function, 0, NULL, 0) == 0))
361 return caller_level <= ld->level;
364 /* No matches - use global level, if defined */
366 return caller_level <= min_level;
367 /* All programs/services previously defaulted to WARNING.
368 * Now WE default to WARNING, and THEY default to NULL.
370 return caller_level <= GNUNET_ERROR_TYPE_WARNING;
375 * Utility function - parses a definition
378 * component;file;function;from_line-to_line;level[/component...]
379 * All entries are mandatory, but may be empty.
380 * Empty entries for component, file and function are treated as
381 * "matches anything".
382 * Empty line entry is treated as "from 0 to INT_MAX"
383 * Line entry with only one line is treated as "this line only"
384 * Entry for level MUST NOT be empty.
385 * Entries for component, file and function that consist of a
386 * single character "*" are treated (at the moment) the same way
387 * empty entries are treated (wildcard matching is not implemented (yet?)).
388 * file entry is matched to the end of __FILE__. That is, it might be
389 * a base name, or a base name with leading directory names (some compilers
390 * define __FILE__ to absolute file path).
392 * @param constname name of the environment variable from which to get the
393 * string to be parsed
394 * @param force 1 if definitions found in @constname are to be forced
395 * @return number of added definitions
398 parse_definitions (const char *constname, int force)
404 char *function = NULL;
410 int from_line, to_line;
412 int keep_looking = 1;
414 tmp = getenv (constname);
417 def = GNUNET_strdup (tmp);
421 for (p = def, state = 0, start = def; keep_looking; p++)
425 case ';': /* found a field separator */
429 case 0: /* within a component name */
432 case 1: /* within a file name */
435 case 2: /* within a function name */
436 /* after a file name there must be a function name */
439 case 3: /* within a from-to line range */
440 if (strlen (start) > 0)
443 from_line = strtol (start, &t, 10);
444 if (errno != 0 || from_line < 0)
449 if (t < p && t[0] == '-')
453 to_line = strtol (start, &t, 10);
454 if (errno != 0 || to_line < 0 || t != p)
460 else /* one number means "match this line only" */
463 else /* default to 0-max */
473 case '\0': /* found EOL */
475 /* fall through to '/' */
476 case '/': /* found a definition separator */
479 case 4: /* within a log level */
482 level = get_type ((const char *) start);
483 if (level == GNUNET_ERROR_TYPE_INVALID
484 || level == GNUNET_ERROR_TYPE_UNSPECIFIED
485 || 0 != add_definition (comp, file, function, from_line,
486 to_line, level, force))
506 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
509 parse_all_definitions ()
511 if (gnunet_log_parsed == GNUNET_NO)
512 parse_definitions ("GNUNET_LOG", 0);
513 gnunet_log_parsed = GNUNET_YES;
514 if (gnunet_force_log_parsed == GNUNET_NO)
515 gnunet_force_log_present =
516 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
517 gnunet_force_log_parsed = GNUNET_YES;
523 * @param comp default component to use
524 * @param loglevel what types of messages should be logged
525 * @param logfile which file to write log messages to (can be NULL)
526 * @return GNUNET_OK on success
529 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
534 const char *env_logfile = NULL;
536 min_level = get_type (loglevel);
537 #if !defined(GNUNET_CULL_LOGGING)
538 parse_all_definitions ();
541 QueryPerformanceFrequency (&performance_frequency);
543 GNUNET_free_non_null (component);
544 GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
545 GNUNET_free_non_null (component_nopid);
546 component_nopid = GNUNET_strdup (comp);
548 env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
549 if ( (env_logfile != NULL) &&
550 (strlen (env_logfile) > 0) )
551 logfile = env_logfile;
555 fn = GNUNET_STRINGS_filename_expand (logfile);
557 return GNUNET_SYSERR;
558 dirwarn = (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn));
559 altlog = FOPEN (fn, "a");
562 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", fn);
564 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
565 _("Failed to create or access directory for log file `%s'\n"),
568 return GNUNET_SYSERR;
571 if (GNUNET_stderr != NULL)
572 fclose (GNUNET_stderr);
573 GNUNET_stderr = altlog;
578 * Add a custom logger.
580 * @param logger log function
581 * @param logger_cls closure for logger
584 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
586 struct CustomLogger *entry;
588 entry = GNUNET_malloc (sizeof (struct CustomLogger));
589 entry->logger = logger;
590 entry->logger_cls = logger_cls;
591 entry->next = loggers;
596 * Remove a custom logger.
598 * @param logger log function
599 * @param logger_cls closure for logger
602 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
604 struct CustomLogger *pos;
605 struct CustomLogger *prev;
609 while ((pos != NULL) &&
610 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
615 GNUNET_assert (pos != NULL);
619 prev->next = pos->next;
625 * Actually output the log message.
627 * @param kind how severe was the issue
628 * @param comp component responsible
629 * @param datestr current date/time
630 * @param msg the actual message
633 output_message (enum GNUNET_ErrorType kind, const char *comp,
634 const char *datestr, const char *msg)
636 struct CustomLogger *pos;
638 if (GNUNET_stderr != NULL)
640 fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp,
641 GNUNET_error_type_to_string (kind), msg);
642 fflush (GNUNET_stderr);
647 pos->logger (pos->logger_cls, kind, comp, datestr, msg);
654 * Flush an existing bulk report to the output.
656 * @param datestr our current timestamp
659 flush_bulk (const char *datestr)
661 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
666 if ((last_bulk_time.abs_value == 0) || (last_bulk_repeat == 0))
669 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
671 last = &last_bulk[BULK_TRACK_SIZE - 1];
672 else if (last != last_bulk)
679 ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
681 snprintf (msg, sizeof (msg),
682 _("Message `%.*s' repeated %u times in the last %s\n"),
683 BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
687 output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
688 last_bulk_time = GNUNET_TIME_absolute_get ();
689 last_bulk_repeat = 0;
694 * Ignore the next n calls to the log function.
696 * @param n number of log calls to ignore
697 * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
700 GNUNET_log_skip (unsigned int n, int check_reset)
706 ok = (0 == skip_log);
717 * Output a log message using the default mechanism.
719 * @param kind how severe was the issue
720 * @param comp component responsible
721 * @param message the actual message
722 * @param va arguments to the format string "message"
725 mylog (enum GNUNET_ErrorType kind, const char *comp, const char *message,
728 char date[DATE_STR_SIZE];
729 char date2[DATE_STR_SIZE];
731 struct timeval timeofday;
737 size = VSNPRINTF (NULL, 0, message, vacp) + 1;
738 GNUNET_assert (0 != size);
743 VSNPRINTF (buf, size, message, va);
745 memset (date, 0, DATE_STR_SIZE);
746 tmptr = localtime (&timetmp);
747 gettimeofday (&timeofday, NULL);
754 QueryPerformanceCounter (&pc);
755 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
756 snprintf (date, sizeof (date), date2,
757 (long long) (pc.QuadPart /
758 (performance_frequency.QuadPart / 1000)));
760 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
761 snprintf (date, sizeof (date), date2, timeofday.tv_usec);
765 strcpy (date, "localtime error");
766 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
767 (last_bulk_time.abs_value != 0) &&
768 (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
771 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value >
772 BULK_DELAY_THRESHOLD) || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
777 strncpy (last_bulk, buf, sizeof (last_bulk));
778 last_bulk_repeat = 0;
779 last_bulk_kind = kind;
780 last_bulk_time = GNUNET_TIME_absolute_get ();
781 strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
782 output_message (kind, comp, date, buf);
790 * @param kind how serious is the error?
791 * @param message what is the message (format string)
792 * @param ... arguments for format string
795 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
799 va_start (va, message);
800 mylog (kind, component, message, va);
806 * Log function that specifies an alternative component.
807 * This function should be used by plugins.
809 * @param kind how serious is the error?
810 * @param comp component responsible for generating the message
811 * @param message what is the message (format string)
812 * @param ... arguments for format string
815 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
816 const char *message, ...)
819 char comp_w_pid[128];
822 comp = component_nopid;
824 va_start (va, message);
825 GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
826 mylog (kind, comp_w_pid, message, va);
832 * Convert error type to string.
834 * @param kind type to convert
835 * @return string corresponding to the type
838 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
840 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
842 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
844 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
846 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
848 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
855 * Convert a hash to a string (for printing debug messages).
856 * This is one of the very few calls in the entire API that is
859 * @param hc the hash code
860 * @return string form; will be overwritten by next call to GNUNET_h2s.
863 GNUNET_h2s (const GNUNET_HashCode * hc)
865 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
867 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
868 ret.encoding[8] = '\0';
869 return (const char *) ret.encoding;
873 * Convert a hash to a string (for printing debug messages).
874 * This is one of the very few calls in the entire API that is
877 * @param hc the hash code
878 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
881 GNUNET_h2s_full (const GNUNET_HashCode * hc)
883 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
885 GNUNET_CRYPTO_hash_to_enc (hc, &ret);
886 ret.encoding[sizeof (ret) - 1] = '\0';
887 return (const char *) ret.encoding;
891 * Convert a peer identity to a string (for printing debug messages).
892 * This is one of the very few calls in the entire API that is
895 * @param pid the peer identity
896 * @return string form of the pid; will be overwritten by next
897 * call to GNUNET_i2s.
900 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
902 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
904 GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
905 ret.encoding[4] = '\0';
906 return (const char *) ret.encoding;
912 * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
913 * (for printing debug messages). This is one of the very few calls
914 * in the entire API that is NOT reentrant!
916 * @param addr the address
917 * @param addrlen the length of the address
918 * @return nicely formatted string for the address
919 * will be overwritten by next call to GNUNET_a2s.
922 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
924 static char buf[INET6_ADDRSTRLEN + 8];
926 const struct sockaddr_in *v4;
927 const struct sockaddr_un *un;
928 const struct sockaddr_in6 *v6;
932 return _("unknown address");
933 switch (addr->sa_family)
936 if (addrlen != sizeof (struct sockaddr_in))
937 return "<invalid v4 address>";
938 v4 = (const struct sockaddr_in *) addr;
939 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
940 if (0 == ntohs (v4->sin_port))
943 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
947 if (addrlen != sizeof (struct sockaddr_in6))
948 return "<invalid v4 address>";
949 v6 = (const struct sockaddr_in6 *) addr;
951 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
952 if (0 == ntohs (v6->sin6_port))
955 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
959 if (addrlen <= sizeof (sa_family_t))
960 return "<unbound UNIX client>";
961 un = (const struct sockaddr_un *) addr;
963 if (un->sun_path[0] == '\0')
965 snprintf (buf, sizeof (buf), "%s%.*s", (off == 1) ? "@" : "",
966 (int) (addrlen - sizeof (sa_family_t) - 1 - off),
970 return _("invalid address");
978 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
980 GNUNET_stderr = stderr;
990 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
997 /* end of common_logging.c */