introduce allocation wrappers to improve libgcrypt performance
[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 it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file util/common_logging.c
21  * @brief error handling API
22  * @author Christian Grothoff
23  */
24 #include "platform.h"
25 #include "gnunet_crypto_lib.h"
26 #include "gnunet_disk_lib.h"
27 #include "gnunet_strings_lib.h"
28 #include <regex.h>
29
30
31 /**
32  * After how many milliseconds do we always print
33  * that "message X was repeated N times"?  Use 12h.
34  */
35 #define BULK_DELAY_THRESHOLD (12 * 60 * 60 * 1000LL * 1000LL)
36
37 /**
38  * After how many repetitions do we always print
39  * that "message X was repeated N times"? (even if
40  * we have not yet reached the delay threshold)
41  */
42 #define BULK_REPEAT_THRESHOLD 1000
43
44 /**
45  * How many characters do we use for matching of
46  * bulk messages?
47  */
48 #define BULK_TRACK_SIZE 256
49
50 /**
51  * How many characters do we use for matching of
52  * bulk components?
53  */
54 #define COMP_TRACK_SIZE 32
55
56 /**
57  * How many characters can a date/time string
58  * be at most?
59  */
60 #define DATE_STR_SIZE 64
61
62 /**
63  * How many log files to keep?
64  */
65 #define ROTATION_KEEP 3
66
67 #ifndef PATH_MAX
68 /**
69  * Assumed maximum path length (for the log file name).
70  */
71 #define PATH_MAX 4096
72 #endif
73
74
75 /**
76  * Linked list of active loggers.
77  */
78 struct CustomLogger
79 {
80   /**
81    * This is a linked list.
82    */
83   struct CustomLogger *next;
84
85   /**
86    * Log function.
87    */
88   GNUNET_Logger logger;
89
90   /**
91    * Closure for logger.
92    */
93   void *logger_cls;
94 };
95
96 /**
97  * The last "bulk" error message that we have been logging.
98  * Note that this message maybe truncated to the first BULK_TRACK_SIZE
99  * characters, in which case it is NOT 0-terminated!
100  */
101 static char last_bulk[BULK_TRACK_SIZE];
102
103 /**
104  * Type of the last bulk message.
105  */
106 static enum GNUNET_ErrorType last_bulk_kind;
107
108 /**
109  * Time of the last bulk error message (0 for none)
110  */
111 static struct GNUNET_TIME_Absolute last_bulk_time;
112
113 /**
114  * Number of times that bulk message has been repeated since.
115  */
116 static unsigned int last_bulk_repeat;
117
118 /**
119  * Component when the last bulk was logged.  Will be 0-terminated.
120  */
121 static char last_bulk_comp[COMP_TRACK_SIZE + 1];
122
123 /**
124  * Running component.
125  */
126 static char *component;
127
128 /**
129  * Running component (without pid).
130  */
131 static char *component_nopid;
132
133 /**
134  * Format string describing the name of the log file.
135  */
136 static char *log_file_name;
137
138 /**
139  * Minimum log level.
140  */
141 static enum GNUNET_ErrorType min_level;
142
143 /**
144  * Linked list of our custom loggres.
145  */
146 static struct CustomLogger *loggers;
147
148 /**
149  * Number of log calls to ignore.
150  */
151 static int skip_log = 0;
152
153 /**
154  * File descriptor to use for "stderr", or NULL for none.
155  */
156 static FILE *GNUNET_stderr;
157
158 /**
159  * Represents a single logging definition
160  */
161 struct LogDef
162 {
163   /**
164    * Component name regex
165    */
166   regex_t component_regex;
167
168   /**
169    * File name regex
170    */
171   regex_t file_regex;
172
173   /**
174    * Function name regex
175    */
176   regex_t function_regex;
177
178   /**
179    * Lowest line at which this definition matches.
180    * Defaults to 0. Must be <= to_line.
181    */
182   int from_line;
183
184   /**
185    * Highest line at which this definition matches.
186    * Defaults to INT_MAX. Must be >= from_line.
187    */
188   int to_line;
189
190   /**
191    * Maximal log level allowed for calls that match this definition.
192    * Calls with higher log level will be disabled.
193    * Must be >= 0
194    */
195   int level;
196
197   /**
198    * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
199    * overrides any configuration options. 0 otherwise.
200    */
201   int force;
202 };
203
204
205 #if !defined(GNUNET_CULL_LOGGING)
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 #endif
236
237 #ifdef WINDOWS
238 /**
239  * Contains the number of performance counts per second.
240  */
241 static LARGE_INTEGER performance_frequency;
242 #endif
243
244
245 /**
246  * Convert a textual description of a loglevel
247  * to the respective GNUNET_GE_KIND.
248  *
249  * @param log loglevel to parse
250  * @return GNUNET_GE_INVALID if log does not parse
251  */
252 static enum GNUNET_ErrorType
253 get_type (const char *log)
254 {
255   if (NULL == log)
256     return GNUNET_ERROR_TYPE_UNSPECIFIED;
257   if (0 == strcasecmp (log, _("DEBUG")))
258     return GNUNET_ERROR_TYPE_DEBUG;
259   if (0 == strcasecmp (log, _("INFO")))
260     return GNUNET_ERROR_TYPE_INFO;
261   if (0 == strcasecmp (log, _("MESSAGE")))
262     return GNUNET_ERROR_TYPE_MESSAGE;
263   if (0 == strcasecmp (log, _("WARNING")))
264     return GNUNET_ERROR_TYPE_WARNING;
265   if (0 == strcasecmp (log, _("ERROR")))
266     return GNUNET_ERROR_TYPE_ERROR;
267   if (0 == strcasecmp (log, _("NONE")))
268     return GNUNET_ERROR_TYPE_NONE;
269   return GNUNET_ERROR_TYPE_INVALID;
270 }
271
272
273 /**
274  * Abort the process, generate a core dump if possible.
275  */
276 void
277 GNUNET_abort_ ()
278 {
279 #if WINDOWS
280   DebugBreak ();
281 #endif
282   abort ();
283 }
284
285
286 #if !defined(GNUNET_CULL_LOGGING)
287 /**
288  * Utility function - reallocates logdefs array to be twice as large.
289  */
290 static void
291 resize_logdefs ()
292 {
293   logdefs_size = (logdefs_size + 1) * 2;
294   logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
295 }
296
297
298 #if ! TALER_WALLET_ONLY
299 /**
300  * Rotate logs, deleting the oldest log.
301  *
302  * @param new_name new name to add to the rotation
303  */
304 static void
305 log_rotate (const char *new_name)
306 {
307   static char *rotation[ROTATION_KEEP];
308   static unsigned int rotation_off;
309   char *discard;
310
311   if ('\0' == *new_name)
312     return; /* not a real log file name */
313   discard = rotation[rotation_off % ROTATION_KEEP];
314   if (NULL != discard)
315   {
316     /* Note: can't log errors during logging (recursion!), so this
317        operation MUST silently fail... */
318     (void) UNLINK (discard);
319     GNUNET_free (discard);
320   }
321   rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup (new_name);
322   rotation_off++;
323 }
324
325
326 /**
327  * Setup the log file.
328  *
329  * @param tm timestamp for which we should setup logging
330  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
331  */
332 static int
333 setup_log_file (const struct tm *tm)
334 {
335   static char last_fn[PATH_MAX + 1];
336   char fn[PATH_MAX + 1];
337   int altlog_fd;
338   int dup_return;
339   FILE *altlog;
340   char *leftsquare;
341
342   if (NULL == log_file_name)
343     return GNUNET_SYSERR;
344   if (0 == strftime (fn, sizeof (fn), log_file_name, tm))
345     return GNUNET_SYSERR;
346   leftsquare = strrchr (fn, '[');
347   if ( (NULL != leftsquare) && (']' == leftsquare[1]) )
348   {
349     char *logfile_copy = GNUNET_strdup (fn);
350
351     logfile_copy[leftsquare - fn] = '\0';
352     logfile_copy[leftsquare - fn + 1] = '\0';
353     snprintf (fn,
354               PATH_MAX,
355               "%s%d%s",
356               logfile_copy,
357               getpid (),
358               &logfile_copy[leftsquare - fn + 2]);
359     GNUNET_free (logfile_copy);
360   }
361   if (0 == strcmp (fn, last_fn))
362     return GNUNET_OK; /* no change */
363   log_rotate (last_fn);
364   strcpy (last_fn, fn);
365   if (GNUNET_SYSERR ==
366       GNUNET_DISK_directory_create_for_file (fn))
367   {
368     fprintf (stderr,
369              "Failed to create directory for `%s': %s\n",
370              fn,
371              STRERROR (errno));
372     return GNUNET_SYSERR;
373   }
374 #if WINDOWS
375   altlog_fd = OPEN (fn, O_APPEND |
376                         O_BINARY |
377                         O_WRONLY | O_CREAT,
378                         _S_IREAD | _S_IWRITE);
379 #else
380   altlog_fd = OPEN (fn, O_APPEND |
381                         O_WRONLY | O_CREAT,
382                         S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
383 #endif
384   if (-1 != altlog_fd)
385   {
386     if (NULL != GNUNET_stderr)
387       fclose (GNUNET_stderr);
388     dup_return = dup2 (altlog_fd, 2);
389     (void) close (altlog_fd);
390     if (-1 != dup_return)
391     {
392       altlog = fdopen (2, "ab");
393       if (NULL == altlog)
394       {
395         (void) close (2);
396         altlog_fd = -1;
397       }
398     }
399     else
400     {
401       altlog_fd = -1;
402     }
403   }
404   if (-1 == altlog_fd)
405   {
406     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
407     return GNUNET_SYSERR;
408   }
409   GNUNET_stderr = altlog;
410   return GNUNET_OK;
411 }
412 #endif
413
414
415 /**
416  * Utility function - adds a parsed definition to logdefs array.
417  *
418  * @param component see struct LogDef, can't be NULL
419  * @param file see struct LogDef, can't be NULL
420  * @param function see struct LogDef, can't be NULL
421  * @param from_line see struct LogDef
422  * @param to_line see struct LogDef
423  * @param level see struct LogDef, must be >= 0
424  * @param force see struct LogDef
425  * @return 0 on success, regex-specific error otherwise
426  */
427 static int
428 add_definition (const char *component,
429                 const char *file,
430                 const char *function,
431                 int from_line,
432                 int to_line,
433                 int level,
434                 int force)
435 {
436   struct LogDef n;
437   int r;
438
439   if (logdefs_size == logdefs_len)
440     resize_logdefs ();
441   memset (&n, 0, sizeof (n));
442   if (0 == strlen (component))
443     component = (char *) ".*";
444   r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
445   if (0 != r)
446   {
447     return r;
448   }
449   if (0 == strlen (file))
450     file = (char *) ".*";
451   r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
452   if (0 != r)
453   {
454     regfree (&n.component_regex);
455     return r;
456   }
457   if ((NULL == function) || (0 == strlen (function)))
458     function = (char *) ".*";
459   r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
460   if (0 != r)
461   {
462     regfree (&n.component_regex);
463     regfree (&n.file_regex);
464     return r;
465   }
466   n.from_line = from_line;
467   n.to_line = to_line;
468   n.level = level;
469   n.force = force;
470   logdefs[logdefs_len++] = n;
471   return 0;
472 }
473
474
475 /**
476  * Decides whether a particular logging call should or should not be allowed
477  * to be made. Used internally by GNUNET_log*()
478  *
479  * @param caller_level loglevel the caller wants to use
480  * @param comp component name the caller uses (NULL means that global
481  *   component name is used)
482  * @param file file name containing the logging call, usually __FILE__
483  * @param function function which tries to make a logging call,
484  *   usually __FUNCTION__
485  * @param line line at which the call is made, usually __LINE__
486  * @return 0 to disallow the call, 1 to allow it
487  */
488 int
489 GNUNET_get_log_call_status (int caller_level,
490                             const char *comp,
491                             const char *file,
492                             const char *function,
493                             int line)
494 {
495   struct LogDef *ld;
496   int i;
497   int force_only;
498
499   if (NULL == comp)
500     /* Use default component */
501     comp = component_nopid;
502
503   /* We have no definitions to override globally configured log level,
504    * so just use it right away.
505    */
506   if ( (min_level >= 0) && (GNUNET_NO == gnunet_force_log_present) )
507     return caller_level <= min_level;
508
509   /* Only look for forced definitions? */
510   force_only = min_level >= 0;
511   for (i = 0; i < logdefs_len; i++)
512   {
513     ld = &logdefs[i];
514     if (( (!force_only) || ld->force) &&
515         (line >= ld->from_line && line <= ld->to_line) &&
516         (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
517         (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
518         (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
519     {
520       /* We're finished */
521       return caller_level <= ld->level;
522     }
523   }
524   /* No matches - use global level, if defined */
525   if (min_level >= 0)
526     return caller_level <= min_level;
527   /* All programs/services previously defaulted to WARNING.
528    * Now *we* default to WARNING, and THEY default to NULL.
529    * Or rather we default to MESSAGE, since things aren't always bad.
530    */
531   return caller_level <= GNUNET_ERROR_TYPE_MESSAGE;
532 }
533
534
535 /**
536  * Utility function - parses a definition
537  *
538  * Definition format:
539  * component;file;function;from_line-to_line;level[/component...]
540  * All entries are mandatory, but may be empty.
541  * Empty entries for component, file and function are treated as
542  * "matches anything".
543  * Empty line entry is treated as "from 0 to INT_MAX"
544  * Line entry with only one line is treated as "this line only"
545  * Entry for level MUST NOT be empty.
546  * Entries for component, file and function that consist of a
547  * single character "*" are treated (at the moment) the same way
548  * empty entries are treated (wildcard matching is not implemented (yet?)).
549  * file entry is matched to the end of __FILE__. That is, it might be
550  * a base name, or a base name with leading directory names (some compilers
551  * define __FILE__ to absolute file path).
552  *
553  * @param constname name of the environment variable from which to get the
554  *   string to be parsed
555  * @param force 1 if definitions found in constname are to be forced
556  * @return number of added definitions
557  */
558 static int
559 parse_definitions (const char *constname, int force)
560 {
561   char *def;
562   const char *tmp;
563   char *comp = NULL;
564   char *file = NULL;
565   char *function = NULL;
566   char *p;
567   char *start;
568   char *t;
569   short state;
570   int level;
571   int from_line, to_line;
572   int counter = 0;
573   int keep_looking = 1;
574
575   tmp = getenv (constname);
576   if (NULL == tmp)
577     return 0;
578   def = GNUNET_strdup (tmp);
579   from_line = 0;
580   to_line = INT_MAX;
581   for (p = def, state = 0, start = def; keep_looking; p++)
582   {
583     switch (p[0])
584     {
585     case ';':                  /* found a field separator */
586       p[0] = '\0';
587       switch (state)
588       {
589       case 0:                  /* within a component name */
590         comp = start;
591         break;
592       case 1:                  /* within a file name */
593         file = start;
594         break;
595       case 2:                  /* within a function name */
596         /* after a file name there must be a function name */
597         function = start;
598         break;
599       case 3:                  /* within a from-to line range */
600         if (strlen (start) > 0)
601         {
602           errno = 0;
603           from_line = strtol (start, &t, 10);
604           if ( (0 != errno) || (from_line < 0) )
605           {
606             GNUNET_free (def);
607             return counter;
608           }
609           if ( (t < p) && ('-' == t[0]) )
610           {
611             errno = 0;
612             start = t + 1;
613             to_line = strtol (start, &t, 10);
614             if ( (0 != errno) || (to_line < 0) || (t != p) )
615             {
616               GNUNET_free (def);
617               return counter;
618             }
619           }
620           else                  /* one number means "match this line only" */
621             to_line = from_line;
622         }
623         else                    /* default to 0-max */
624         {
625           from_line = 0;
626           to_line = INT_MAX;
627         }
628         break;
629       default:
630         fprintf(stderr, "ERROR: Unable to parse log defintion: Syntax error.\n");
631         break;
632       }
633       start = p + 1;
634       state++;
635       break;
636     case '\0':                 /* found EOL */
637       keep_looking = 0;
638       /* fall through to '/' */
639     case '/':                  /* found a definition separator */
640       switch (state)
641       {
642       case 4:                  /* within a log level */
643         p[0] = '\0';
644         state = 0;
645         level = get_type ((const char *) start);
646         if ( (GNUNET_ERROR_TYPE_INVALID == level) ||
647              (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
648              (0 != add_definition (comp, file, function, from_line, to_line,
649                                    level, force)) )
650         {
651           GNUNET_free (def);
652           return counter;
653         }
654         counter++;
655         start = p + 1;
656         break;
657       default:
658         fprintf(stderr, "ERROR: Unable to parse log defintion: Syntax error.\n");
659         break;
660       }
661     default:
662       break;
663     }
664   }
665   GNUNET_free (def);
666   return counter;
667 }
668
669
670 /**
671  * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
672  */
673 static void
674 parse_all_definitions ()
675 {
676   if (GNUNET_NO == gnunet_log_parsed)
677     parse_definitions ("GNUNET_LOG", 0);
678   gnunet_log_parsed = GNUNET_YES;
679   if (GNUNET_NO == gnunet_force_log_parsed)
680     gnunet_force_log_present =
681         parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
682   gnunet_force_log_parsed = GNUNET_YES;
683 }
684 #endif
685
686
687 /**
688  * Setup logging.
689  *
690  * @param comp default component to use
691  * @param loglevel what types of messages should be logged
692  * @param logfile which file to write log messages to (can be NULL)
693  * @return #GNUNET_OK on success
694  */
695 int
696 GNUNET_log_setup (const char *comp,
697                   const char *loglevel,
698                   const char *logfile)
699 {
700   const char *env_logfile;
701
702   min_level = get_type (loglevel);
703 #if !defined(GNUNET_CULL_LOGGING)
704   parse_all_definitions ();
705 #endif
706 #ifdef WINDOWS
707   QueryPerformanceFrequency (&performance_frequency);
708 #endif
709   GNUNET_free_non_null (component);
710   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
711   GNUNET_free_non_null (component_nopid);
712   component_nopid = GNUNET_strdup (comp);
713
714   env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
715   if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
716     logfile = env_logfile;
717   if (NULL == logfile)
718     return GNUNET_OK;
719   GNUNET_free_non_null (log_file_name);
720   log_file_name = GNUNET_STRINGS_filename_expand (logfile);
721   if (NULL == log_file_name)
722     return GNUNET_SYSERR;
723 #if TALER_WALLET_ONLY || defined(GNUNET_CULL_LOGGING)
724   /* log file option not allowed for wallet logic */
725   GNUNET_assert (NULL == logfile);
726   return GNUNET_OK;
727 #else
728   {
729     time_t t;
730     const struct tm *tm;
731
732     t = time (NULL);
733     tm = gmtime (&t);
734     return setup_log_file (tm);
735   }
736 #endif
737 }
738
739
740 /**
741  * Add a custom logger. Note that installing any custom logger
742  * will disable the standard logger.  When multiple custom loggers
743  * are installed, all will be called.  The standard logger will
744  * only be used if no custom loggers are present.
745  *
746  * @param logger log function
747  * @param logger_cls closure for @a logger
748  */
749 void
750 GNUNET_logger_add (GNUNET_Logger logger,
751                    void *logger_cls)
752 {
753   struct CustomLogger *entry;
754
755   entry = GNUNET_new (struct CustomLogger);
756   entry->logger = logger;
757   entry->logger_cls = logger_cls;
758   entry->next = loggers;
759   loggers = entry;
760 }
761
762
763 /**
764  * Remove a custom logger.
765  *
766  * @param logger log function
767  * @param logger_cls closure for @a logger
768  */
769 void
770 GNUNET_logger_remove (GNUNET_Logger logger,
771                       void *logger_cls)
772 {
773   struct CustomLogger *pos;
774   struct CustomLogger *prev;
775
776   prev = NULL;
777   pos = loggers;
778   while ((NULL != pos) &&
779          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
780   {
781     prev = pos;
782     pos = pos->next;
783   }
784   GNUNET_assert (NULL != pos);
785   if (NULL == prev)
786     loggers = pos->next;
787   else
788     prev->next = pos->next;
789   GNUNET_free (pos);
790 }
791
792 #if WINDOWS
793 CRITICAL_SECTION output_message_cs;
794 #endif
795
796
797 /**
798  * Actually output the log message.
799  *
800  * @param kind how severe was the issue
801  * @param comp component responsible
802  * @param datestr current date/time
803  * @param msg the actual message
804  */
805 static void
806 output_message (enum GNUNET_ErrorType kind,
807                 const char *comp,
808                 const char *datestr,
809                 const char *msg)
810 {
811   struct CustomLogger *pos;
812
813 #if WINDOWS
814   EnterCriticalSection (&output_message_cs);
815 #endif
816   /* only use the standard logger if no custom loggers are present */
817   if ( (NULL != GNUNET_stderr) &&
818        (NULL == loggers) )
819   {
820     if (kind == GNUNET_ERROR_TYPE_MESSAGE)
821     {
822       /* The idea here is to produce "normal" output messages
823        * for end users while still having the power of the
824        * logging engine for developer needs. So ideally this
825        * is what it should look like when CLI tools are used
826        * interactively, yet the same message shouldn't look
827        * this way if the output is going to logfiles or robots
828        * instead.
829        */
830       FPRINTF (GNUNET_stderr,
831                "* %s",
832                msg);
833     }
834     else
835     {
836       FPRINTF (GNUNET_stderr,
837                "%s %s %s %s",
838                datestr,
839                comp,
840                GNUNET_error_type_to_string (kind),
841                msg);
842     }
843     fflush (GNUNET_stderr);
844   }
845   pos = loggers;
846   while (NULL != pos)
847   {
848     pos->logger (pos->logger_cls,
849                  kind,
850                  comp,
851                  datestr,
852                  msg);
853     pos = pos->next;
854   }
855 #if WINDOWS
856   LeaveCriticalSection (&output_message_cs);
857 #endif
858 }
859
860
861 /**
862  * Flush an existing bulk report to the output.
863  *
864  * @param datestr our current timestamp
865  */
866 static void
867 flush_bulk (const char *datestr)
868 {
869   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
870   int rev;
871   char *last;
872   const char *ft;
873
874   if ( (0 == last_bulk_time.abs_value_us) ||
875        (0 == last_bulk_repeat) )
876     return;
877   rev = 0;
878   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
879   if (last == NULL)
880     last = &last_bulk[BULK_TRACK_SIZE - 1];
881   else if (last != last_bulk)
882     last--;
883   if (last[0] == '\n')
884   {
885     rev = 1;
886     last[0] = '\0';
887   }
888   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
889                                                (last_bulk_time), GNUNET_YES);
890   snprintf (msg, sizeof (msg),
891             _("Message `%.*s' repeated %u times in the last %s\n"),
892             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
893   if (rev == 1)
894     last[0] = '\n';
895   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
896   last_bulk_time = GNUNET_TIME_absolute_get ();
897   last_bulk_repeat = 0;
898 }
899
900
901 /**
902  * Ignore the next n calls to the log function.
903  *
904  * @param n number of log calls to ignore (could be negative)
905  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
906  */
907 void
908 GNUNET_log_skip (int n,
909                  int check_reset)
910 {
911   int ok;
912
913   if (0 == n)
914   {
915     ok = (0 == skip_log);
916     skip_log = 0;
917     if (check_reset)
918       GNUNET_break (ok);
919   }
920   else
921   {
922     skip_log += n;
923   }
924 }
925
926
927 /**
928  * Get the number of log calls that are going to be skipped
929  *
930  * @return number of log calls to be ignored
931  */
932 int
933 GNUNET_get_log_skip ()
934 {
935   return skip_log;
936 }
937
938
939 /**
940  * Output a log message using the default mechanism.
941  *
942  * @param kind how severe was the issue
943  * @param comp component responsible
944  * @param message the actual message
945  * @param va arguments to the format string "message"
946  */
947 static void
948 mylog (enum GNUNET_ErrorType kind,
949        const char *comp,
950        const char *message,
951        va_list va)
952 {
953   char date[DATE_STR_SIZE];
954   char date2[DATE_STR_SIZE];
955   struct tm *tmptr;
956   size_t size;
957   va_list vacp;
958
959   va_copy (vacp, va);
960   size = VSNPRINTF (NULL,
961                     0,
962                     message,
963                     vacp) + 1;
964   GNUNET_assert (0 != size);
965   va_end (vacp);
966   memset (date,
967           0,
968           DATE_STR_SIZE);
969   {
970     char buf[size];
971     long long offset;
972 #ifdef WINDOWS
973     LARGE_INTEGER pc;
974     time_t timetmp;
975
976     offset = GNUNET_TIME_get_offset ();
977     time (&timetmp);
978     timetmp += offset / 1000;
979     tmptr = localtime (&timetmp);
980     pc.QuadPart = 0;
981     QueryPerformanceCounter (&pc);
982     if (NULL == tmptr)
983     {
984       strcpy (date, "localtime error");
985     }
986     else
987     {
988       if (0 ==
989           strftime (date2,
990                     DATE_STR_SIZE,
991                     "%b %d %H:%M:%S-%%020llu",
992                     tmptr))
993         abort ();
994       if (0 >
995           snprintf (date,
996                     sizeof (date),
997                     date2,
998                     (long long) (pc.QuadPart /
999                                  (performance_frequency.QuadPart / 1000))))
1000         abort ();
1001     }
1002 #else
1003     struct timeval timeofday;
1004
1005     gettimeofday (&timeofday,
1006                   NULL);
1007     offset = GNUNET_TIME_get_offset ();
1008     if (offset > 0)
1009     {
1010       timeofday.tv_sec += offset / 1000LL;
1011       timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1012       if (timeofday.tv_usec > 1000000LL)
1013       {
1014         timeofday.tv_usec -= 1000000LL;
1015         timeofday.tv_sec++;
1016       }
1017     }
1018     else
1019     {
1020       timeofday.tv_sec += offset / 1000LL;
1021       if (timeofday.tv_usec > - (offset % 1000LL) * 1000LL)
1022       {
1023         timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1024       }
1025       else
1026       {
1027         timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
1028         timeofday.tv_sec--;
1029       }
1030     }
1031     tmptr = localtime (&timeofday.tv_sec);
1032     if (NULL == tmptr)
1033     {
1034       strcpy (date,
1035               "localtime error");
1036     }
1037     else
1038     {
1039       if (0 ==
1040           strftime (date2,
1041                     DATE_STR_SIZE,
1042                     "%b %d %H:%M:%S-%%06u",
1043                     tmptr))
1044         abort ();
1045       if (0 >
1046           snprintf (date,
1047                     sizeof (date),
1048                     date2,
1049                     timeofday.tv_usec))
1050         abort ();
1051     }
1052 #endif
1053     VSNPRINTF (buf,
1054                size,
1055                message,
1056                va);
1057 #if ! (defined(GNUNET_CULL_LOGGING) || TALER_WALLET_ONLY)
1058     if (NULL != tmptr)
1059       (void) setup_log_file (tmptr);
1060 #endif
1061     if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
1062         (0 != last_bulk_time.abs_value_us) &&
1063         (0 == strncmp (buf,
1064                        last_bulk,
1065                        sizeof (last_bulk))))
1066     {
1067       last_bulk_repeat++;
1068       if ( (GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
1069             BULK_DELAY_THRESHOLD) ||
1070            (last_bulk_repeat > BULK_REPEAT_THRESHOLD) )
1071         flush_bulk (date);
1072       return;
1073     }
1074     flush_bulk (date);
1075     strncpy (last_bulk,
1076              buf,
1077              sizeof (last_bulk));
1078     last_bulk_repeat = 0;
1079     last_bulk_kind = kind;
1080     last_bulk_time = GNUNET_TIME_absolute_get ();
1081     strncpy (last_bulk_comp,
1082              comp,
1083              COMP_TRACK_SIZE);
1084     output_message (kind,
1085                     comp,
1086                     date,
1087                     buf);
1088   }
1089 }
1090
1091
1092 /**
1093  * Main log function.
1094  *
1095  * @param kind how serious is the error?
1096  * @param message what is the message (format string)
1097  * @param ... arguments for format string
1098  */
1099 void
1100 GNUNET_log_nocheck (enum GNUNET_ErrorType kind,
1101                     const char *message, ...)
1102 {
1103   va_list va;
1104
1105   va_start (va, message);
1106   mylog (kind, component, message, va);
1107   va_end (va);
1108 }
1109
1110
1111 /**
1112  * Log function that specifies an alternative component.
1113  * This function should be used by plugins.
1114  *
1115  * @param kind how serious is the error?
1116  * @param comp component responsible for generating the message
1117  * @param message what is the message (format string)
1118  * @param ... arguments for format string
1119  */
1120 void
1121 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
1122                          const char *message, ...)
1123 {
1124   va_list va;
1125   char comp_w_pid[128];
1126
1127   if (comp == NULL)
1128     comp = component_nopid;
1129
1130   va_start (va, message);
1131   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
1132   mylog (kind, comp_w_pid, message, va);
1133   va_end (va);
1134 }
1135
1136
1137 /**
1138  * Convert error type to string.
1139  *
1140  * @param kind type to convert
1141  * @return string corresponding to the type
1142  */
1143 const char *
1144 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1145 {
1146   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1147     return _("ERROR");
1148   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1149     return _("WARNING");
1150   if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0)
1151     return _("MESSAGE");
1152   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1153     return _("INFO");
1154   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1155     return _("DEBUG");
1156   if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1157     return _("NONE");
1158   return _("INVALID");
1159 }
1160
1161
1162 /**
1163  * Convert a hash to a string (for printing debug messages).
1164  * This is one of the very few calls in the entire API that is
1165  * NOT reentrant!
1166  *
1167  * @param hc the hash code
1168  * @return string form; will be overwritten by next call to GNUNET_h2s.
1169  */
1170 const char *
1171 GNUNET_h2s (const struct GNUNET_HashCode * hc)
1172 {
1173   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1174
1175   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1176   ret.encoding[8] = '\0';
1177   return (const char *) ret.encoding;
1178 }
1179
1180
1181 /**
1182  * Convert a hash to a string (for printing debug messages).
1183  * This is one of the very few calls in the entire API that is
1184  * NOT reentrant! Identical to #GNUNET_h2s(), except that another
1185  * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
1186  * used within the same log statement.
1187  *
1188  * @param hc the hash code
1189  * @return string form; will be overwritten by next call to GNUNET_h2s.
1190  */
1191 const char *
1192 GNUNET_h2s2 (const struct GNUNET_HashCode * hc)
1193 {
1194   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1195
1196   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1197   ret.encoding[8] = '\0';
1198   return (const char *) ret.encoding;
1199 }
1200
1201
1202 /**
1203  * @ingroup logging
1204  * Convert a public key value to a string (for printing debug messages).
1205  * This is one of the very few calls in the entire API that is
1206  * NOT reentrant!
1207  *
1208  * @param hc the hash code
1209  * @return string
1210  */
1211 const char *
1212 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1213 {
1214   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1215   struct GNUNET_HashCode hc;
1216
1217   GNUNET_CRYPTO_hash (p,
1218                       sizeof (*p),
1219                       &hc);
1220   GNUNET_CRYPTO_hash_to_enc (&hc,
1221                              &ret);
1222   ret.encoding[6] = '\0';
1223   return (const char *) ret.encoding;
1224 }
1225
1226
1227 /**
1228  * @ingroup logging
1229  * Convert a public key value to a string (for printing debug messages).
1230  * This is one of the very few calls in the entire API that is
1231  * NOT reentrant!
1232  *
1233  * @param hc the hash code
1234  * @return string
1235  */
1236 const char *
1237 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1238 {
1239   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1240   struct GNUNET_HashCode hc;
1241
1242   GNUNET_CRYPTO_hash (p,
1243                       sizeof (*p),
1244                       &hc);
1245   GNUNET_CRYPTO_hash_to_enc (&hc,
1246                              &ret);
1247   ret.encoding[6] = '\0';
1248   return (const char *) ret.encoding;
1249 }
1250
1251
1252 /**
1253  * @ingroup logging
1254  * Convert a public key value to a string (for printing debug messages).
1255  * This is one of the very few calls in the entire API that is
1256  * NOT reentrant!
1257  *
1258  * @param hc the hash code
1259  * @return string
1260  */
1261 const char *
1262 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1263 {
1264   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1265   struct GNUNET_HashCode hc;
1266
1267   GNUNET_CRYPTO_hash (p,
1268                       sizeof (*p),
1269                       &hc);
1270   GNUNET_CRYPTO_hash_to_enc (&hc,
1271                              &ret);
1272   ret.encoding[6] = '\0';
1273   return (const char *) ret.encoding;
1274 }
1275
1276
1277 /**
1278  * @ingroup logging
1279  * Convert a public key value to a string (for printing debug messages).
1280  * This is one of the very few calls in the entire API that is
1281  * NOT reentrant!
1282  *
1283  * @param hc the hash code
1284  * @return string
1285  */
1286 const char *
1287 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1288 {
1289   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1290   struct GNUNET_HashCode hc;
1291
1292   GNUNET_CRYPTO_hash (p,
1293                       sizeof (*p),
1294                       &hc);
1295   GNUNET_CRYPTO_hash_to_enc (&hc,
1296                              &ret);
1297   ret.encoding[6] = '\0';
1298   return (const char *) ret.encoding;
1299 }
1300
1301
1302 /**
1303  * @ingroup logging
1304  * Convert a short hash value to a string (for printing debug messages).
1305  * This is one of the very few calls in the entire API that is
1306  * NOT reentrant!
1307  *
1308  * @param shc the hash code
1309  * @return string
1310  */
1311 const char *
1312 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc)
1313 {
1314   static char buf[64];
1315
1316   GNUNET_STRINGS_data_to_string (shc,
1317                                  sizeof (*shc),
1318                                  buf,
1319                                  sizeof (buf));
1320   buf[6] = '\0';
1321   return (const char *) buf;
1322 }
1323
1324
1325 /**
1326  * Convert a hash to a string (for printing debug messages).
1327  * This is one of the very few calls in the entire API that is
1328  * NOT reentrant!
1329  *
1330  * @param hc the hash code
1331  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1332  */
1333 const char *
1334 GNUNET_h2s_full (const struct GNUNET_HashCode * hc)
1335 {
1336   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1337
1338   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1339   ret.encoding[sizeof (ret) - 1] = '\0';
1340   return (const char *) ret.encoding;
1341 }
1342
1343
1344 /**
1345  * Convert a peer identity to a string (for printing debug messages).
1346  * This is one of the very few calls in the entire API that is
1347  * NOT reentrant!
1348  *
1349  * @param pid the peer identity
1350  * @return string form of the pid; will be overwritten by next
1351  *         call to #GNUNET_i2s.
1352  */
1353 const char *
1354 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1355 {
1356   static char buf[5];
1357   char *ret;
1358
1359   if (NULL == pid)
1360     return "NULL";
1361   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1362   strncpy (buf,
1363            ret,
1364            sizeof (buf) - 1);
1365   GNUNET_free (ret);
1366   buf[4] = '\0';
1367   return buf;
1368 }
1369
1370
1371 /**
1372  * Convert a peer identity to a string (for printing debug messages).
1373  * This is one of the very few calls in the entire API that is
1374  * NOT reentrant!  Identical to #GNUNET_i2s(), except that another
1375  * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
1376  * used within the same log statement.
1377  *
1378  * @param pid the peer identity
1379  * @return string form of the pid; will be overwritten by next
1380  *         call to #GNUNET_i2s.
1381  */
1382 const char *
1383 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid)
1384 {
1385   static char buf[5];
1386   char *ret;
1387
1388   if (NULL == pid)
1389     return "NULL";
1390   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1391   strncpy (buf,
1392            ret,
1393            sizeof (buf) - 1);
1394   GNUNET_free (ret);
1395   buf[4] = '\0';
1396   return buf;
1397 }
1398
1399
1400 /**
1401  * Convert a peer identity to a string (for printing debug messages).
1402  * This is one of the very few calls in the entire API that is
1403  * NOT reentrant!
1404  *
1405  * @param pid the peer identity
1406  * @return string form of the pid; will be overwritten by next
1407  *         call to #GNUNET_i2s_full.
1408  */
1409 const char *
1410 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1411 {
1412   static char buf[256];
1413   char *ret;
1414
1415   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1416   strcpy (buf, ret);
1417   GNUNET_free (ret);
1418   return buf;
1419 }
1420
1421
1422 /**
1423  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1424  * (for printing debug messages).  This is one of the very few calls
1425  * in the entire API that is NOT reentrant!
1426  *
1427  * @param addr the address
1428  * @param addrlen the length of the address in @a addr
1429  * @return nicely formatted string for the address
1430  *  will be overwritten by next call to #GNUNET_a2s.
1431  */
1432 const char *
1433 GNUNET_a2s (const struct sockaddr *addr,
1434             socklen_t addrlen)
1435 {
1436 #ifndef WINDOWS
1437 #define LEN GNUNET_MAX ((INET6_ADDRSTRLEN + 8),         \
1438                         (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t)))
1439 #else
1440 #define LEN (INET6_ADDRSTRLEN + 8)
1441 #endif
1442   static char buf[LEN];
1443 #undef LEN
1444   static char b2[6];
1445   const struct sockaddr_in *v4;
1446   const struct sockaddr_un *un;
1447   const struct sockaddr_in6 *v6;
1448   unsigned int off;
1449
1450   if (addr == NULL)
1451     return _("unknown address");
1452   switch (addr->sa_family)
1453   {
1454   case AF_INET:
1455     if (addrlen != sizeof (struct sockaddr_in))
1456       return "<invalid v4 address>";
1457     v4 = (const struct sockaddr_in *) addr;
1458     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1459     if (0 == ntohs (v4->sin_port))
1460       return buf;
1461     strcat (buf, ":");
1462     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
1463     strcat (buf, b2);
1464     return buf;
1465   case AF_INET6:
1466     if (addrlen != sizeof (struct sockaddr_in6))
1467       return "<invalid v4 address>";
1468     v6 = (const struct sockaddr_in6 *) addr;
1469     buf[0] = '[';
1470     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1471     if (0 == ntohs (v6->sin6_port))
1472       return &buf[1];
1473     strcat (buf, "]:");
1474     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1475     strcat (buf, b2);
1476     return buf;
1477   case AF_UNIX:
1478     if (addrlen <= sizeof (sa_family_t))
1479       return "<unbound UNIX client>";
1480     un = (const struct sockaddr_un *) addr;
1481     off = 0;
1482     if ('\0' == un->sun_path[0])
1483       off++;
1484     memset (buf, 0, sizeof (buf));
1485     GNUNET_snprintf (buf,
1486                      sizeof (buf),
1487                      "%s%.*s",
1488                      (1 == off) ? "@" : "",
1489                      (int) (addrlen - sizeof (sa_family_t) - off),
1490                      &un->sun_path[off]);
1491     return buf;
1492   default:
1493     return _("invalid address");
1494   }
1495 }
1496
1497
1498 /**
1499  * Log error message about missing configuration option.
1500  *
1501  * @param kind log level
1502  * @param section section with missing option
1503  * @param option name of missing option
1504  */
1505 void
1506 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1507                            const char *section,
1508                            const char *option)
1509 {
1510   GNUNET_log (kind,
1511               _("Configuration fails to specify option `%s' in section `%s'!\n"),
1512               option,
1513               section);
1514 }
1515
1516
1517 /**
1518  * Log error message about invalid configuration option value.
1519  *
1520  * @param kind log level
1521  * @param section section with invalid option
1522  * @param option name of invalid option
1523  * @param required what is required that is invalid about the option
1524  */
1525 void
1526 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1527                            const char *section,
1528                            const char *option,
1529                            const char *required)
1530 {
1531   GNUNET_log (kind,
1532               _("Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1533               option, section, required);
1534 }
1535
1536
1537 /**
1538  * Initializer
1539  */
1540 void __attribute__ ((constructor))
1541 GNUNET_util_cl_init ()
1542 {
1543   GNUNET_stderr = stderr;
1544 #ifdef MINGW
1545   GNInitWinEnv (NULL);
1546 #endif
1547 #if WINDOWS
1548   if (!InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400))
1549     GNUNET_abort_ ();
1550 #endif
1551 }
1552
1553
1554 /**
1555  * Destructor
1556  */
1557 void __attribute__ ((destructor))
1558 GNUNET_util_cl_fini ()
1559 {
1560 #if WINDOWS
1561   DeleteCriticalSection (&output_message_cs);
1562 #endif
1563 #ifdef MINGW
1564   GNShutdownWinEnv ();
1565 #endif
1566 }
1567
1568 /* end of common_logging.c */