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