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