d564530ccf7bd9b7dd5240275805efd70794167d
[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  * Linked list of active loggers.
68  */
69 struct CustomLogger
70 {
71   /**
72    * This is a linked list.
73    */
74   struct CustomLogger *next;
75
76   /**
77    * Log function.
78    */
79   GNUNET_Logger logger;
80
81   /**
82    * Closure for logger.
83    */
84   void *logger_cls;
85 };
86
87 /**
88  * The last "bulk" error message that we have been logging.
89  * Note that this message maybe truncated to the first BULK_TRACK_SIZE
90  * characters, in which case it is NOT 0-terminated!
91  */
92 static char last_bulk[BULK_TRACK_SIZE];
93
94 /**
95  * Type of the last bulk message.
96  */
97 static enum GNUNET_ErrorType last_bulk_kind;
98
99 /**
100  * Time of the last bulk error message (0 for none)
101  */
102 static struct GNUNET_TIME_Absolute last_bulk_time;
103
104 /**
105  * Number of times that bulk message has been repeated since.
106  */
107 static unsigned int last_bulk_repeat;
108
109 /**
110  * Component when the last bulk was logged.  Will be 0-terminated.
111  */
112 static char last_bulk_comp[COMP_TRACK_SIZE + 1];
113
114 /**
115  * Running component.
116  */
117 static char *component;
118
119 /**
120  * Running component (without pid).
121  */
122 static char *component_nopid;
123
124 /**
125  * Minimum log level.
126  */
127 static enum GNUNET_ErrorType min_level;
128
129 /**
130  * Linked list of our custom loggres.
131  */
132 static struct CustomLogger *loggers;
133
134 /**
135  * Number of log calls to ignore.
136  */
137 unsigned int skip_log;
138
139 /**
140  * File descriptor to use for "stderr", or NULL for none.
141  */
142 static FILE *GNUNET_stderr;
143
144 /**
145  * Represents a single logging definition
146  */
147 struct LogDef
148 {
149   /**
150    * Component name regex
151    */
152   regex_t component_regex;
153
154   /**
155    * File name regex
156    */
157   regex_t file_regex;
158
159   /**
160    * Function name regex
161    */
162   regex_t function_regex;
163
164   /**
165    * Lowest line at which this definition matches.
166    * Defaults to 0. Must be <= to_line.
167    */
168   int from_line;
169
170   /**
171    * Highest line at which this definition matches.
172    * Defaults to INT_MAX. Must be >= from_line.
173    */
174   int to_line;
175
176   /**
177    * Maximal log level allowed for calls that match this definition.
178    * Calls with higher log level will be disabled.
179    * Must be >= 0
180    */
181   int level;
182
183   /**
184    * 1 if this definition comes from GNUNET_FORCE_LOG, which means that it
185    * overrides any configuration options. 0 otherwise.
186    */
187   int force;
188 };
189
190 /**
191  * Dynamic array of logging definitions
192  */
193 struct LogDef *logdefs = NULL;
194
195 /**
196  * Allocated size of logdefs array (in units)
197  */
198 int logdefs_size = 0;
199
200 /**
201  * The number of units used in logdefs array.
202  */
203 int logdefs_len = 0;
204
205 /**
206  * GNUNET_YES if GNUNET_LOG environment variable is already parsed.
207  */
208 int gnunet_log_parsed = GNUNET_NO;
209
210 /**
211  * GNUNET_YES if GNUNET_FORCE_LOG environment variable is already parsed.
212  */
213 int gnunet_force_log_parsed = GNUNET_NO;
214
215 /**
216  * GNUNET_YES if at least one definition with forced == 1 is available.
217  */
218 int gnunet_force_log_present = GNUNET_NO;
219
220 #ifdef WINDOWS
221 /**
222  * Contains the number of performance counts per second.
223  */
224 LARGE_INTEGER performance_frequency;
225 #endif
226
227 /**
228  * Convert a textual description of a loglevel
229  * to the respective GNUNET_GE_KIND.
230  *
231  * @param log loglevel to parse
232  * @return GNUNET_GE_INVALID if log does not parse
233  */
234 static enum GNUNET_ErrorType
235 get_type (const char *log)
236 {
237   if (log == NULL)
238     return GNUNET_ERROR_TYPE_UNSPECIFIED;
239   if (0 == strcasecmp (log, _("DEBUG")))
240     return GNUNET_ERROR_TYPE_DEBUG;
241   if (0 == strcasecmp (log, _("INFO")))
242     return GNUNET_ERROR_TYPE_INFO;
243   if (0 == strcasecmp (log, _("WARNING")))
244     return GNUNET_ERROR_TYPE_WARNING;
245   if (0 == strcasecmp (log, _("ERROR")))
246     return GNUNET_ERROR_TYPE_ERROR;
247   if (0 == strcasecmp (log, _("NONE")))
248     return GNUNET_ERROR_TYPE_NONE;
249   return GNUNET_ERROR_TYPE_INVALID;
250 }
251
252 #if !defined(GNUNET_CULL_LOGGING)
253 /**
254  * Utility function - reallocates logdefs array to be twice as large.
255  */
256 static void
257 resize_logdefs ()
258 {
259   logdefs_size = (logdefs_size + 1) * 2;
260   logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef));
261 }
262
263 /**
264  * Utility function - adds a parsed definition to logdefs array.
265  *
266  * @param component see struct LogDef, can't be NULL
267  * @param file see struct LogDef, can't be NULL
268  * @param function see struct LogDef, can't be NULL
269  * @param from_line see struct LogDef
270  * @param to_line see struct LogDef
271  * @param level see struct LogDef, must be >= 0
272  * @param force see struct LogDef
273  * @return 0 on success, regex-specific error otherwise
274  */
275 static int
276 add_definition (char *component, char *file, char *function, int from_line,
277                 int to_line, int level, int force)
278 {
279   struct LogDef n;
280   int r;
281   if (logdefs_size == logdefs_len)
282     resize_logdefs ();
283   memset (&n, 0, sizeof (n));
284   if (strlen (component) == 0)
285     component = (char *) ".*";
286   r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB);
287   if (r != 0)
288     {
289       return r;
290     }
291   if (strlen (file) == 0)
292     file = (char *) ".*";
293   r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB);
294   if (r != 0)
295     {
296       regfree (&n.component_regex);
297       return r;
298     }
299   if ( (NULL == function) ||
300        (strlen (function) == 0))
301     function = (char *) ".*";
302   r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB);
303   if (r != 0)
304     {
305       regfree (&n.component_regex);
306       regfree (&n.file_regex);
307       return r;
308     }
309   n.from_line = from_line;
310   n.to_line = to_line;
311   n.level = level;
312   n.force = force;
313   logdefs[logdefs_len++] = n;
314   return 0;
315 }
316
317
318 /**
319  * Decides whether a particular logging call should or should not be allowed
320  * to be made. Used internally by GNUNET_log*()
321  *
322  * @param caller_level loglevel the caller wants to use
323  * @param comp component name the caller uses (NULL means that global
324  *   component name is used)
325  * @param file file name containing the logging call, usually __FILE__
326  * @param function function which tries to make a logging call,
327  *   usually __FUNCTION__
328  * @param line line at which the call is made, usually __LINE__
329  * @return 0 to disallow the call, 1 to allow it
330  */
331 int
332 GNUNET_get_log_call_status (int caller_level, const char *comp,
333                             const char *file, const char *function, int line)
334 {
335   struct LogDef *ld;
336   int i;
337   int force_only;
338
339   if (comp == NULL)
340     /* Use default component */
341     comp = component_nopid;
342
343   /* We have no definitions to override globally configured log level,
344    * so just use it right away.
345    */
346   if (min_level >= 0 && gnunet_force_log_present == GNUNET_NO)
347     return caller_level <= min_level;
348
349   /* Only look for forced definitions? */
350   force_only = min_level >= 0;
351   for (i = 0; i < logdefs_len; i++)
352   {
353       ld = &logdefs[i];
354       if ((!force_only || ld->force) &&
355           (line >= ld->from_line && line <= ld->to_line) &&
356           (regexec (&ld->component_regex, comp, 0, NULL, 0) == 0) &&
357           (regexec (&ld->file_regex, file, 0, NULL, 0) == 0) &&
358           (regexec (&ld->function_regex, function, 0, NULL, 0) == 0))
359         {
360           /* We're finished */
361           return caller_level <= ld->level;
362         }
363   }
364   /* No matches - use global level, if defined */
365   if (min_level >= 0)
366     return caller_level <= min_level;
367   /* All programs/services previously defaulted to WARNING.
368    * Now WE default to WARNING, and THEY default to NULL.
369    */
370   return caller_level <= GNUNET_ERROR_TYPE_WARNING;
371 }
372
373
374 /**
375  * Utility function - parses a definition
376  *
377  * Definition format:
378  * component;file;function;from_line-to_line;level[/component...]
379  * All entries are mandatory, but may be empty.
380  * Empty entries for component, file and function are treated as
381  * "matches anything".
382  * Empty line entry is treated as "from 0 to INT_MAX"
383  * Line entry with only one line is treated as "this line only"
384  * Entry for level MUST NOT be empty.
385  * Entries for component, file and function that consist of a
386  * single character "*" are treated (at the moment) the same way
387  * empty entries are treated (wildcard matching is not implemented (yet?)).
388  * file entry is matched to the end of __FILE__. That is, it might be
389  * a base name, or a base name with leading directory names (some compilers
390  * define __FILE__ to absolute file path).
391  *
392  * @param constname name of the environment variable from which to get the
393  *   string to be parsed
394  * @param force 1 if definitions found in @constname are to be forced
395  * @return number of added definitions
396  */
397 static int
398 parse_definitions (const char *constname, int force)
399 {
400   char *def;
401   const char *tmp;
402   char *comp = NULL;
403   char *file = NULL;
404   char *function = NULL;
405   char *p;
406   char *start;
407   char *t;
408   short state;
409   int level;
410   int from_line, to_line;
411   int counter = 0;
412   int keep_looking = 1;
413
414   tmp = getenv (constname);
415   if (tmp == NULL)
416     return 0;
417   def = GNUNET_strdup (tmp);
418   level = -1;
419   from_line = 0;
420   to_line = INT_MAX;
421   for (p = def, state = 0, start = def; keep_looking; p++)
422   {
423       switch (p[0])
424         {
425         case ';':               /* found a field separator */
426           p[0] = '\0';
427           switch (state)
428             {
429             case 0:             /* within a component name */
430               comp = start;
431               break;
432             case 1:             /* within a file name */
433               file = start;
434               break;
435             case 2:             /* within a function name */
436               /* after a file name there must be a function name */
437               function = start;
438               break;
439             case 3:             /* within a from-to line range */
440               if (strlen (start) > 0)
441                 {
442                   errno = 0;
443                   from_line = strtol (start, &t, 10);
444                   if (errno != 0 || from_line < 0)
445                     {
446                       free (def);
447                       return counter;
448                     }
449                   if (t < p && t[0] == '-')
450                     {
451                       errno = 0;
452                       start = t + 1;
453                       to_line = strtol (start, &t, 10);
454                       if (errno != 0 || to_line < 0 || t != p)
455                         {
456                           free (def);
457                           return counter;
458                         }
459                     }
460                   else          /* one number means "match this line only" */
461                     to_line = from_line;
462                 }
463               else              /* default to 0-max */
464                 {
465                   from_line = 0;
466                   to_line = INT_MAX;
467                 }
468               break;
469             }
470           start = p + 1;
471           state += 1;
472           break;
473         case '\0':              /* found EOL */
474           keep_looking = 0;
475           /* fall through to '/' */
476         case '/':               /* found a definition separator */
477           switch (state)
478             {
479             case 4:             /* within a log level */
480               p[0] = '\0';
481               state = 0;
482               level = get_type ((const char *) start);
483               if (level == GNUNET_ERROR_TYPE_INVALID
484                   || level == GNUNET_ERROR_TYPE_UNSPECIFIED
485                   || 0 != add_definition (comp, file, function, from_line,
486                                           to_line, level, force))
487                 {
488                   free (def);
489                   return counter;
490                 }
491               counter += 1;
492               start = p + 1;
493               break;
494             default:
495               break;
496             }
497         default:
498           break;
499         }
500   }
501   free (def);
502   return counter;
503 }
504
505 /**
506  * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
507  */
508 static void
509 parse_all_definitions ()
510 {
511   if (gnunet_log_parsed == GNUNET_NO)
512     parse_definitions ("GNUNET_LOG", 0);
513   gnunet_log_parsed = GNUNET_YES;
514   if (gnunet_force_log_parsed == GNUNET_NO)
515     gnunet_force_log_present =
516         parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
517   gnunet_force_log_parsed = GNUNET_YES;
518 }
519 #endif
520 /**
521  * Setup logging.
522  *
523  * @param comp default component to use
524  * @param loglevel what types of messages should be logged
525  * @param logfile which file to write log messages to (can be NULL)
526  * @return GNUNET_OK on success
527  */
528 int
529 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
530 {
531   FILE *altlog;
532   int dirwarn;
533   char *fn;
534   const char *env_logfile = NULL;
535
536   min_level = get_type (loglevel);
537 #if !defined(GNUNET_CULL_LOGGING)
538   parse_all_definitions ();
539 #endif
540 #ifdef WINDOWS
541   QueryPerformanceFrequency (&performance_frequency);
542 #endif
543   GNUNET_free_non_null (component);
544   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
545   GNUNET_free_non_null (component_nopid);
546   component_nopid = GNUNET_strdup (comp);
547
548   env_logfile = getenv ("GNUNET_FORCE_LOGFILE");
549   if (env_logfile != NULL)
550     logfile = env_logfile;
551
552   if (logfile == NULL)
553     return GNUNET_OK;
554   fn = GNUNET_STRINGS_filename_expand (logfile);
555   if (NULL == fn)
556     return GNUNET_SYSERR;
557   dirwarn = (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn));
558   altlog = FOPEN (fn, "a");
559   if (altlog == NULL)
560   {
561     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", fn);
562     if (dirwarn)
563       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
564                   _("Failed to create or access directory for log file `%s'\n"),
565                   fn);
566     GNUNET_free (fn);
567     return GNUNET_SYSERR;
568   }
569   GNUNET_free (fn);
570   if (GNUNET_stderr != NULL)
571     fclose (GNUNET_stderr);
572   GNUNET_stderr = altlog;
573   return GNUNET_OK;
574 }
575
576 /**
577  * Add a custom logger.
578  *
579  * @param logger log function
580  * @param logger_cls closure for logger
581  */
582 void
583 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
584 {
585   struct CustomLogger *entry;
586
587   entry = GNUNET_malloc (sizeof (struct CustomLogger));
588   entry->logger = logger;
589   entry->logger_cls = logger_cls;
590   entry->next = loggers;
591   loggers = entry;
592 }
593
594 /**
595  * Remove a custom logger.
596  *
597  * @param logger log function
598  * @param logger_cls closure for logger
599  */
600 void
601 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
602 {
603   struct CustomLogger *pos;
604   struct CustomLogger *prev;
605
606   prev = NULL;
607   pos = loggers;
608   while ((pos != NULL) &&
609          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
610   {
611     prev = pos;
612     pos = pos->next;
613   }
614   GNUNET_assert (pos != NULL);
615   if (prev == NULL)
616     loggers = pos->next;
617   else
618     prev->next = pos->next;
619   GNUNET_free (pos);
620 }
621
622
623 /**
624  * Actually output the log message.
625  *
626  * @param kind how severe was the issue
627  * @param comp component responsible
628  * @param datestr current date/time
629  * @param msg the actual message
630  */
631 static void
632 output_message (enum GNUNET_ErrorType kind, const char *comp,
633                 const char *datestr, const char *msg)
634 {
635   struct CustomLogger *pos;
636
637   if (GNUNET_stderr != NULL)
638   {
639     fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp,
640              GNUNET_error_type_to_string (kind), msg);
641     fflush (GNUNET_stderr);
642   }
643   pos = loggers;
644   while (pos != NULL)
645   {
646     pos->logger (pos->logger_cls, kind, comp, datestr, msg);
647     pos = pos->next;
648   }
649 }
650
651
652 /**
653  * Flush an existing bulk report to the output.
654  *
655  * @param datestr our current timestamp
656  */
657 static void
658 flush_bulk (const char *datestr)
659 {
660   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
661   int rev;
662   char *last;
663   char *ft;
664
665   if ((last_bulk_time.abs_value == 0) || (last_bulk_repeat == 0))
666     return;
667   rev = 0;
668   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
669   if (last == NULL)
670     last = &last_bulk[BULK_TRACK_SIZE - 1];
671   else if (last != last_bulk)
672     last--;
673   if (last[0] == '\n')
674   {
675     rev = 1;
676     last[0] = '\0';
677   }
678   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
679                                                (last_bulk_time));
680   snprintf (msg, sizeof (msg),
681             _("Message `%.*s' repeated %u times in the last %s\n"),
682             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
683   GNUNET_free (ft);
684   if (rev == 1)
685     last[0] = '\n';
686   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
687   last_bulk_time = GNUNET_TIME_absolute_get ();
688   last_bulk_repeat = 0;
689 }
690
691
692 /**
693  * Ignore the next n calls to the log function.
694  *
695  * @param n number of log calls to ignore
696  * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
697  */
698 void
699 GNUNET_log_skip (unsigned int n, int check_reset)
700 {
701   if (n == 0)
702   {
703     int ok;
704
705     ok = (0 == skip_log);
706     skip_log = 0;
707     if (check_reset)
708       GNUNET_assert (ok);
709   }
710   else
711     skip_log += n;
712 }
713
714
715 /**
716  * Output a log message using the default mechanism.
717  *
718  * @param kind how severe was the issue
719  * @param comp component responsible
720  * @param message the actual message
721  * @param va arguments to the format string "message"
722  */
723 static void
724 mylog (enum GNUNET_ErrorType kind, const char *comp, const char *message,
725        va_list va)
726 {
727   char date[DATE_STR_SIZE];
728   char date2[DATE_STR_SIZE];
729   time_t timetmp;
730   struct timeval timeofday;
731   struct tm *tmptr;
732   size_t size;
733   va_list vacp;
734
735   va_copy (vacp, va);
736   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
737   GNUNET_assert (0 != size);
738   va_end (vacp);
739   {
740     char buf[size];
741
742     VSNPRINTF (buf, size, message, va);
743     time (&timetmp);
744     memset (date, 0, DATE_STR_SIZE);
745     tmptr = localtime (&timetmp);
746     gettimeofday (&timeofday, NULL);
747     if (NULL != tmptr)
748     {
749 #ifdef WINDOWS
750       LARGE_INTEGER pc;
751
752       pc.QuadPart = 0;
753       QueryPerformanceCounter (&pc);
754       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
755       snprintf (date, sizeof (date), date2,
756                 (long long) (pc.QuadPart /
757                              (performance_frequency.QuadPart / 1000)));
758 #else
759       strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
760       snprintf (date, sizeof (date), date2, timeofday.tv_usec);
761 #endif
762     }
763     else
764       strcpy (date, "localtime error");
765     if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
766         (last_bulk_time.abs_value != 0) &&
767         (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
768     {
769       last_bulk_repeat++;
770       if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value >
771            BULK_DELAY_THRESHOLD) || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
772         flush_bulk (date);
773       return;
774     }
775     flush_bulk (date);
776     strncpy (last_bulk, buf, sizeof (last_bulk));
777     last_bulk_repeat = 0;
778     last_bulk_kind = kind;
779     last_bulk_time = GNUNET_TIME_absolute_get ();
780     strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
781     output_message (kind, comp, date, buf);
782   }
783 }
784
785
786 /**
787  * Main log function.
788  *
789  * @param kind how serious is the error?
790  * @param message what is the message (format string)
791  * @param ... arguments for format string
792  */
793 void
794 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
795 {
796   va_list va;
797
798   va_start (va, message);
799   mylog (kind, component, message, va);
800   va_end (va);
801 }
802
803
804 /**
805  * Log function that specifies an alternative component.
806  * This function should be used by plugins.
807  *
808  * @param kind how serious is the error?
809  * @param comp component responsible for generating the message
810  * @param message what is the message (format string)
811  * @param ... arguments for format string
812  */
813 void
814 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
815                          const char *message, ...)
816 {
817   va_list va;
818   char comp_w_pid[128];
819
820   if (comp == NULL)
821     comp = component_nopid;
822
823   va_start (va, message);
824   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
825   mylog (kind, comp_w_pid, message, va);
826   va_end (va);
827 }
828
829
830 /**
831  * Convert error type to string.
832  *
833  * @param kind type to convert
834  * @return string corresponding to the type
835  */
836 const char *
837 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
838 {
839   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
840     return _("ERROR");
841   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
842     return _("WARNING");
843   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
844     return _("INFO");
845   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
846     return _("DEBUG");
847   if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
848     return _("NONE");
849   return _("INVALID");
850 }
851
852
853 /**
854  * Convert a hash to a string (for printing debug messages).
855  * This is one of the very few calls in the entire API that is
856  * NOT reentrant!
857  *
858  * @param hc the hash code
859  * @return string form; will be overwritten by next call to GNUNET_h2s.
860  */
861 const char *
862 GNUNET_h2s (const GNUNET_HashCode * hc)
863 {
864   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
865
866   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
867   ret.encoding[8] = '\0';
868   return (const char *) ret.encoding;
869 }
870
871 /**
872  * Convert a hash to a string (for printing debug messages).
873  * This is one of the very few calls in the entire API that is
874  * NOT reentrant!
875  *
876  * @param hc the hash code
877  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
878  */
879 const char *
880 GNUNET_h2s_full (const GNUNET_HashCode * hc)
881 {
882   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
883
884   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
885   ret.encoding[sizeof (ret) - 1] = '\0';
886   return (const char *) ret.encoding;
887 }
888
889 /**
890  * Convert a peer identity to a string (for printing debug messages).
891  * This is one of the very few calls in the entire API that is
892  * NOT reentrant!
893  *
894  * @param pid the peer identity
895  * @return string form of the pid; will be overwritten by next
896  *         call to GNUNET_i2s.
897  */
898 const char *
899 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
900 {
901   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
902
903   GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
904   ret.encoding[4] = '\0';
905   return (const char *) ret.encoding;
906 }
907
908
909
910 /**
911  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
912  * (for printing debug messages).  This is one of the very few calls
913  * in the entire API that is NOT reentrant!
914  *
915  * @param addr the address
916  * @param addrlen the length of the address
917  * @return nicely formatted string for the address
918  *  will be overwritten by next call to GNUNET_a2s.
919  */
920 const char *
921 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
922 {
923   static char buf[INET6_ADDRSTRLEN + 8];
924   static char b2[6];
925   const struct sockaddr_in *v4;
926   const struct sockaddr_un *un;
927   const struct sockaddr_in6 *v6;
928   unsigned int off;
929
930   if (addr == NULL)
931     return _("unknown address");
932   switch (addr->sa_family)
933   {
934   case AF_INET:
935     if (addrlen != sizeof (struct sockaddr_in))
936       return "<invalid v4 address>";
937     v4 = (const struct sockaddr_in *) addr;
938     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
939     if (0 == ntohs (v4->sin_port))
940       return buf;
941     strcat (buf, ":");
942     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
943     strcat (buf, b2);
944     return buf;
945   case AF_INET6:
946     if (addrlen != sizeof (struct sockaddr_in6))
947       return "<invalid v4 address>";
948     v6 = (const struct sockaddr_in6 *) addr;
949     buf[0] = '[';
950     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
951     if (0 == ntohs (v6->sin6_port))
952       return &buf[1];
953     strcat (buf, "]:");
954     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
955     strcat (buf, b2);
956     return buf;
957   case AF_UNIX:
958     if (addrlen <= sizeof (sa_family_t))
959       return "<unbound UNIX client>";
960     un = (const struct sockaddr_un *) addr;
961     off = 0;
962     if (un->sun_path[0] == '\0')
963       off++;
964     snprintf (buf, sizeof (buf), "%s%.*s", (off == 1) ? "@" : "",
965               (int) (addrlen - sizeof (sa_family_t) - 1 - off),
966               &un->sun_path[off]);
967     return buf;
968   default:
969     return _("invalid address");
970   }
971 }
972
973
974 /**
975  * Initializer
976  */
977 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
978 {
979   GNUNET_stderr = stderr;
980 #ifdef MINGW
981   GNInitWinEnv (NULL);
982 #endif
983 }
984
985
986 /**
987  * Destructor
988  */
989 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
990 {
991 #ifdef MINGW
992   GNShutdownWinEnv ();
993 #endif
994 }
995
996 /* end of common_logging.c */