indentation
[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  * Minimum log level.
119  */
120 static enum GNUNET_ErrorType min_level;
121
122 /**
123  * Linked list of our custom loggres.
124  */
125 static struct CustomLogger *loggers;
126
127 /**
128  * Number of log calls to ignore.
129  */
130 static unsigned int skip_log;
131
132 /**
133  * File descriptor to use for "stderr", or NULL for none.
134  */
135 static FILE *GNUNET_stderr;
136
137 #ifdef WINDOWS
138 /**
139  * Contains the number of performance counts per second.
140  */
141 LARGE_INTEGER performance_frequency;
142 #endif
143
144 /**
145  * Convert a textual description of a loglevel
146  * to the respective GNUNET_GE_KIND.
147  *
148  * @param log loglevel to parse
149  * @return GNUNET_GE_INVALID if log does not parse
150  */
151 static enum GNUNET_ErrorType
152 get_type (const char *log)
153 {
154   if (0 == strcasecmp (log, _("DEBUG")))
155     return GNUNET_ERROR_TYPE_DEBUG;
156   if (0 == strcasecmp (log, _("INFO")))
157     return GNUNET_ERROR_TYPE_INFO;
158   if (0 == strcasecmp (log, _("WARNING")))
159     return GNUNET_ERROR_TYPE_WARNING;
160   if (0 == strcasecmp (log, _("ERROR")))
161     return GNUNET_ERROR_TYPE_ERROR;
162   if (0 == strcasecmp (log, _("NONE")))
163     return GNUNET_ERROR_TYPE_NONE;
164   return GNUNET_ERROR_TYPE_INVALID;
165 }
166
167
168 /**
169  * Setup logging.
170  *
171  * @param comp default component to use
172  * @param loglevel what types of messages should be logged
173  * @param logfile which file to write log messages to (can be NULL)
174  * @return GNUNET_OK on success
175  */
176 int
177 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
178 {
179   FILE *altlog;
180   int dirwarn;
181   char *fn;
182   const char *env_loglevel;
183   int env_minlevel = 0;
184   int env_min_force_level = 100000;
185
186 #ifdef WINDOWS
187   QueryPerformanceFrequency (&performance_frequency);
188 #endif
189   GNUNET_free_non_null (component);
190   GNUNET_asprintf (&component, "%s-%d", comp, getpid ());
191   env_loglevel = getenv ("GNUNET_LOGLEVEL");
192   if (env_loglevel != NULL)
193     env_minlevel = get_type (env_loglevel);
194   env_loglevel = getenv ("GNUNET_FORCE_LOGLEVEL");
195   if (env_loglevel != NULL)
196     env_min_force_level = get_type (env_loglevel);
197   min_level = get_type (loglevel);
198   if (env_minlevel > min_level)
199     min_level = env_minlevel;
200   if (env_min_force_level < min_level)
201     min_level = env_min_force_level;
202   if (logfile == NULL)
203     return GNUNET_OK;
204   fn = GNUNET_STRINGS_filename_expand (logfile);
205   if (NULL == fn)
206     return GNUNET_SYSERR;
207   dirwarn = (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn));
208   altlog = FOPEN (fn, "a");
209   if (altlog == NULL)
210   {
211     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", fn);
212     if (dirwarn)
213       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
214                   _("Failed to create or access directory for log file `%s'\n"),
215                   fn);
216     GNUNET_free (fn);
217     return GNUNET_SYSERR;
218   }
219   GNUNET_free (fn);
220   if (GNUNET_stderr != NULL)
221     fclose (GNUNET_stderr);
222   GNUNET_stderr = altlog;
223   return GNUNET_OK;
224 }
225
226 /**
227  * Add a custom logger.
228  *
229  * @param logger log function
230  * @param logger_cls closure for logger
231  */
232 void
233 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
234 {
235   struct CustomLogger *entry;
236
237   entry = GNUNET_malloc (sizeof (struct CustomLogger));
238   entry->logger = logger;
239   entry->logger_cls = logger_cls;
240   entry->next = loggers;
241   loggers = entry;
242 }
243
244 /**
245  * Remove a custom logger.
246  *
247  * @param logger log function
248  * @param logger_cls closure for logger
249  */
250 void
251 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
252 {
253   struct CustomLogger *pos;
254   struct CustomLogger *prev;
255
256   prev = NULL;
257   pos = loggers;
258   while ((pos != NULL) &&
259          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
260   {
261     prev = pos;
262     pos = pos->next;
263   }
264   GNUNET_assert (pos != NULL);
265   if (prev == NULL)
266     loggers = pos->next;
267   else
268     prev->next = pos->next;
269   GNUNET_free (pos);
270 }
271
272
273 /**
274  * Actually output the log message.
275  *
276  * @param kind how severe was the issue
277  * @param comp component responsible
278  * @param datestr current date/time
279  * @param msg the actual message
280  */
281 static void
282 output_message (enum GNUNET_ErrorType kind,
283                 const char *comp, const char *datestr, const char *msg)
284 {
285   struct CustomLogger *pos;
286
287   if (GNUNET_stderr != NULL)
288   {
289     fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp,
290              GNUNET_error_type_to_string (kind), msg);
291     fflush (GNUNET_stderr);
292   }
293   pos = loggers;
294   while (pos != NULL)
295   {
296     pos->logger (pos->logger_cls, kind, comp, datestr, msg);
297     pos = pos->next;
298   }
299 }
300
301
302 /**
303  * Flush an existing bulk report to the output.
304  *
305  * @param datestr our current timestamp
306  */
307 static void
308 flush_bulk (const char *datestr)
309 {
310   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
311   int rev;
312   char *last;
313   char *ft;
314
315   if ((last_bulk_time.abs_value == 0) || (last_bulk_repeat == 0))
316     return;
317   rev = 0;
318   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
319   if (last == NULL)
320     last = &last_bulk[BULK_TRACK_SIZE - 1];
321   else if (last != last_bulk)
322     last--;
323   if (last[0] == '\n')
324   {
325     rev = 1;
326     last[0] = '\0';
327   }
328   ft = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
329                                                (last_bulk_time));
330   snprintf (msg, sizeof (msg),
331             _("Message `%.*s' repeated %u times in the last %s\n"),
332             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
333   GNUNET_free (ft);
334   if (rev == 1)
335     last[0] = '\n';
336   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
337   last_bulk_time = GNUNET_TIME_absolute_get ();
338   last_bulk_repeat = 0;
339 }
340
341
342 /**
343  * Ignore the next n calls to the log function.
344  *
345  * @param n number of log calls to ignore
346  * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
347  */
348 void
349 GNUNET_log_skip (unsigned int n, int check_reset)
350 {
351   if (n == 0)
352   {
353     int ok;
354
355     ok = (0 == skip_log);
356     skip_log = 0;
357     if (check_reset)
358       GNUNET_assert (ok);
359   }
360   else
361     skip_log += n;
362 }
363
364
365 /**
366  * Output a log message using the default mechanism.
367  *
368  * @param kind how severe was the issue
369  * @param comp component responsible
370  * @param message the actual message
371  * @param va arguments to the format string "message"
372  */
373 static void
374 mylog (enum GNUNET_ErrorType kind,
375        const char *comp, const char *message, va_list va)
376 {
377   char date[DATE_STR_SIZE];
378   char date2[DATE_STR_SIZE];
379   time_t timetmp;
380   struct timeval timeofday;
381   struct tm *tmptr;
382   size_t size;
383   char *buf;
384   va_list vacp;
385
386   if (skip_log > 0)
387   {
388     skip_log--;
389     return;
390   }
391   if ((kind & (~GNUNET_ERROR_TYPE_BULK)) > min_level)
392     return;
393   va_copy (vacp, va);
394   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
395   va_end (vacp);
396   buf = malloc (size);
397   if (buf == NULL)
398     return;                     /* oops */
399   VSNPRINTF (buf, size, message, va);
400   time (&timetmp);
401   memset (date, 0, DATE_STR_SIZE);
402   tmptr = localtime (&timetmp);
403   gettimeofday (&timeofday, NULL);
404   if (NULL != tmptr)
405   {
406 #ifdef WINDOWS
407     LARGE_INTEGER pc;
408
409     pc.QuadPart = 0;
410     QueryPerformanceCounter (&pc);
411     strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr);
412     snprintf (date, sizeof (date), date2,
413               (long long) (pc.QuadPart /
414                            (performance_frequency.QuadPart / 1000)));
415 #else
416     strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr);
417     snprintf (date, sizeof (date), date2, timeofday.tv_usec);
418 #endif
419   }
420   else
421     strcpy (date, "localtime error");
422   if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
423       (last_bulk_time.abs_value != 0) &&
424       (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
425   {
426     last_bulk_repeat++;
427     if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value >
428          BULK_DELAY_THRESHOLD) || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
429       flush_bulk (date);
430     free (buf);
431     return;
432   }
433   flush_bulk (date);
434   strncpy (last_bulk, buf, sizeof (last_bulk));
435   last_bulk_repeat = 0;
436   last_bulk_kind = kind;
437   last_bulk_time = GNUNET_TIME_absolute_get ();
438   strncpy (last_bulk_comp, comp, COMP_TRACK_SIZE);
439   output_message (kind, comp, date, buf);
440   free (buf);
441 }
442
443
444 /**
445  * Main log function.
446  *
447  * @param kind how serious is the error?
448  * @param message what is the message (format string)
449  * @param ... arguments for format string
450  */
451 void
452 GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...)
453 {
454   va_list va;
455
456   va_start (va, message);
457   mylog (kind, component, message, va);
458   va_end (va);
459 }
460
461
462 /**
463  * Log function that specifies an alternative component.
464  * This function should be used by plugins.
465  *
466  * @param kind how serious is the error?
467  * @param comp component responsible for generating the message
468  * @param message what is the message (format string)
469  * @param ... arguments for format string
470  */
471 void
472 GNUNET_log_from (enum GNUNET_ErrorType kind,
473                  const char *comp, const char *message, ...)
474 {
475   va_list va;
476   char comp_w_pid[128];
477
478   va_start (va, message);
479   GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ());
480   mylog (kind, comp_w_pid, message, va);
481   va_end (va);
482 }
483
484
485 /**
486  * Convert error type to string.
487  *
488  * @param kind type to convert
489  * @return string corresponding to the type
490  */
491 const char *
492 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
493 {
494   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
495     return _("ERROR");
496   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
497     return _("WARNING");
498   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
499     return _("INFO");
500   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
501     return _("DEBUG");
502   return _("INVALID");
503 }
504
505
506 /**
507  * Convert a hash to a string (for printing debug messages).
508  * This is one of the very few calls in the entire API that is
509  * NOT reentrant!
510  *
511  * @param hc the hash code
512  * @return string form; will be overwritten by next call to GNUNET_h2s.
513  */
514 const char *
515 GNUNET_h2s (const GNUNET_HashCode * hc)
516 {
517   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
518
519   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
520   ret.encoding[8] = '\0';
521   return (const char *) ret.encoding;
522 }
523
524 /**
525  * Convert a hash to a string (for printing debug messages).
526  * This is one of the very few calls in the entire API that is
527  * NOT reentrant!
528  *
529  * @param hc the hash code
530  * @return string form; will be overwritten by next call to GNUNET_h2s_full.
531  */
532 const char *
533 GNUNET_h2s_full (const GNUNET_HashCode * hc)
534 {
535   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
536
537   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
538   ret.encoding[sizeof (ret) - 1] = '\0';
539   return (const char *) ret.encoding;
540 }
541
542 /**
543  * Convert a peer identity to a string (for printing debug messages).
544  * This is one of the very few calls in the entire API that is
545  * NOT reentrant!
546  *
547  * @param pid the peer identity
548  * @return string form of the pid; will be overwritten by next
549  *         call to GNUNET_i2s.
550  */
551 const char *
552 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
553 {
554   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
555
556   GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
557   ret.encoding[4] = '\0';
558   return (const char *) ret.encoding;
559 }
560
561
562
563 /**
564  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
565  * (for printing debug messages).  This is one of the very few calls
566  * in the entire API that is NOT reentrant!
567  *
568  * @param addr the address
569  * @param addrlen the length of the address
570  * @return nicely formatted string for the address
571  *  will be overwritten by next call to GNUNET_a2s.
572  */
573 const char *
574 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
575 {
576   static char buf[INET6_ADDRSTRLEN + 8];
577   static char b2[6];
578   const struct sockaddr_in *v4;
579   const struct sockaddr_un *un;
580   const struct sockaddr_in6 *v6;
581   unsigned int off;
582
583   if (addr == NULL)
584     return _("unknown address");
585   switch (addr->sa_family)
586   {
587   case AF_INET:
588     if (addrlen != sizeof (struct sockaddr_in))
589       return "<invalid v4 address>";
590     v4 = (const struct sockaddr_in *) addr;
591     inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
592     if (0 == ntohs (v4->sin_port))
593       return buf;
594     strcat (buf, ":");
595     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port));
596     strcat (buf, b2);
597     return buf;
598   case AF_INET6:
599     if (addrlen != sizeof (struct sockaddr_in6))
600       return "<invalid v4 address>";
601     v6 = (const struct sockaddr_in6 *) addr;
602     buf[0] = '[';
603     inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
604     if (0 == ntohs (v6->sin6_port))
605       return &buf[1];
606     strcat (buf, "]:");
607     GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port));
608     strcat (buf, b2);
609     return buf;
610   case AF_UNIX:
611     if (addrlen <= sizeof (sa_family_t))
612       return "<unbound UNIX client>";
613     un = (const struct sockaddr_un *) addr;
614     off = 0;
615     if (un->sun_path[0] == '\0')
616       off++;
617     snprintf (buf,
618               sizeof (buf),
619               "%s%.*s",
620               (off == 1) ? "@" : "",
621               (int) (addrlen - sizeof (sa_family_t) - 1 - off),
622               &un->sun_path[off]);
623     return buf;
624   default:
625     return _("invalid address");
626   }
627 }
628
629
630 /**
631  * Initializer
632  */
633 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
634 {
635   GNUNET_stderr = stderr;
636 #ifdef MINGW
637   GNInitWinEnv (NULL);
638 #endif
639 }
640
641
642 /**
643  * Destructor
644  */
645 void __attribute__ ((destructor)) GNUNET_util_cl_fini ()
646 {
647 #ifdef MINGW
648   GNShutdownWinEnv ();
649 #endif
650 }
651
652 /* end of common_logging.c */