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