-rps: logging
[oweals/gnunet.git] / src / util / common_logging.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2006-2013 GNUnet e.V.
4
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 3, or (at your
8      option) any later version.
9
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.
14
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/common_logging.c
23  * @brief error handling API
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_strings_lib.h"
29 #include <regex.h>
30
31
32 /**
33  * After how many milliseconds do we always print
34  * that "message X was repeated N times"?  Use 12h.
35  */
36 #define BULK_DELAY_THRESHOLD (12 * 60 * 60 * 1000LL * 1000LL)
37
38 /**
39  * After how many repetitions do we always print
40  * that "message X was repeated N times"? (even if
41  * we have not yet reached the delay threshold)
42  */
43 #define BULK_REPEAT_THRESHOLD 1000
44
45 /**
46  * How many characters do we use for matching of
47  * bulk messages?
48  */
49 #define BULK_TRACK_SIZE 256
50
51 /**
52  * How many characters do we use for matching of
53  * bulk components?
54  */
55 #define COMP_TRACK_SIZE 32
56
57 /**
58  * How many characters can a date/time string
59  * be at most?
60  */
61 #define DATE_STR_SIZE 64
62
63 /**
64  * How many log files to keep?
65  */
66 #define ROTATION_KEEP 3
67
68 #ifndef PATH_MAX
69 /**
70  * Assumed maximum path length (for the log file name).
71  */
72 #define PATH_MAX 4096
73 #endif
74
75
76 /**
77  * Linked list of active loggers.
78  */
79 struct CustomLogger
80 {
81   /**
82    * This is a linked list.
83    */
84   struct CustomLogger *next;
85
86   /**
87    * Log function.
88    */
89   GNUNET_Logger logger;
90
91   /**
92    * Closure for logger.
93    */
94   void *logger_cls;
95 };
96
97 /**
98  * The last "bulk" error message that we have been logging.
99  * Note that this message maybe truncated to the first BULK_TRACK_SIZE
100  * characters, in which case it is NOT 0-terminated!
101  */
102 static char last_bulk[BULK_TRACK_SIZE];
103
104 /**
105  * Type of the last bulk message.
106  */
107 static enum GNUNET_ErrorType last_bulk_kind;
108
109 /**
110  * Time of the last bulk error message (0 for none)
111  */
112 static struct GNUNET_TIME_Absolute last_bulk_time;
113
114 /**
115  * Number of times that bulk message has been repeated since.
116  */
117 static unsigned int last_bulk_repeat;
118
119 /**
120  * Component when the last bulk was logged.  Will be 0-terminated.
121  */
122 static char last_bulk_comp[COMP_TRACK_SIZE + 1];
123
124 /**
125  * Running component.
126  */
127 static char *component;
128
129 /**
130  * Running component (without pid).
131  */
132 static char *component_nopid;
133
134 /**
135  * Format string describing the name of the log file.
136  */
137 static char *log_file_name;
138
139 /**
140  * Minimum log level.
141  */
142 static enum GNUNET_ErrorType min_level;
143
144 /**
145  * Linked list of our custom loggres.
146  */
147 static struct CustomLogger *loggers;
148
149 /**
150  * Number of log calls to ignore.
151  */
152 static int skip_log = 0;
153
154 /**
155  * File descriptor to use for "stderr", or NULL for none.
156  */
157 static FILE *GNUNET_stderr;
158
159 /**
160  * Represents a single logging definition
161  */
162 struct LogDef
163 {
164   /**
165    * Component name regex
166    */
167   regex_t component_regex;
168
169   /**
170    * File name regex
171    */
172   regex_t file_regex;
173
174   /**
175    * Function name regex
176    */
177   regex_t function_regex;
178
179   /**
180    * Lowest line at which this definition matches.
181    * Defaults to 0. Must be <= to_line.
182    */
183   int from_line;
184
185   /**
186    * Highest line at which this definition matches.
187    * Defaults to INT_MAX. Must be >= from_line.
188    */
189   int to_line;
190
191   /**
192    * Maximal log level allowed for calls that match this definition.
193    * Calls with higher log level will be disabled.
194    * Must be >= 0
195    */
196   int level;
197
198   /**
199    * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
200    * overrides any configuration options. 0 otherwise.
201    */
202   int force;
203 };
204
205 /**
206  * Dynamic array of logging definitions
207  */
208 static struct LogDef *logdefs;
209
210 /**
211  * Allocated size of logdefs array (in units)
212  */
213 static int logdefs_size;
214
215 /**
216  * The number of units used in logdefs array.
217  */
218 static int logdefs_len;
219
220 /**
221  * GNUNET_YES if GNUNET_LOG environment variable is already parsed.
222  */
223 static int gnunet_log_parsed;
224
225 /**
226  * GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
227  */
228 static int gnunet_force_log_parsed;
229
230 /**
231  * GNUNET_YES if at least one definition with forced == 1 is available.
232  */
233 static int gnunet_force_log_present;
234
235 #ifdef WINDOWS
236 /**
237  * Contains the number of performance counts per second.
238  */
239 static LARGE_INTEGER performance_frequency;
240 #endif
241
242
243 /**
244  * Convert a textual description of a loglevel
245  * to the respective GNUNET_GE_KIND.
246  *
247  * @param log loglevel to parse
248  * @return GNUNET_GE_INVALID if log does not parse
249  */
250 static enum GNUNET_ErrorType
251 get_type (const char *log)
252 {
253   if (NULL == log)
254     return GNUNET_ERROR_TYPE_UNSPECIFIED;
255   if (0 == strcasecmp (log, _("DEBUG")))
256     return GNUNET_ERROR_TYPE_DEBUG;
257   if (0 == strcasecmp (log, _("INFO")))
258     return GNUNET_ERROR_TYPE_INFO;
259   if (0 == strcasecmp (log, _("WARNING")))
260     return GNUNET_ERROR_TYPE_WARNING;
261   if (0 == strcasecmp (log, _("ERROR")))
262     return GNUNET_ERROR_TYPE_ERROR;
263   if (0 == strcasecmp (log, _("NONE")))
264     return GNUNET_ERROR_TYPE_NONE;
265   return GNUNET_ERROR_TYPE_INVALID;
266 }
267
268
269 #if !defined(GNUNET_CULL_LOGGING)
270 /**
271  * Utility function - reallocates logdefs array to be twice as large.
272  */
273 static void
274 resize_logdefs ()
275 {
276   logdefs_size = (logdefs_size + 1) * 2;
277   logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
278 }
279
280
281 /**
282  * Abort the process, generate a core dump if possible.
283  */
284 void
285 GNUNET_abort_ ()
286 {
287 #if WINDOWS
288   DebugBreak ();
289 #endif
290   abort ();
291 }
292
293
294 /**
295  * Rotate logs, deleting the oldest log.
296  *
297  * @param new_name new name to add to the rotation
298  */
299 static void
300 log_rotate (const char *new_name)
301 {
302   static char *rotation[ROTATION_KEEP];
303   static unsigned int rotation_off;
304   char *discard;
305
306   if ('\0' == *new_name)
307     return; /* not a real log file name */
308   discard = rotation[rotation_off % ROTATION_KEEP];
309   if (NULL != discard)
310   {
311     /* Note: can't log errors during logging (recursion!), so this
312        operation MUST silently fail... */
313     (void) UNLINK (discard);
314     GNUNET_free (discard);
315   }
316   rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup (new_name);
317   rotation_off++;
318 }
319
320
321 /**
322  * Setup the log file.
323  *
324  * @param tm timestamp for which we should setup logging
325  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
326  */
327 static int
328 setup_log_file (const struct tm *tm)
329 {
330   static char last_fn[PATH_MAX + 1];
331   char fn[PATH_MAX + 1];
332   int altlog_fd;
333   int dup_return;
334   FILE *altlog;
335   char *leftsquare;
336
337   if (NULL == log_file_name)
338     return GNUNET_SYSERR;
339   if (0 == strftime (fn, sizeof (fn), log_file_name, tm))
340     return GNUNET_SYSERR;
341   leftsquare = strrchr (fn, '[');
342   if ( (NULL != leftsquare) && (']' == leftsquare[1]) )
343   {
344     char *logfile_copy = GNUNET_strdup (fn);
345
346     logfile_copy[leftsquare - fn] = '\0';
347     logfile_copy[leftsquare - fn + 1] = '\0';
348     snprintf (fn,
349               PATH_MAX,
350               "%s%d%s",
351               logfile_copy,
352               getpid (),
353               &logfile_copy[leftsquare - fn + 2]);
354     GNUNET_free (logfile_copy);
355   }
356   if (0 == strcmp (fn, last_fn))
357     return GNUNET_OK; /* no change */
358   log_rotate (last_fn);
359   strcpy (last_fn, fn);
360 #if WINDOWS
361   altlog_fd = OPEN (fn, O_APPEND |
362                         O_BINARY |
363                         O_WRONLY | O_CREAT,
364                         _S_IREAD | _S_IWRITE);
365 #else
366   altlog_fd = OPEN (fn, O_APPEND |
367                         O_WRONLY | O_CREAT,
368                         S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
369 #endif
370   if (-1 != altlog_fd)
371   {
372     if (NULL != GNUNET_stderr)
373       fclose (GNUNET_stderr);
374     dup_return = dup2 (altlog_fd, 2);
375     (void) close (altlog_fd);
376     if (-1 != dup_return)
377     {
378       altlog = fdopen (2, "ab");
379       if (NULL == altlog)
380       {
381         (void) close (2);
382         altlog_fd = -1;
383       }
384     }
385     else
386     {
387       altlog_fd = -1;
388     }
389   }
390   if (-1 == altlog_fd)
391   {
392     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
393     return GNUNET_SYSERR;
394   }
395   GNUNET_stderr = altlog;
396   return GNUNET_OK;
397 }
398
399
400 /**
401  * Utility function - adds a parsed definition to logdefs array.
402  *
403  * @param component see struct LogDef, can't be NULL
404  * @param file see struct LogDef, can't be NULL
405  * @param function see struct LogDef, can't be NULL
406  * @param from_line see struct LogDef
407  * @param to_line see struct LogDef
408  * @param level see struct LogDef, must be >= 0
409  * @param force see struct LogDef
410  * @return 0 on success, regex-specific error otherwise
411  */
412 static int
413 add_definition (const char *component,
414                 const char *file,
415                 const char *function,
416                 int from_line,
417                 int to_line,
418                 int level,
419                 int force)
420 {
421   struct LogDef n;
422   int r;
423
424   if (logdefs_size == logdefs_len)
425     resize_logdefs ();
426   memset (&n, 0, sizeof (n));
427   if (0 == strlen (component))
428     component = (char *) ".*";
429   r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
430   if (0 != r)
431   {
432     return r;
433   }
434   if (0 == strlen (file))
435     file = (char *) ".*";
436   r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
437   if (0 != r)
438   {
439     regfree (&n.component_regex);
440     return r;
441   }
442   if ((NULL == function) || (0 == strlen (function)))
443     function = (char *) ".*";
444   r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
445   if (0 != r)
446   {
447     regfree (&n.component_regex);
448     regfree (&n.file_regex);
449     return r;
450   }
451   n.from_line = from_line;
452   n.to_line = to_line;
453   n.level = level;
454   n.force = force;
455   logdefs[logdefs_len++] = n;
456   return 0;
457 }
458
459
460 /**
461  * Decides whether a particular logging call should or should not be allowed
462  * to be made. Used internally by GNUNET_log*()
463  *
464  * @param caller_level loglevel the caller wants to use
465  * @param comp component name the caller uses (NULL means that global
466  *   component name is used)
467  * @param file file name containing the logging call, usually __FILE__
468  * @param function function which tries to make a logging call,
469  *   usually __FUNCTION__
470  * @param line line at which the call is made, usually __LINE__
471  * @return 0 to disallow the call, 1 to allow it
472  */
473 int
474 GNUNET_get_log_call_status (int caller_level,
475                             const char *comp,
476                             const char *file,
477                             const char *function,
478                             int line)
479 {
480   struct LogDef *ld;
481   int i;
482   int force_only;
483
484   if (NULL == comp)
485     /* Use default component */
486     comp = component_nopid;
487
488   /* We have no definitions to override globally configured log level,
489    * so just use it right away.
490    */
491   if ( (min_level >= 0) && (GNUNET_NO == gnunet_force_log_present) )
492     return caller_level <= min_level;
493
494   /* Only look for forced definitions? */
495   force_only = min_level >= 0;
496   for (i = 0; i < logdefs_len; i++)
497   {
498     ld = &logdefs[i];
499     if (( (!force_only) || ld->force) &&
500         (line >= ld->from_line && line <= ld->to_line) &&
501         (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
502         (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
503         (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
504     {
505       /* We're finished */
506       return caller_level <= ld->level;
507     }
508   }
509   /* No matches - use global level, if defined */
510   if (min_level >= 0)
511     return caller_level <= min_level;
512   /* All programs/services previously defaulted to WARNING.
513    * Now WE default to WARNING, and THEY default to NULL.
514    */
515   return caller_level <= GNUNET_ERROR_TYPE_WARNING;
516 }
517
518
519 /**
520  * Utility function - parses a definition
521  *
522  * Definition format:
523  * component;file;function;from_line-to_line;level[/component...]
524  * All entries are mandatory, but may be empty.
525  * Empty entries for component, file and function are treated as
526  * "matches anything".
527  * Empty line entry is treated as "from 0 to INT_MAX"
528  * Line entry with only one line is treated as "this line only"
529  * Entry for level MUST NOT be empty.
530  * Entries for component, file and function that consist of a
531  * single character "*" are treated (at the moment) the same way
532  * empty entries are treated (wildcard matching is not implemented (yet?)).
533  * file entry is matched to the end of __FILE__. That is, it might be
534  * a base name, or a base name with leading directory names (some compilers
535  * define __FILE__ to absolute file path).
536  *
537  * @param constname name of the environment variable from which to get the
538  *   string to be parsed
539  * @param force 1 if definitions found in constname are to be forced
540  * @return number of added definitions
541  */
542 static int
543 parse_definitions (const char *constname, int force)
544 {
545   char *def;
546   const char *tmp;
547   char *comp = NULL;
548   char *file = NULL;
549   char *function = NULL;
550   char *p;
551   char *start;
552   char *t;
553   short state;
554   int level;
555   int from_line, to_line;
556   int counter = 0;
557   int keep_looking = 1;
558
559   tmp = getenv (constname);
560   if (NULL == tmp)
561     return 0;
562   def = GNUNET_strdup (tmp);
563   from_line = 0;
564   to_line = INT_MAX;
565   for (p = def, state = 0, start = def; keep_looking; p++)
566   {
567     switch (p[0])
568     {
569     case ';':                  /* found a field separator */
570       p[0] = '\0';
571       switch (state)
572       {
573       case 0:                  /* within a component name */
574         comp = start;
575         break;
576       case 1:                  /* within a file name */
577         file = start;
578         break;
579       case 2:                  /* within a function name */
580         /* after a file name there must be a function name */
581         function = start;
582         break;
583       case 3:                  /* within a from-to line range */
584         if (strlen (start) > 0)
585         {
586           errno = 0;
587           from_line = strtol (start, &t, 10);
588           if ( (0 != errno) || (from_line < 0) )
589           {
590             GNUNET_free (def);
591             return counter;
592           }
593           if ( (t < p) && ('-' == t[0]) )
594           {
595             errno = 0;
596             start = t + 1;
597             to_line = strtol (start, &t, 10);
598             if ( (0 != errno) || (to_line < 0) || (t != p) )
599             {
600               GNUNET_free (def);
601               return counter;
602             }
603           }
604           else                  /* one number means "match this line only" */
605             to_line = from_line;
606         }
607         else                    /* default to 0-max */
608         {
609           from_line = 0;
610           to_line = INT_MAX;
611         }
612         break;
613       }
614       start = p + 1;
615       state++;
616       break;
617     case '\0':                 /* found EOL */
618       keep_looking = 0;
619       /* fall through to '/' */
620     case '/':                  /* found a definition separator */
621       switch (state)
622       {
623       case 4:                  /* within a log level */
624         p[0] = '\0';
625         state = 0;
626         level = get_type ((const char *) start);
627         if ( (GNUNET_ERROR_TYPE_INVALID == level) ||
628              (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
629              (0 != add_definition (comp, file, function, from_line, to_line,
630                                    level, force)) )
631         {
632           GNUNET_free (def);
633           return counter;
634         }
635         counter++;
636         start = p + 1;
637         break;
638       default:
639         break;
640       }
641     default:
642       break;
643     }
644   }
645   GNUNET_free (def);
646   return counter;
647 }
648
649
650 /**
651  * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
652  */
653 static void
654 parse_all_definitions ()
655 {
656   if (GNUNET_NO == gnunet_log_parsed)
657     parse_definitions ("GNUNET_LOG", 0);
658   gnunet_log_parsed = GNUNET_YES;
659   if (GNUNET_NO == gnunet_force_log_parsed)
660     gnunet_force_log_present =
661         parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
662   gnunet_force_log_parsed = GNUNET_YES;
663 }
664 #endif
665
666
667 /**
668  * Setup logging.
669  *
670  * @param comp default component to use
671  * @param loglevel what types of messages should be logged
672  * @param logfile which file to write log messages to (can be NULL)
673  * @return #GNUNET_OK on success
674  */
675 int
676 GNUNET_log_setup (const char *comp,
677                   const char *loglevel,
678                   const char *logfile)
679 {
680   const char *env_logfile;
681   const struct tm *tm;
682   time_t t;
683
684   min_level = get_type (loglevel);
685 #if !defined(GNUNET_CULL_LOGGING)
686   parse_all_definitions ();
687 #endif
688 #ifdef WINDOWS
689   QueryPerformanceFrequency (&performance_frequency);
690 #endif
691   GNUNET_free_non_null (component);
692   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
693   GNUNET_free_non_null (component_nopid);
694   component_nopid = GNUNET_strdup (comp);
695
696   env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
697   if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
698     logfile = env_logfile;
699   if (NULL == logfile)
700     return GNUNET_OK;
701   GNUNET_free_non_null (log_file_name);
702   log_file_name = GNUNET_STRINGS_filename_expand (logfile);
703   if (NULL == log_file_name)
704     return GNUNET_SYSERR;
705   t = time (NULL);
706   tm = gmtime (&t);
707   return setup_log_file (tm);
708 }
709
710
711 /**
712  * Add a custom logger. Note that installing any custom logger
713  * will disable the standard logger.  When multiple custom loggers
714  * are installed, all will be called.  The standard logger will
715  * only be used if no custom loggers are present.
716  *
717  * @param logger log function
718  * @param logger_cls closure for @a logger
719  */
720 void
721 GNUNET_logger_add (GNUNET_Logger logger,
722                    void *logger_cls)
723 {
724   struct CustomLogger *entry;
725
726   entry = GNUNET_new (struct CustomLogger);
727   entry->logger = logger;
728   entry->logger_cls = logger_cls;
729   entry->next = loggers;
730   loggers = entry;
731 }
732
733
734 /**
735  * Remove a custom logger.
736  *
737  * @param logger log function
738  * @param logger_cls closure for @a logger
739  */
740 void
741 GNUNET_logger_remove (GNUNET_Logger logger,
742                       void *logger_cls)
743 {
744   struct CustomLogger *pos;
745   struct CustomLogger *prev;
746
747   prev = NULL;
748   pos = loggers;
749   while ((NULL != pos) &&
750          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
751   {
752     prev = pos;
753     pos = pos->next;
754   }
755   GNUNET_assert (NULL != pos);
756   if (NULL == prev)
757     loggers = pos->next;
758   else
759     prev->next = pos->next;
760   GNUNET_free (pos);
761 }
762
763 #if WINDOWS
764 CRITICAL_SECTION output_message_cs;
765 #endif
766
767
768 /**
769  * Actually output the log message.
770  *
771  * @param kind how severe was the issue
772  * @param comp component responsible
773  * @param datestr current date/time
774  * @param msg the actual message
775  */
776 static void
777 output_message (enum GNUNET_ErrorType kind,
778                 const char *comp,
779                 const char *datestr,
780                 const char *msg)
781 {
782   struct CustomLogger *pos;
783
784 #if WINDOWS
785   EnterCriticalSection (&output_message_cs);
786 #endif
787   /* only use the standard logger if no custom loggers are present */
788   if ( (NULL != GNUNET_stderr) &&
789        (NULL == loggers) )
790   {
791     FPRINTF (GNUNET_stderr,
792              "%s %s %s %s",
793              datestr,
794              comp,
795              GNUNET_error_type_to_string (kind),
796              msg);
797     fflush (GNUNET_stderr);
798   }
799   pos = loggers;
800   while (pos != NULL)
801   {
802     pos->logger (pos->logger_cls, kind, comp, datestr, msg);
803     pos = pos->next;
804   }
805 #if WINDOWS
806   LeaveCriticalSection (&output_message_cs);
807 #endif
808 }
809
810
811 /**
812  * Flush an existing bulk report to the output.
813  *
814  * @param datestr our current timestamp
815  */
816 static void
817 flush_bulk (const char *datestr)
818 {
819   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
820   int rev;
821   char *last;
822   const char *ft;
823
824   if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat))
825     return;
826   rev = 0;
827   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
828   if (last == NULL)
829     last = &last_bulk[BULK_TRACK_SIZE - 1];
830   else if (last != last_bulk)
831     last--;
832   if (last[0] == '\n')
833   {
834     rev = 1;
835     last[0] = '\0';
836   }
837   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
838                                                (last_bulk_time), GNUNET_YES);
839   snprintf (msg, sizeof (msg),
840             _("Message `%.*s' repeated %u times in the last %s\n"),
841             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
842   if (rev == 1)
843     last[0] = '\n';
844   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
845   last_bulk_time = GNUNET_TIME_absolute_get ();
846   last_bulk_repeat = 0;
847 }
848
849
850 /**
851  * Ignore the next n calls to the log function.
852  *
853  * @param n number of log calls to ignore (could be negative)
854  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
855  */
856 void
857 GNUNET_log_skip (int n,
858                  int check_reset)
859 {
860   int ok;
861
862   if (0 == n)
863   {
864     ok = (0 == skip_log);
865     skip_log = 0;
866     if (check_reset)
867       GNUNET_break (ok);
868   }
869   else
870   {
871     skip_log += n;
872   }
873 }
874
875
876 /**
877  * Get the number of log calls that are going to be skipped
878  *
879  * @return number of log calls to be ignored
880  */
881 int
882 GNUNET_get_log_skip ()
883 {
884   return skip_log;
885 }
886
887
888 /**
889  * Output a log message using the default mechanism.
890  *
891  * @param kind how severe was the issue
892  * @param comp component responsible
893  * @param message the actual message
894  * @param va arguments to the format string "message"
895  */
896 static void
897 mylog (enum GNUNET_ErrorType kind,
898        const char *comp,
899        const char *message,
900        va_list va)
901 {
902   char date[DATE_STR_SIZE];
903   char date2[DATE_STR_SIZE];
904   struct tm *tmptr;
905   size_t size;
906   va_list vacp;
907
908   va_copy (vacp, va);
909   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
910   GNUNET_assert (0 != size);
911   va_end (vacp);
912   memset (date, 0, DATE_STR_SIZE);
913   {
914     char buf[size];
915     long long offset;
916 #ifdef WINDOWS
917     LARGE_INTEGER pc;
918     time_t timetmp;
919
920     offset = GNUNET_TIME_get_offset ();
921     time (&timetmp);
922     timetmp += offset / 1000;
923     tmptr = localtime (&timetmp);
924     pc.QuadPart = 0;
925     QueryPerformanceCounter (&pc);
926     if (NULL == tmptr)
927     {
928       strcpy (date, "localtime error");
929     }
930     else
931     {
932       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
933       snprintf (date, sizeof (date), date2,
934                 (long long) (pc.QuadPart /
935                              (performance_frequency.QuadPart / 1000)));
936     }
937 #else
938     struct timeval timeofday;
939
940     gettimeofday (&timeofday, NULL);
941     offset = GNUNET_TIME_get_offset ();
942     if (offset > 0)
943     {
944       timeofday.tv_sec += offset / 1000LL;
945       timeofday.tv_usec += (offset % 1000LL) * 1000LL;
946       if (timeofday.tv_usec > 1000000LL)
947       {
948         timeofday.tv_usec -= 1000000LL;
949         timeofday.tv_sec++;
950       }
951     }
952     else
953     {
954       timeofday.tv_sec += offset / 1000LL;
955       if (timeofday.tv_usec > - (offset % 1000LL) * 1000LL)
956       {
957         timeofday.tv_usec += (offset % 1000LL) * 1000LL;
958       }
959       else
960       {
961         timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
962         timeofday.tv_sec--;
963       }
964     }
965     tmptr = localtime (&timeofday.tv_sec);
966     if (NULL == tmptr)
967     {
968       strcpy (date, "localtime error");
969     }
970     else
971     {
972       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
973       snprintf (date, sizeof (date), date2, timeofday.tv_usec);
974     }
975 #endif
976     VSNPRINTF (buf, size, message, va);
977     if (NULL != tmptr)
978       (void) setup_log_file (tmptr);
979     if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
980         (0 != last_bulk_time.abs_value_us) &&
981         (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
982     {
983       last_bulk_repeat++;
984       if ( (GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
985             BULK_DELAY_THRESHOLD) ||
986            (last_bulk_repeat > BULK_REPEAT_THRESHOLD) )
987         flush_bulk (date);
988       return;
989     }
990     flush_bulk (date);
991     strncpy (last_bulk, buf, sizeof (last_bulk));
992     last_bulk_repeat = 0;
993     last_bulk_kind = kind;
994     last_bulk_time = GNUNET_TIME_absolute_get ();
995     strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
996     output_message (kind, comp, date, buf);
997   }
998 }
999
1000
1001 /**
1002  * Main log function.
1003  *
1004  * @param kind how serious is the error?
1005  * @param message what is the message (format string)
1006  * @param ... arguments for format string
1007  */
1008 void
1009 GNUNET_log_nocheck (enum GNUNET_ErrorType kind,
1010                     const char *message, ...)
1011 {
1012   va_list va;
1013
1014   va_start (va, message);
1015   mylog (kind, component, message, va);
1016   va_end (va);
1017 }
1018
1019
1020 /**
1021  * Log function that specifies an alternative component.
1022  * This function should be used by plugins.
1023  *
1024  * @param kind how serious is the error?
1025  * @param comp component responsible for generating the message
1026  * @param message what is the message (format string)
1027  * @param ... arguments for format string
1028  */
1029 void
1030 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
1031                          const char *message, ...)
1032 {
1033   va_list va;
1034   char comp_w_pid[128];
1035
1036   if (comp == NULL)
1037     comp = component_nopid;
1038
1039   va_start (va, message);
1040   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
1041   mylog (kind, comp_w_pid, message, va);
1042   va_end (va);
1043 }
1044
1045
1046 /**
1047  * Convert error type to string.
1048  *
1049  * @param kind type to convert
1050  * @return string corresponding to the type
1051  */
1052 const char *
1053 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1054 {
1055   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1056     return _("ERROR");
1057   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1058     return _("WARNING");
1059   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1060     return _("INFO");
1061   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1062     return _("DEBUG");
1063   if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1064     return _("NONE");
1065   return _("INVALID");
1066 }
1067
1068
1069 /**
1070  * Convert a hash to a string (for printing debug messages).
1071  * This is one of the very few calls in the entire API that is
1072  * NOT reentrant!
1073  *
1074  * @param hc the hash code
1075  * @return string form; will be overwritten by next call to GNUNET_h2s.
1076  */
1077 const char *
1078 GNUNET_h2s (const struct GNUNET_HashCode * hc)
1079 {
1080   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1081
1082   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1083   ret.encoding[8] = '\0';
1084   return (const char *) ret.encoding;
1085 }
1086
1087
1088 /**
1089  * Convert a hash to a string (for printing debug messages).
1090  * This is one of the very few calls in the entire API that is
1091  * NOT reentrant!
1092  *
1093  * @param hc the hash code
1094  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1095  */
1096 const char *
1097 GNUNET_h2s_full (const struct GNUNET_HashCode * hc)
1098 {
1099   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1100
1101   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1102   ret.encoding[sizeof (ret) - 1] = '\0';
1103   return (const char *) ret.encoding;
1104 }
1105
1106
1107 /**
1108  * Convert a peer identity to a string (for printing debug messages).
1109  * This is one of the very few calls in the entire API that is
1110  * NOT reentrant!
1111  *
1112  * @param pid the peer identity
1113  * @return string form of the pid; will be overwritten by next
1114  *         call to #GNUNET_i2s.
1115  */
1116 const char *
1117 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1118 {
1119   static char buf[256];
1120   char *ret;
1121
1122   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1123   strcpy (buf, ret);
1124   GNUNET_free (ret);
1125   buf[4] = '\0';
1126   return buf;
1127 }
1128
1129
1130 /**
1131  * Convert a peer identity to a string (for printing debug messages).
1132  * This is one of the very few calls in the entire API that is
1133  * NOT reentrant!
1134  *
1135  * @param pid the peer identity
1136  * @return string form of the pid; will be overwritten by next
1137  *         call to #GNUNET_i2s_full.
1138  */
1139 const char *
1140 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1141 {
1142   static char buf[256];
1143   char *ret;
1144
1145   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1146   strcpy (buf, ret);
1147   GNUNET_free (ret);
1148   return buf;
1149 }
1150
1151
1152 /**
1153  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1154  * (for printing debug messages).  This is one of the very few calls
1155  * in the entire API that is NOT reentrant!
1156  *
1157  * @param addr the address
1158  * @param addrlen the length of the address in @a addr
1159  * @return nicely formatted string for the address
1160  *  will be overwritten by next call to #GNUNET_a2s.
1161  */
1162 const char *
1163 GNUNET_a2s (const struct sockaddr *addr,
1164             socklen_t addrlen)
1165 {
1166 #ifndef WINDOWS
1167 #define LEN GNUNET_MAX ((INET6_ADDRSTRLEN + 8),         \
1168                         (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t)))
1169 #else
1170 #define LEN (INET6_ADDRSTRLEN + 8)
1171 #endif
1172   static char buf[LEN];
1173 #undef LEN
1174   static char b2[6];
1175   const struct sockaddr_in *v4;
1176   const struct sockaddr_un *un;
1177   const struct sockaddr_in6 *v6;
1178   unsigned int off;
1179
1180   if (addr == NULL)
1181     return _("unknown address");
1182   switch (addr->sa_family)
1183   {
1184   case AF_INET:
1185     if (addrlen != sizeof (struct sockaddr_in))
1186       return "<invalid v4 address>";
1187     v4 = (const struct sockaddr_in *) addr;
1188     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1189     if (0 == ntohs (v4->sin_port))
1190       return buf;
1191     strcat (buf, ":");
1192     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
1193     strcat (buf, b2);
1194     return buf;
1195   case AF_INET6:
1196     if (addrlen != sizeof (struct sockaddr_in6))
1197       return "<invalid v4 address>";
1198     v6 = (const struct sockaddr_in6 *) addr;
1199     buf[0] = '[';
1200     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1201     if (0 == ntohs (v6->sin6_port))
1202       return &buf[1];
1203     strcat (buf, "]:");
1204     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1205     strcat (buf, b2);
1206     return buf;
1207   case AF_UNIX:
1208     if (addrlen <= sizeof (sa_family_t))
1209       return "<unbound UNIX client>";
1210     un = (const struct sockaddr_un *) addr;
1211     off = 0;
1212     if ('\0' == un->sun_path[0])
1213       off++;
1214     memset (buf, 0, sizeof (buf));
1215     GNUNET_snprintf (buf,
1216                      sizeof (buf),
1217                      "%s%.*s",
1218                      (1 == off) ? "@" : "",
1219                      (int) (addrlen - sizeof (sa_family_t) - off),
1220                      &un->sun_path[off]);
1221     return buf;
1222   default:
1223     return _("invalid address");
1224   }
1225 }
1226
1227
1228 /**
1229  * Log error message about missing configuration option.
1230  *
1231  * @param kind log level
1232  * @param section section with missing option
1233  * @param option name of missing option
1234  */
1235 void
1236 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1237                            const char *section,
1238                            const char *option)
1239 {
1240   GNUNET_log (kind,
1241               _("Configuration fails to specify option `%s' in section `%s'!\n"),
1242               option,
1243               section);
1244 }
1245
1246
1247 /**
1248  * Log error message about invalid configuration option value.
1249  *
1250  * @param kind log level
1251  * @param section section with invalid option
1252  * @param option name of invalid option
1253  * @param required what is required that is invalid about the option
1254  */
1255 void
1256 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1257                            const char *section,
1258                            const char *option,
1259                            const char *required)
1260 {
1261   GNUNET_log (kind,
1262               _("Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1263               option, section, required);
1264 }
1265
1266
1267 /**
1268  * Initializer
1269  */
1270 void __attribute__ ((constructor))
1271 GNUNET_util_cl_init ()
1272 {
1273   GNUNET_stderr = stderr;
1274 #ifdef MINGW
1275   GNInitWinEnv (NULL);
1276 #endif
1277 #if WINDOWS
1278   if (!InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400))
1279     GNUNET_abort_ ();
1280 #endif
1281 }
1282
1283
1284 /**
1285  * Destructor
1286  */
1287 void __attribute__ ((destructor))
1288 GNUNET_util_cl_fini ()
1289 {
1290 #if WINDOWS
1291   DeleteCriticalSection (&output_message_cs);
1292 #endif
1293 #ifdef MINGW
1294   GNShutdownWinEnv ();
1295 #endif
1296 }
1297
1298 /* end of common_logging.c */