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