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