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