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