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