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