f5688f42c620495d8d237396139548a8d217c0c3
[oweals/gnunet.git] / src / util / common_logging.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2006-2013 Christian Grothoff (and other contributing authors)
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 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     logfile_copy[leftsquare - fn] = '\0';
346     logfile_copy[leftsquare - fn + 1] = '\0';
347     snprintf (fn, PATH_MAX, "%s%d%s",
348          logfile_copy, getpid (), &logfile_copy[leftsquare - fn + 2]);
349     GNUNET_free (logfile_copy);
350   }
351   if (0 == strcmp (fn, last_fn))
352     return GNUNET_OK; /* no change */
353   log_rotate (last_fn);
354   strcpy (last_fn, fn);
355 #if WINDOWS
356   altlog_fd = OPEN (fn, O_APPEND |
357                         O_BINARY |
358                         O_WRONLY | O_CREAT,
359                         _S_IREAD | _S_IWRITE);
360 #else
361   altlog_fd = OPEN (fn, O_APPEND |
362                         O_WRONLY | O_CREAT,
363                         S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
364 #endif
365   if (-1 != altlog_fd)
366   {
367     if (NULL != GNUNET_stderr)
368       fclose (GNUNET_stderr);
369     dup_return = dup2 (altlog_fd, 2);
370     (void) close (altlog_fd);
371     if (-1 != dup_return)
372     {
373       altlog = fdopen (2, "ab");
374       if (NULL == altlog)
375       {
376         (void) close (2);
377         altlog_fd = -1;
378       }
379     }
380     else
381     {
382       altlog_fd = -1;
383     }
384   }
385   if (-1 == altlog_fd)
386   {
387     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
388     return GNUNET_SYSERR;
389   }
390   GNUNET_stderr = altlog;
391   return GNUNET_OK;
392 }
393
394
395 /**
396  * Utility function - adds a parsed definition to logdefs array.
397  *
398  * @param component see struct LogDef, can't be NULL
399  * @param file see struct LogDef, can't be NULL
400  * @param function see struct LogDef, can't be NULL
401  * @param from_line see struct LogDef
402  * @param to_line see struct LogDef
403  * @param level see struct LogDef, must be >= 0
404  * @param force see struct LogDef
405  * @return 0 on success, regex-specific error otherwise
406  */
407 static int
408 add_definition (char *component, char *file, char *function, int from_line,
409                 int to_line, int level, int force)
410 {
411   struct LogDef n;
412   int r;
413
414   if (logdefs_size == logdefs_len)
415     resize_logdefs ();
416   memset (&n, 0, sizeof (n));
417   if (0 == strlen (component))
418     component = (char *) ".*";
419   r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
420   if (0 != r)
421   {
422     return r;
423   }
424   if (0 == strlen (file))
425     file = (char *) ".*";
426   r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
427   if (0 != r)
428   {
429     regfree (&n.component_regex);
430     return r;
431   }
432   if ((NULL == function) || (0 == strlen (function)))
433     function = (char *) ".*";
434   r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
435   if (0 != r)
436   {
437     regfree (&n.component_regex);
438     regfree (&n.file_regex);
439     return r;
440   }
441   n.from_line = from_line;
442   n.to_line = to_line;
443   n.level = level;
444   n.force = force;
445   logdefs[logdefs_len++] = n;
446   return 0;
447 }
448
449
450 /**
451  * Decides whether a particular logging call should or should not be allowed
452  * to be made. Used internally by GNUNET_log*()
453  *
454  * @param caller_level loglevel the caller wants to use
455  * @param comp component name the caller uses (NULL means that global
456  *   component name is used)
457  * @param file file name containing the logging call, usually __FILE__
458  * @param function function which tries to make a logging call,
459  *   usually __FUNCTION__
460  * @param line line at which the call is made, usually __LINE__
461  * @return 0 to disallow the call, 1 to allow it
462  */
463 int
464 GNUNET_get_log_call_status (int caller_level, const char *comp,
465                             const char *file, const char *function, int line)
466 {
467   struct LogDef *ld;
468   int i;
469   int force_only;
470
471   if (NULL == comp)
472     /* Use default component */
473     comp = component_nopid;
474
475   /* We have no definitions to override globally configured log level,
476    * so just use it right away.
477    */
478   if ( (min_level >= 0) && (GNUNET_NO == gnunet_force_log_present) )
479     return caller_level <= min_level;
480
481   /* Only look for forced definitions? */
482   force_only = min_level >= 0;
483   for (i = 0; i < logdefs_len; i++)
484   {
485     ld = &logdefs[i];
486     if (( (!force_only) || ld->force) &&
487         (line >= ld->from_line && line <= ld->to_line) &&
488         (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
489         (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
490         (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
491     {
492       /* We're finished */
493       return caller_level <= ld->level;
494     }
495   }
496   /* No matches - use global level, if defined */
497   if (min_level >= 0)
498     return caller_level <= min_level;
499   /* All programs/services previously defaulted to WARNING.
500    * Now WE default to WARNING, and THEY default to NULL.
501    */
502   return caller_level <= GNUNET_ERROR_TYPE_WARNING;
503 }
504
505
506 /**
507  * Utility function - parses a definition
508  *
509  * Definition format:
510  * component;file;function;from_line-to_line;level[/component...]
511  * All entries are mandatory, but may be empty.
512  * Empty entries for component, file and function are treated as
513  * "matches anything".
514  * Empty line entry is treated as "from 0 to INT_MAX"
515  * Line entry with only one line is treated as "this line only"
516  * Entry for level MUST NOT be empty.
517  * Entries for component, file and function that consist of a
518  * single character "*" are treated (at the moment) the same way
519  * empty entries are treated (wildcard matching is not implemented (yet?)).
520  * file entry is matched to the end of __FILE__. That is, it might be
521  * a base name, or a base name with leading directory names (some compilers
522  * define __FILE__ to absolute file path).
523  *
524  * @param constname name of the environment variable from which to get the
525  *   string to be parsed
526  * @param force 1 if definitions found in constname are to be forced
527  * @return number of added definitions
528  */
529 static int
530 parse_definitions (const char *constname, int force)
531 {
532   char *def;
533   const char *tmp;
534   char *comp = NULL;
535   char *file = NULL;
536   char *function = NULL;
537   char *p;
538   char *start;
539   char *t;
540   short state;
541   int level;
542   int from_line, to_line;
543   int counter = 0;
544   int keep_looking = 1;
545
546   tmp = getenv (constname);
547   if (NULL == tmp)
548     return 0;
549   def = GNUNET_strdup (tmp);
550   from_line = 0;
551   to_line = INT_MAX;
552   for (p = def, state = 0, start = def; keep_looking; p++)
553   {
554     switch (p[0])
555     {
556     case ';':                  /* found a field separator */
557       p[0] = '\0';
558       switch (state)
559       {
560       case 0:                  /* within a component name */
561         comp = start;
562         break;
563       case 1:                  /* within a file name */
564         file = start;
565         break;
566       case 2:                  /* within a function name */
567         /* after a file name there must be a function name */
568         function = start;
569         break;
570       case 3:                  /* within a from-to line range */
571         if (strlen (start) > 0)
572         {
573           errno = 0;
574           from_line = strtol (start, &t, 10);
575           if ( (0 != errno) || (from_line < 0) )
576           {
577             GNUNET_free (def);
578             return counter;
579           }
580           if ( (t < p) && ('-' == t[0]) )
581           {
582             errno = 0;
583             start = t + 1;
584             to_line = strtol (start, &t, 10);
585             if ( (0 != errno) || (to_line < 0) || (t != p) )
586             {
587               GNUNET_free (def);
588               return counter;
589             }
590           }
591           else                  /* one number means "match this line only" */
592             to_line = from_line;
593         }
594         else                    /* default to 0-max */
595         {
596           from_line = 0;
597           to_line = INT_MAX;
598         }
599         break;
600       }
601       start = p + 1;
602       state++;
603       break;
604     case '\0':                 /* found EOL */
605       keep_looking = 0;
606       /* fall through to '/' */
607     case '/':                  /* found a definition separator */
608       switch (state)
609       {
610       case 4:                  /* within a log level */
611         p[0] = '\0';
612         state = 0;
613         level = get_type ((const char *) start);
614         if ( (GNUNET_ERROR_TYPE_INVALID == level) ||
615              (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
616              (0 != add_definition (comp, file, function, from_line, to_line,
617                                    level, force)) )
618         {
619           GNUNET_free (def);
620           return counter;
621         }
622         counter++;
623         start = p + 1;
624         break;
625       default:
626         break;
627       }
628     default:
629       break;
630     }
631   }
632   GNUNET_free (def);
633   return counter;
634 }
635
636
637 /**
638  * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
639  */
640 static void
641 parse_all_definitions ()
642 {
643   if (GNUNET_NO == gnunet_log_parsed)
644     parse_definitions ("GNUNET_LOG", 0);
645   gnunet_log_parsed = GNUNET_YES;
646   if (GNUNET_NO == gnunet_force_log_parsed)
647     gnunet_force_log_present =
648         parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
649   gnunet_force_log_parsed = GNUNET_YES;
650 }
651 #endif
652
653
654 /**
655  * Setup logging.
656  *
657  * @param comp default component to use
658  * @param loglevel what types of messages should be logged
659  * @param logfile which file to write log messages to (can be NULL)
660  * @return #GNUNET_OK on success
661  */
662 int
663 GNUNET_log_setup (const char *comp,
664                   const char *loglevel,
665                   const char *logfile)
666 {
667   const char *env_logfile;
668   const struct tm *tm;
669   time_t t;
670
671   min_level = get_type (loglevel);
672 #if !defined(GNUNET_CULL_LOGGING)
673   parse_all_definitions ();
674 #endif
675 #ifdef WINDOWS
676   QueryPerformanceFrequency (&performance_frequency);
677 #endif
678   GNUNET_free_non_null (component);
679   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
680   GNUNET_free_non_null (component_nopid);
681   component_nopid = GNUNET_strdup (comp);
682
683   env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
684   if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
685     logfile = env_logfile;
686   if (NULL == logfile)
687     return GNUNET_OK;
688   GNUNET_free_non_null (log_file_name);
689   log_file_name = GNUNET_STRINGS_filename_expand (logfile);
690   if (NULL == log_file_name)
691     return GNUNET_SYSERR;
692   t = time (NULL);
693   tm = gmtime (&t);
694   return setup_log_file (tm);
695 }
696
697
698 /**
699  * Add a custom logger.
700  *
701  * @param logger log function
702  * @param logger_cls closure for @a logger
703  */
704 void
705 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
706 {
707   struct CustomLogger *entry;
708
709   entry = GNUNET_new (struct CustomLogger);
710   entry->logger = logger;
711   entry->logger_cls = logger_cls;
712   entry->next = loggers;
713   loggers = entry;
714 }
715
716
717 /**
718  * Remove a custom logger.
719  *
720  * @param logger log function
721  * @param logger_cls closure for @a logger
722  */
723 void
724 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
725 {
726   struct CustomLogger *pos;
727   struct CustomLogger *prev;
728
729   prev = NULL;
730   pos = loggers;
731   while ((NULL != pos) &&
732          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
733   {
734     prev = pos;
735     pos = pos->next;
736   }
737   GNUNET_assert (NULL != pos);
738   if (NULL == prev)
739     loggers = pos->next;
740   else
741     prev->next = pos->next;
742   GNUNET_free (pos);
743 }
744
745 #if WINDOWS
746 CRITICAL_SECTION output_message_cs;
747 #endif
748
749
750 /**
751  * Actually output the log message.
752  *
753  * @param kind how severe was the issue
754  * @param comp component responsible
755  * @param datestr current date/time
756  * @param msg the actual message
757  */
758 static void
759 output_message (enum GNUNET_ErrorType kind, const char *comp,
760                 const char *datestr, const char *msg)
761 {
762   struct CustomLogger *pos;
763 #if WINDOWS
764   EnterCriticalSection (&output_message_cs);
765 #endif
766   if (NULL != GNUNET_stderr)
767   {
768     FPRINTF (GNUNET_stderr, "%s %s %s %s", datestr, comp,
769              GNUNET_error_type_to_string (kind), msg);
770     fflush (GNUNET_stderr);
771   }
772   pos = loggers;
773   while (pos != NULL)
774   {
775     pos->logger (pos->logger_cls, kind, comp, datestr, msg);
776     pos = pos->next;
777   }
778 #if WINDOWS
779   LeaveCriticalSection (&output_message_cs);
780 #endif
781 }
782
783
784 /**
785  * Flush an existing bulk report to the output.
786  *
787  * @param datestr our current timestamp
788  */
789 static void
790 flush_bulk (const char *datestr)
791 {
792   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
793   int rev;
794   char *last;
795   const char *ft;
796
797   if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat))
798     return;
799   rev = 0;
800   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
801   if (last == NULL)
802     last = &last_bulk[BULK_TRACK_SIZE - 1];
803   else if (last != last_bulk)
804     last--;
805   if (last[0] == '\n')
806   {
807     rev = 1;
808     last[0] = '\0';
809   }
810   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
811                                                (last_bulk_time), GNUNET_YES);
812   snprintf (msg, sizeof (msg),
813             _("Message `%.*s' repeated %u times in the last %s\n"),
814             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
815   if (rev == 1)
816     last[0] = '\n';
817   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
818   last_bulk_time = GNUNET_TIME_absolute_get ();
819   last_bulk_repeat = 0;
820 }
821
822
823 /**
824  * Ignore the next n calls to the log function.
825  *
826  * @param n number of log calls to ignore (could be negative)
827  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
828  */
829 void
830 GNUNET_log_skip (int n,
831                  int check_reset)
832 {
833   int ok;
834
835   if (0 == n)
836   {
837     ok = (0 == skip_log);
838     skip_log = 0;
839     if (check_reset)
840       GNUNET_break (ok);
841   }
842   else
843   {
844     skip_log += n;
845   }
846 }
847
848
849 /**
850  * Get the number of log calls that are going to be skipped
851  *
852  * @return number of log calls to be ignored
853  */
854 int
855 GNUNET_get_log_skip ()
856 {
857   return skip_log;
858 }
859
860
861 /**
862  * Output a log message using the default mechanism.
863  *
864  * @param kind how severe was the issue
865  * @param comp component responsible
866  * @param message the actual message
867  * @param va arguments to the format string "message"
868  */
869 static void
870 mylog (enum GNUNET_ErrorType kind,
871        const char *comp,
872        const char *message,
873        va_list va)
874 {
875   char date[DATE_STR_SIZE];
876   char date2[DATE_STR_SIZE];
877   struct tm *tmptr;
878   size_t size;
879   va_list vacp;
880
881   va_copy (vacp, va);
882   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
883   GNUNET_assert (0 != size);
884   va_end (vacp);
885   memset (date, 0, DATE_STR_SIZE);
886   {
887     char buf[size];
888     long long offset;
889 #ifdef WINDOWS
890     LARGE_INTEGER pc;
891     time_t timetmp;
892
893     offset = GNUNET_TIME_get_offset ();
894     time (&timetmp);
895     timetmp += offset / 1000;
896     tmptr = localtime (&timetmp);
897     pc.QuadPart = 0;
898     QueryPerformanceCounter (&pc);
899     if (NULL == tmptr)
900     {
901       strcpy (date, "localtime error");
902     }
903     else
904     {
905       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
906       snprintf (date, sizeof (date), date2,
907                 (long long) (pc.QuadPart /
908                              (performance_frequency.QuadPart / 1000)));
909     }
910 #else
911     struct timeval timeofday;
912
913     gettimeofday (&timeofday, NULL);
914     offset = GNUNET_TIME_get_offset ();
915     if (offset > 0)
916     {
917       timeofday.tv_sec += offset / 1000LL;
918       timeofday.tv_usec += (offset % 1000LL) * 1000LL;
919       if (timeofday.tv_usec > 1000000LL)
920       {
921         timeofday.tv_usec -= 1000000LL;
922         timeofday.tv_sec++;
923       }
924     }
925     else
926     {
927       timeofday.tv_sec += offset / 1000LL;
928       if (timeofday.tv_usec > - (offset % 1000LL) * 1000LL)
929       {
930         timeofday.tv_usec += (offset % 1000LL) * 1000LL;
931       }
932       else
933       {
934         timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
935         timeofday.tv_sec--;
936       }
937     }
938     tmptr = localtime (&timeofday.tv_sec);
939     if (NULL == tmptr)
940     {
941       strcpy (date, "localtime error");
942     }
943     else
944     {
945       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
946       snprintf (date, sizeof (date), date2, timeofday.tv_usec);
947     }
948 #endif
949     VSNPRINTF (buf, size, message, va);
950     if (NULL != tmptr)
951       (void) setup_log_file (tmptr);
952     if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
953         (0 != last_bulk_time.abs_value_us) &&
954         (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
955     {
956       last_bulk_repeat++;
957       if ( (GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
958             BULK_DELAY_THRESHOLD) ||
959            (last_bulk_repeat > BULK_REPEAT_THRESHOLD) )
960         flush_bulk (date);
961       return;
962     }
963     flush_bulk (date);
964     strncpy (last_bulk, buf, sizeof (last_bulk));
965     last_bulk_repeat = 0;
966     last_bulk_kind = kind;
967     last_bulk_time = GNUNET_TIME_absolute_get ();
968     strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
969     output_message (kind, comp, date, buf);
970   }
971 }
972
973
974 /**
975  * Main log function.
976  *
977  * @param kind how serious is the error?
978  * @param message what is the message (format string)
979  * @param ... arguments for format string
980  */
981 void
982 GNUNET_log_nocheck (enum GNUNET_ErrorType kind,
983                     const char *message, ...)
984 {
985   va_list va;
986
987   va_start (va, message);
988   mylog (kind, component, message, va);
989   va_end (va);
990 }
991
992
993 /**
994  * Log function that specifies an alternative component.
995  * This function should be used by plugins.
996  *
997  * @param kind how serious is the error?
998  * @param comp component responsible for generating the message
999  * @param message what is the message (format string)
1000  * @param ... arguments for format string
1001  */
1002 void
1003 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
1004                          const char *message, ...)
1005 {
1006   va_list va;
1007   char comp_w_pid[128];
1008
1009   if (comp == NULL)
1010     comp = component_nopid;
1011
1012   va_start (va, message);
1013   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
1014   mylog (kind, comp_w_pid, message, va);
1015   va_end (va);
1016 }
1017
1018
1019 /**
1020  * Convert error type to string.
1021  *
1022  * @param kind type to convert
1023  * @return string corresponding to the type
1024  */
1025 const char *
1026 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1027 {
1028   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1029     return _("ERROR");
1030   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1031     return _("WARNING");
1032   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1033     return _("INFO");
1034   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1035     return _("DEBUG");
1036   if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1037     return _("NONE");
1038   return _("INVALID");
1039 }
1040
1041
1042 /**
1043  * Convert a hash to a string (for printing debug messages).
1044  * This is one of the very few calls in the entire API that is
1045  * NOT reentrant!
1046  *
1047  * @param hc the hash code
1048  * @return string form; will be overwritten by next call to GNUNET_h2s.
1049  */
1050 const char *
1051 GNUNET_h2s (const struct GNUNET_HashCode * hc)
1052 {
1053   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1054
1055   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1056   ret.encoding[8] = '\0';
1057   return (const char *) ret.encoding;
1058 }
1059
1060
1061 /**
1062  * Convert a hash to a string (for printing debug messages).
1063  * This is one of the very few calls in the entire API that is
1064  * NOT reentrant!
1065  *
1066  * @param hc the hash code
1067  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1068  */
1069 const char *
1070 GNUNET_h2s_full (const struct GNUNET_HashCode * hc)
1071 {
1072   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1073
1074   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1075   ret.encoding[sizeof (ret) - 1] = '\0';
1076   return (const char *) ret.encoding;
1077 }
1078
1079
1080 /**
1081  * Convert a peer identity to a string (for printing debug messages).
1082  * This is one of the very few calls in the entire API that is
1083  * NOT reentrant!
1084  *
1085  * @param pid the peer identity
1086  * @return string form of the pid; will be overwritten by next
1087  *         call to #GNUNET_i2s.
1088  */
1089 const char *
1090 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1091 {
1092   static char buf[256];
1093   char *ret;
1094
1095   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1096   strcpy (buf, ret);
1097   GNUNET_free (ret);
1098   buf[4] = '\0';
1099   return buf;
1100 }
1101
1102
1103 /**
1104  * Convert a peer identity to a string (for printing debug messages).
1105  * This is one of the very few calls in the entire API that is
1106  * NOT reentrant!
1107  *
1108  * @param pid the peer identity
1109  * @return string form of the pid; will be overwritten by next
1110  *         call to #GNUNET_i2s_full.
1111  */
1112 const char *
1113 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1114 {
1115   static char buf[256];
1116   char *ret;
1117
1118   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1119   strcpy (buf, ret);
1120   GNUNET_free (ret);
1121   return buf;
1122 }
1123
1124
1125 /**
1126  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1127  * (for printing debug messages).  This is one of the very few calls
1128  * in the entire API that is NOT reentrant!
1129  *
1130  * @param addr the address
1131  * @param addrlen the length of the address in @a addr
1132  * @return nicely formatted string for the address
1133  *  will be overwritten by next call to #GNUNET_a2s.
1134  */
1135 const char *
1136 GNUNET_a2s (const struct sockaddr *addr,
1137             socklen_t addrlen)
1138 {
1139 #ifndef WINDOWS
1140 #define LEN GNUNET_MAX ((INET6_ADDRSTRLEN + 8),         \
1141                         (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t)))
1142 #else
1143 #define LEN (INET6_ADDRSTRLEN + 8)
1144 #endif
1145   static char buf[LEN];
1146 #undef LEN
1147   static char b2[6];
1148   const struct sockaddr_in *v4;
1149   const struct sockaddr_un *un;
1150   const struct sockaddr_in6 *v6;
1151   unsigned int off;
1152
1153   if (addr == NULL)
1154     return _("unknown address");
1155   switch (addr->sa_family)
1156   {
1157   case AF_INET:
1158     if (addrlen != sizeof (struct sockaddr_in))
1159       return "<invalid v4 address>";
1160     v4 = (const struct sockaddr_in *) addr;
1161     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1162     if (0 == ntohs (v4->sin_port))
1163       return buf;
1164     strcat (buf, ":");
1165     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
1166     strcat (buf, b2);
1167     return buf;
1168   case AF_INET6:
1169     if (addrlen != sizeof (struct sockaddr_in6))
1170       return "<invalid v4 address>";
1171     v6 = (const struct sockaddr_in6 *) addr;
1172     buf[0] = '[';
1173     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1174     if (0 == ntohs (v6->sin6_port))
1175       return &buf[1];
1176     strcat (buf, "]:");
1177     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1178     strcat (buf, b2);
1179     return buf;
1180   case AF_UNIX:
1181     if (addrlen <= sizeof (sa_family_t))
1182       return "<unbound UNIX client>";
1183     un = (const struct sockaddr_un *) addr;
1184     off = 0;
1185     if ('\0' == un->sun_path[0])
1186       off++;
1187     memset (buf, 0, sizeof (buf));
1188     GNUNET_snprintf (buf,
1189                      sizeof (buf),
1190                      "%s%.*s",
1191                      (1 == off) ? "@" : "",
1192                      (int) (addrlen - sizeof (sa_family_t) - off),
1193                      &un->sun_path[off]);
1194     return buf;
1195   default:
1196     return _("invalid address");
1197   }
1198 }
1199
1200
1201 /**
1202  * Log error message about missing configuration option.
1203  *
1204  * @param kind log level
1205  * @param section section with missing option
1206  * @param option name of missing option
1207  */
1208 void
1209 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1210                            const char *section,
1211                            const char *option)
1212 {
1213   GNUNET_log (kind,
1214               _("Configuration fails to specify option `%s' in section `%s'!\n"),
1215               option,
1216               section);
1217 }
1218
1219
1220 /**
1221  * Log error message about invalid configuration option value.
1222  *
1223  * @param kind log level
1224  * @param section section with invalid option
1225  * @param option name of invalid option
1226  * @param required what is required that is invalid about the option
1227  */
1228 void
1229 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1230                            const char *section,
1231                            const char *option,
1232                            const char *required)
1233 {
1234   GNUNET_log (kind,
1235               _("Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1236               option, section, required);
1237 }
1238
1239
1240 /**
1241  * Initializer
1242  */
1243 void __attribute__ ((constructor))
1244 GNUNET_util_cl_init ()
1245 {
1246   GNUNET_stderr = stderr;
1247 #ifdef MINGW
1248   GNInitWinEnv (NULL);
1249 #endif
1250 #if WINDOWS
1251   if (!InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400))
1252     GNUNET_abort_ ();
1253 #endif
1254 }
1255
1256
1257 /**
1258  * Destructor
1259  */
1260 void __attribute__ ((destructor))
1261 GNUNET_util_cl_fini ()
1262 {
1263 #if WINDOWS
1264   DeleteCriticalSection (&output_message_cs);
1265 #endif
1266 #ifdef MINGW
1267   GNShutdownWinEnv ();
1268 #endif
1269 }
1270
1271 /* end of common_logging.c */