i18n, fix typo, better logging
[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,
631                 _("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
632                 p);
633         break;
634       }
635       start = p + 1;
636       state++;
637       break;
638     case '\0':                 /* found EOL */
639       keep_looking = 0;
640       /* fall through to '/' */
641     case '/':                  /* found a definition separator */
642       switch (state)
643       {
644       case 4:                  /* within a log level */
645         p[0] = '\0';
646         state = 0;
647         level = get_type ((const char *) start);
648         if ( (GNUNET_ERROR_TYPE_INVALID == level) ||
649              (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
650              (0 != add_definition (comp, file, function, from_line, to_line,
651                                    level, force)) )
652         {
653           GNUNET_free (def);
654           return counter;
655         }
656         counter++;
657         start = p + 1;
658         break;
659       default:
660         fprintf(stderr,
661                 _("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
662                 p);
663         break;
664       }
665     default:
666       break;
667     }
668   }
669   GNUNET_free (def);
670   return counter;
671 }
672
673
674 /**
675  * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
676  */
677 static void
678 parse_all_definitions ()
679 {
680   if (GNUNET_NO == gnunet_log_parsed)
681     parse_definitions ("GNUNET_LOG", 0);
682   gnunet_log_parsed = GNUNET_YES;
683   if (GNUNET_NO == gnunet_force_log_parsed)
684     gnunet_force_log_present =
685         parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
686   gnunet_force_log_parsed = GNUNET_YES;
687 }
688 #endif
689
690
691 /**
692  * Setup logging.
693  *
694  * @param comp default component to use
695  * @param loglevel what types of messages should be logged
696  * @param logfile which file to write log messages to (can be NULL)
697  * @return #GNUNET_OK on success
698  */
699 int
700 GNUNET_log_setup (const char *comp,
701                   const char *loglevel,
702                   const char *logfile)
703 {
704   const char *env_logfile;
705
706   min_level = get_type (loglevel);
707 #if !defined(GNUNET_CULL_LOGGING)
708   parse_all_definitions ();
709 #endif
710 #ifdef WINDOWS
711   QueryPerformanceFrequency (&performance_frequency);
712 #endif
713   GNUNET_free_non_null (component);
714   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
715   GNUNET_free_non_null (component_nopid);
716   component_nopid = GNUNET_strdup (comp);
717
718   env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
719   if ((NULL != env_logfile) && (strlen (env_logfile) > 0))
720     logfile = env_logfile;
721   if (NULL == logfile)
722     return GNUNET_OK;
723   GNUNET_free_non_null (log_file_name);
724   log_file_name = GNUNET_STRINGS_filename_expand (logfile);
725   if (NULL == log_file_name)
726     return GNUNET_SYSERR;
727 #if TALER_WALLET_ONLY || defined(GNUNET_CULL_LOGGING)
728   /* log file option not allowed for wallet logic */
729   GNUNET_assert (NULL == logfile);
730   return GNUNET_OK;
731 #else
732   {
733     time_t t;
734     const struct tm *tm;
735
736     t = time (NULL);
737     tm = gmtime (&t);
738     return setup_log_file (tm);
739   }
740 #endif
741 }
742
743
744 /**
745  * Add a custom logger. Note that installing any custom logger
746  * will disable the standard logger.  When multiple custom loggers
747  * are installed, all will be called.  The standard logger will
748  * only be used if no custom loggers are present.
749  *
750  * @param logger log function
751  * @param logger_cls closure for @a logger
752  */
753 void
754 GNUNET_logger_add (GNUNET_Logger logger,
755                    void *logger_cls)
756 {
757   struct CustomLogger *entry;
758
759   entry = GNUNET_new (struct CustomLogger);
760   entry->logger = logger;
761   entry->logger_cls = logger_cls;
762   entry->next = loggers;
763   loggers = entry;
764 }
765
766
767 /**
768  * Remove a custom logger.
769  *
770  * @param logger log function
771  * @param logger_cls closure for @a logger
772  */
773 void
774 GNUNET_logger_remove (GNUNET_Logger logger,
775                       void *logger_cls)
776 {
777   struct CustomLogger *pos;
778   struct CustomLogger *prev;
779
780   prev = NULL;
781   pos = loggers;
782   while ((NULL != pos) &&
783          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
784   {
785     prev = pos;
786     pos = pos->next;
787   }
788   GNUNET_assert (NULL != pos);
789   if (NULL == prev)
790     loggers = pos->next;
791   else
792     prev->next = pos->next;
793   GNUNET_free (pos);
794 }
795
796 #if WINDOWS
797 CRITICAL_SECTION output_message_cs;
798 #endif
799
800
801 /**
802  * Actually output the log message.
803  *
804  * @param kind how severe was the issue
805  * @param comp component responsible
806  * @param datestr current date/time
807  * @param msg the actual message
808  */
809 static void
810 output_message (enum GNUNET_ErrorType kind,
811                 const char *comp,
812                 const char *datestr,
813                 const char *msg)
814 {
815   struct CustomLogger *pos;
816
817 #if WINDOWS
818   EnterCriticalSection (&output_message_cs);
819 #endif
820   /* only use the standard logger if no custom loggers are present */
821   if ( (NULL != GNUNET_stderr) &&
822        (NULL == loggers) )
823   {
824     if (kind == GNUNET_ERROR_TYPE_MESSAGE)
825     {
826       /* The idea here is to produce "normal" output messages
827        * for end users while still having the power of the
828        * logging engine for developer needs. So ideally this
829        * is what it should look like when CLI tools are used
830        * interactively, yet the same message shouldn't look
831        * this way if the output is going to logfiles or robots
832        * instead.
833        */
834       FPRINTF (GNUNET_stderr,
835                "* %s",
836                msg);
837     }
838     else
839     {
840       FPRINTF (GNUNET_stderr,
841                "%s %s %s %s",
842                datestr,
843                comp,
844                GNUNET_error_type_to_string (kind),
845                msg);
846     }
847     fflush (GNUNET_stderr);
848   }
849   pos = loggers;
850   while (NULL != pos)
851   {
852     pos->logger (pos->logger_cls,
853                  kind,
854                  comp,
855                  datestr,
856                  msg);
857     pos = pos->next;
858   }
859 #if WINDOWS
860   LeaveCriticalSection (&output_message_cs);
861 #endif
862 }
863
864
865 /**
866  * Flush an existing bulk report to the output.
867  *
868  * @param datestr our current timestamp
869  */
870 static void
871 flush_bulk (const char *datestr)
872 {
873   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
874   int rev;
875   char *last;
876   const char *ft;
877
878   if ( (0 == last_bulk_time.abs_value_us) ||
879        (0 == last_bulk_repeat) )
880     return;
881   rev = 0;
882   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
883   if (last == NULL)
884     last = &last_bulk[BULK_TRACK_SIZE - 1];
885   else if (last != last_bulk)
886     last--;
887   if (last[0] == '\n')
888   {
889     rev = 1;
890     last[0] = '\0';
891   }
892   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
893                                                (last_bulk_time), GNUNET_YES);
894   snprintf (msg, sizeof (msg),
895             _("Message `%.*s' repeated %u times in the last %s\n"),
896             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
897   if (rev == 1)
898     last[0] = '\n';
899   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
900   last_bulk_time = GNUNET_TIME_absolute_get ();
901   last_bulk_repeat = 0;
902 }
903
904
905 /**
906  * Ignore the next n calls to the log function.
907  *
908  * @param n number of log calls to ignore (could be negative)
909  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
910  */
911 void
912 GNUNET_log_skip (int n,
913                  int check_reset)
914 {
915   int ok;
916
917   if (0 == n)
918   {
919     ok = (0 == skip_log);
920     skip_log = 0;
921     if (check_reset)
922       GNUNET_break (ok);
923   }
924   else
925   {
926     skip_log += n;
927   }
928 }
929
930
931 /**
932  * Get the number of log calls that are going to be skipped
933  *
934  * @return number of log calls to be ignored
935  */
936 int
937 GNUNET_get_log_skip ()
938 {
939   return skip_log;
940 }
941
942
943 /**
944  * Output a log message using the default mechanism.
945  *
946  * @param kind how severe was the issue
947  * @param comp component responsible
948  * @param message the actual message
949  * @param va arguments to the format string "message"
950  */
951 static void
952 mylog (enum GNUNET_ErrorType kind,
953        const char *comp,
954        const char *message,
955        va_list va)
956 {
957   char date[DATE_STR_SIZE];
958   char date2[DATE_STR_SIZE];
959   struct tm *tmptr;
960   size_t size;
961   va_list vacp;
962
963   va_copy (vacp, va);
964   size = VSNPRINTF (NULL,
965                     0,
966                     message,
967                     vacp) + 1;
968   GNUNET_assert (0 != size);
969   va_end (vacp);
970   memset (date,
971           0,
972           DATE_STR_SIZE);
973   {
974     char buf[size];
975     long long offset;
976 #ifdef WINDOWS
977     LARGE_INTEGER pc;
978     time_t timetmp;
979
980     offset = GNUNET_TIME_get_offset ();
981     time (&timetmp);
982     timetmp += offset / 1000;
983     tmptr = localtime (&timetmp);
984     pc.QuadPart = 0;
985     QueryPerformanceCounter (&pc);
986     if (NULL == tmptr)
987     {
988       strcpy (date, "localtime error");
989     }
990     else
991     {
992       if (0 ==
993           strftime (date2,
994                     DATE_STR_SIZE,
995                     "%b %d %H:%M:%S-%%020llu",
996                     tmptr))
997         abort ();
998       if (0 >
999           snprintf (date,
1000                     sizeof (date),
1001                     date2,
1002                     (long long) (pc.QuadPart /
1003                                  (performance_frequency.QuadPart / 1000))))
1004         abort ();
1005     }
1006 #else
1007     struct timeval timeofday;
1008
1009     gettimeofday (&timeofday,
1010                   NULL);
1011     offset = GNUNET_TIME_get_offset ();
1012     if (offset > 0)
1013     {
1014       timeofday.tv_sec += offset / 1000LL;
1015       timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1016       if (timeofday.tv_usec > 1000000LL)
1017       {
1018         timeofday.tv_usec -= 1000000LL;
1019         timeofday.tv_sec++;
1020       }
1021     }
1022     else
1023     {
1024       timeofday.tv_sec += offset / 1000LL;
1025       if (timeofday.tv_usec > - (offset % 1000LL) * 1000LL)
1026       {
1027         timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1028       }
1029       else
1030       {
1031         timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
1032         timeofday.tv_sec--;
1033       }
1034     }
1035     tmptr = localtime (&timeofday.tv_sec);
1036     if (NULL == tmptr)
1037     {
1038       strcpy (date,
1039               "localtime error");
1040     }
1041     else
1042     {
1043       if (0 ==
1044           strftime (date2,
1045                     DATE_STR_SIZE,
1046                     "%b %d %H:%M:%S-%%06u",
1047                     tmptr))
1048         abort ();
1049       if (0 >
1050           snprintf (date,
1051                     sizeof (date),
1052                     date2,
1053                     timeofday.tv_usec))
1054         abort ();
1055     }
1056 #endif
1057     VSNPRINTF (buf,
1058                size,
1059                message,
1060                va);
1061 #if ! (defined(GNUNET_CULL_LOGGING) || TALER_WALLET_ONLY)
1062     if (NULL != tmptr)
1063       (void) setup_log_file (tmptr);
1064 #endif
1065     if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
1066         (0 != last_bulk_time.abs_value_us) &&
1067         (0 == strncmp (buf,
1068                        last_bulk,
1069                        sizeof (last_bulk))))
1070     {
1071       last_bulk_repeat++;
1072       if ( (GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us >
1073             BULK_DELAY_THRESHOLD) ||
1074            (last_bulk_repeat > BULK_REPEAT_THRESHOLD) )
1075         flush_bulk (date);
1076       return;
1077     }
1078     flush_bulk (date);
1079     strncpy (last_bulk,
1080              buf,
1081              sizeof (last_bulk));
1082     last_bulk_repeat = 0;
1083     last_bulk_kind = kind;
1084     last_bulk_time = GNUNET_TIME_absolute_get ();
1085     strncpy (last_bulk_comp,
1086              comp,
1087              COMP_TRACK_SIZE);
1088     output_message (kind,
1089                     comp,
1090                     date,
1091                     buf);
1092   }
1093 }
1094
1095
1096 /**
1097  * Main log function.
1098  *
1099  * @param kind how serious is the error?
1100  * @param message what is the message (format string)
1101  * @param ... arguments for format string
1102  */
1103 void
1104 GNUNET_log_nocheck (enum GNUNET_ErrorType kind,
1105                     const char *message, ...)
1106 {
1107   va_list va;
1108
1109   va_start (va, message);
1110   mylog (kind, component, message, va);
1111   va_end (va);
1112 }
1113
1114
1115 /**
1116  * Log function that specifies an alternative component.
1117  * This function should be used by plugins.
1118  *
1119  * @param kind how serious is the error?
1120  * @param comp component responsible for generating the message
1121  * @param message what is the message (format string)
1122  * @param ... arguments for format string
1123  */
1124 void
1125 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
1126                          const char *message, ...)
1127 {
1128   va_list va;
1129   char comp_w_pid[128];
1130
1131   if (comp == NULL)
1132     comp = component_nopid;
1133
1134   va_start (va, message);
1135   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
1136   mylog (kind, comp_w_pid, message, va);
1137   va_end (va);
1138 }
1139
1140
1141 /**
1142  * Convert error type to string.
1143  *
1144  * @param kind type to convert
1145  * @return string corresponding to the type
1146  */
1147 const char *
1148 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1149 {
1150   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1151     return _("ERROR");
1152   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1153     return _("WARNING");
1154   if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0)
1155     return _("MESSAGE");
1156   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1157     return _("INFO");
1158   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1159     return _("DEBUG");
1160   if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1161     return _("NONE");
1162   return _("INVALID");
1163 }
1164
1165
1166 /**
1167  * Convert a hash to a string (for printing debug messages).
1168  * This is one of the very few calls in the entire API that is
1169  * NOT reentrant!
1170  *
1171  * @param hc the hash code
1172  * @return string form; will be overwritten by next call to GNUNET_h2s.
1173  */
1174 const char *
1175 GNUNET_h2s (const struct GNUNET_HashCode * hc)
1176 {
1177   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1178
1179   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1180   ret.encoding[8] = '\0';
1181   return (const char *) ret.encoding;
1182 }
1183
1184
1185 /**
1186  * Convert a hash to a string (for printing debug messages).
1187  * This is one of the very few calls in the entire API that is
1188  * NOT reentrant! Identical to #GNUNET_h2s(), except that another
1189  * buffer is used so both #GNUNET_h2s() and #GNUNET_h2s2() can be
1190  * used within the same log statement.
1191  *
1192  * @param hc the hash code
1193  * @return string form; will be overwritten by next call to GNUNET_h2s.
1194  */
1195 const char *
1196 GNUNET_h2s2 (const struct GNUNET_HashCode * hc)
1197 {
1198   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1199
1200   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1201   ret.encoding[8] = '\0';
1202   return (const char *) ret.encoding;
1203 }
1204
1205
1206 /**
1207  * @ingroup logging
1208  * Convert a public key value to a string (for printing debug messages).
1209  * This is one of the very few calls in the entire API that is
1210  * NOT reentrant!
1211  *
1212  * @param hc the hash code
1213  * @return string
1214  */
1215 const char *
1216 GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1217 {
1218   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1219   struct GNUNET_HashCode hc;
1220
1221   GNUNET_CRYPTO_hash (p,
1222                       sizeof (*p),
1223                       &hc);
1224   GNUNET_CRYPTO_hash_to_enc (&hc,
1225                              &ret);
1226   ret.encoding[6] = '\0';
1227   return (const char *) ret.encoding;
1228 }
1229
1230
1231 /**
1232  * @ingroup logging
1233  * Convert a public key value to a string (for printing debug messages).
1234  * This is one of the very few calls in the entire API that is
1235  * NOT reentrant!
1236  *
1237  * @param hc the hash code
1238  * @return string
1239  */
1240 const char *
1241 GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1242 {
1243   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1244   struct GNUNET_HashCode hc;
1245
1246   GNUNET_CRYPTO_hash (p,
1247                       sizeof (*p),
1248                       &hc);
1249   GNUNET_CRYPTO_hash_to_enc (&hc,
1250                              &ret);
1251   ret.encoding[6] = '\0';
1252   return (const char *) ret.encoding;
1253 }
1254
1255
1256 /**
1257  * @ingroup logging
1258  * Convert a public key value to a string (for printing debug messages).
1259  * This is one of the very few calls in the entire API that is
1260  * NOT reentrant!
1261  *
1262  * @param hc the hash code
1263  * @return string
1264  */
1265 const char *
1266 GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1267 {
1268   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1269   struct GNUNET_HashCode hc;
1270
1271   GNUNET_CRYPTO_hash (p,
1272                       sizeof (*p),
1273                       &hc);
1274   GNUNET_CRYPTO_hash_to_enc (&hc,
1275                              &ret);
1276   ret.encoding[6] = '\0';
1277   return (const char *) ret.encoding;
1278 }
1279
1280
1281 /**
1282  * @ingroup logging
1283  * Convert a public key value to a string (for printing debug messages).
1284  * This is one of the very few calls in the entire API that is
1285  * NOT reentrant!
1286  *
1287  * @param hc the hash code
1288  * @return string
1289  */
1290 const char *
1291 GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1292 {
1293   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1294   struct GNUNET_HashCode hc;
1295
1296   GNUNET_CRYPTO_hash (p,
1297                       sizeof (*p),
1298                       &hc);
1299   GNUNET_CRYPTO_hash_to_enc (&hc,
1300                              &ret);
1301   ret.encoding[6] = '\0';
1302   return (const char *) ret.encoding;
1303 }
1304
1305
1306 /**
1307  * @ingroup logging
1308  * Convert a short hash value to a string (for printing debug messages).
1309  * This is one of the very few calls in the entire API that is
1310  * NOT reentrant!
1311  *
1312  * @param shc the hash code
1313  * @return string
1314  */
1315 const char *
1316 GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc)
1317 {
1318   static char buf[64];
1319
1320   GNUNET_STRINGS_data_to_string (shc,
1321                                  sizeof (*shc),
1322                                  buf,
1323                                  sizeof (buf));
1324   buf[6] = '\0';
1325   return (const char *) buf;
1326 }
1327
1328
1329 /**
1330  * Convert a hash to a string (for printing debug messages).
1331  * This is one of the very few calls in the entire API that is
1332  * NOT reentrant!
1333  *
1334  * @param hc the hash code
1335  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1336  */
1337 const char *
1338 GNUNET_h2s_full (const struct GNUNET_HashCode * hc)
1339 {
1340   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1341
1342   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
1343   ret.encoding[sizeof (ret) - 1] = '\0';
1344   return (const char *) ret.encoding;
1345 }
1346
1347
1348 /**
1349  * Convert a peer identity to a string (for printing debug messages).
1350  * This is one of the very few calls in the entire API that is
1351  * NOT reentrant!
1352  *
1353  * @param pid the peer identity
1354  * @return string form of the pid; will be overwritten by next
1355  *         call to #GNUNET_i2s.
1356  */
1357 const char *
1358 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1359 {
1360   static char buf[5];
1361   char *ret;
1362
1363   if (NULL == pid)
1364     return "NULL";
1365   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1366   strncpy (buf,
1367            ret,
1368            sizeof (buf) - 1);
1369   GNUNET_free (ret);
1370   buf[4] = '\0';
1371   return buf;
1372 }
1373
1374
1375 /**
1376  * Convert a peer identity to a string (for printing debug messages).
1377  * This is one of the very few calls in the entire API that is
1378  * NOT reentrant!  Identical to #GNUNET_i2s(), except that another
1379  * buffer is used so both #GNUNET_i2s() and #GNUNET_i2s2() can be
1380  * used within the same log statement.
1381  *
1382  * @param pid the peer identity
1383  * @return string form of the pid; will be overwritten by next
1384  *         call to #GNUNET_i2s.
1385  */
1386 const char *
1387 GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid)
1388 {
1389   static char buf[5];
1390   char *ret;
1391
1392   if (NULL == pid)
1393     return "NULL";
1394   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1395   strncpy (buf,
1396            ret,
1397            sizeof (buf) - 1);
1398   GNUNET_free (ret);
1399   buf[4] = '\0';
1400   return buf;
1401 }
1402
1403
1404 /**
1405  * Convert a peer identity to a string (for printing debug messages).
1406  * This is one of the very few calls in the entire API that is
1407  * NOT reentrant!
1408  *
1409  * @param pid the peer identity
1410  * @return string form of the pid; will be overwritten by next
1411  *         call to #GNUNET_i2s_full.
1412  */
1413 const char *
1414 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1415 {
1416   static char buf[256];
1417   char *ret;
1418
1419   ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key);
1420   strcpy (buf, ret);
1421   GNUNET_free (ret);
1422   return buf;
1423 }
1424
1425
1426 /**
1427  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
1428  * (for printing debug messages).  This is one of the very few calls
1429  * in the entire API that is NOT reentrant!
1430  *
1431  * @param addr the address
1432  * @param addrlen the length of the address in @a addr
1433  * @return nicely formatted string for the address
1434  *  will be overwritten by next call to #GNUNET_a2s.
1435  */
1436 const char *
1437 GNUNET_a2s (const struct sockaddr *addr,
1438             socklen_t addrlen)
1439 {
1440 #ifndef WINDOWS
1441 #define LEN GNUNET_MAX ((INET6_ADDRSTRLEN + 8),         \
1442                         (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t)))
1443 #else
1444 #define LEN (INET6_ADDRSTRLEN + 8)
1445 #endif
1446   static char buf[LEN];
1447 #undef LEN
1448   static char b2[6];
1449   const struct sockaddr_in *v4;
1450   const struct sockaddr_un *un;
1451   const struct sockaddr_in6 *v6;
1452   unsigned int off;
1453
1454   if (addr == NULL)
1455     return _("unknown address");
1456   switch (addr->sa_family)
1457   {
1458   case AF_INET:
1459     if (addrlen != sizeof (struct sockaddr_in))
1460       return "<invalid v4 address>";
1461     v4 = (const struct sockaddr_in *) addr;
1462     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1463     if (0 == ntohs (v4->sin_port))
1464       return buf;
1465     strcat (buf, ":");
1466     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
1467     strcat (buf, b2);
1468     return buf;
1469   case AF_INET6:
1470     if (addrlen != sizeof (struct sockaddr_in6))
1471       return "<invalid v4 address>";
1472     v6 = (const struct sockaddr_in6 *) addr;
1473     buf[0] = '[';
1474     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1475     if (0 == ntohs (v6->sin6_port))
1476       return &buf[1];
1477     strcat (buf, "]:");
1478     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
1479     strcat (buf, b2);
1480     return buf;
1481   case AF_UNIX:
1482     if (addrlen <= sizeof (sa_family_t))
1483       return "<unbound UNIX client>";
1484     un = (const struct sockaddr_un *) addr;
1485     off = 0;
1486     if ('\0' == un->sun_path[0])
1487       off++;
1488     memset (buf, 0, sizeof (buf));
1489     GNUNET_snprintf (buf,
1490                      sizeof (buf),
1491                      "%s%.*s",
1492                      (1 == off) ? "@" : "",
1493                      (int) (addrlen - sizeof (sa_family_t) - off),
1494                      &un->sun_path[off]);
1495     return buf;
1496   default:
1497     return _("invalid address");
1498   }
1499 }
1500
1501
1502 /**
1503  * Log error message about missing configuration option.
1504  *
1505  * @param kind log level
1506  * @param section section with missing option
1507  * @param option name of missing option
1508  */
1509 void
1510 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1511                            const char *section,
1512                            const char *option)
1513 {
1514   GNUNET_log (kind,
1515               _("Configuration fails to specify option `%s' in section `%s'!\n"),
1516               option,
1517               section);
1518 }
1519
1520
1521 /**
1522  * Log error message about invalid configuration option value.
1523  *
1524  * @param kind log level
1525  * @param section section with invalid option
1526  * @param option name of invalid option
1527  * @param required what is required that is invalid about the option
1528  */
1529 void
1530 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1531                            const char *section,
1532                            const char *option,
1533                            const char *required)
1534 {
1535   GNUNET_log (kind,
1536               _("Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1537               option, section, required);
1538 }
1539
1540
1541 /**
1542  * Initializer
1543  */
1544 void __attribute__ ((constructor))
1545 GNUNET_util_cl_init ()
1546 {
1547   GNUNET_stderr = stderr;
1548 #ifdef MINGW
1549   GNInitWinEnv (NULL);
1550 #endif
1551 #if WINDOWS
1552   if (!InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400))
1553     GNUNET_abort_ ();
1554 #endif
1555 }
1556
1557
1558 /**
1559  * Destructor
1560  */
1561 void __attribute__ ((destructor))
1562 GNUNET_util_cl_fini ()
1563 {
1564 #if WINDOWS
1565   DeleteCriticalSection (&output_message_cs);
1566 #endif
1567 #ifdef MINGW
1568   GNShutdownWinEnv ();
1569 #endif
1570 }
1571
1572 /* end of common_logging.c */