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