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