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