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