better defaults, nicer error msgs:
[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 can a date/time string
54  * be at most?
55  */
56 #define DATE_STR_SIZE 64
57
58 /**
59  * Linked list of active loggers.
60  */
61 struct CustomLogger
62 {
63   /**
64    * This is a linked list.
65    */
66   struct CustomLogger *next;
67
68   /**
69    * Log function.
70    */
71   GNUNET_Logger logger;
72
73   /**
74    * Closure for logger.
75    */
76   void *logger_cls;
77 };
78
79 /**
80  * The last "bulk" error message that we have been logging.
81  * Note that this message maybe truncated to the first BULK_TRACK_SIZE
82  * characters, in which case it is NOT 0-terminated!
83  */
84 static char last_bulk[BULK_TRACK_SIZE];
85
86 /**
87  * Type of the last bulk message.
88  */
89 static enum GNUNET_ErrorType last_bulk_kind;
90
91 /**
92  * Time of the last bulk error message (0 for none)
93  */
94 static struct GNUNET_TIME_Absolute last_bulk_time;
95
96 /**
97  * Number of times that bulk message has been repeated since.
98  */
99 static unsigned int last_bulk_repeat;
100
101 /**
102  * Component when the last bulk was logged.
103  */
104 static const char *last_bulk_comp;
105
106 /**
107  * Running component.
108  */
109 static char *component;
110
111 /**
112  * Minimum log level.
113  */
114 static enum GNUNET_ErrorType min_level;
115
116 /**
117  * Linked list of our custom loggres.
118  */
119 static struct CustomLogger *loggers;
120
121 /**
122  * Number of log calls to ignore.
123  */
124 static unsigned int skip_log;
125
126 /**
127  * File descriptor to use for "stderr", or NULL for none.
128  */
129 static FILE *GNUNET_stderr;
130
131 /**
132  * Convert a textual description of a loglevel
133  * to the respective GNUNET_GE_KIND.
134  *
135  * @param log loglevel to parse
136  * @return GNUNET_GE_INVALID if log does not parse
137  */
138 static enum GNUNET_ErrorType
139 get_type (const char *log)
140 {
141   if (0 == strcasecmp (log, _("DEBUG")))
142     return GNUNET_ERROR_TYPE_DEBUG;
143   if (0 == strcasecmp (log, _("INFO")))
144     return GNUNET_ERROR_TYPE_INFO;
145   if (0 == strcasecmp (log, _("WARNING")))
146     return GNUNET_ERROR_TYPE_WARNING;
147   if (0 == strcasecmp (log, _("ERROR")))
148     return GNUNET_ERROR_TYPE_ERROR;
149   return GNUNET_ERROR_TYPE_INVALID;
150 }
151
152
153 /**
154  * Setup logging.
155  *
156  * @param comp default component to use
157  * @param loglevel what types of messages should be logged
158  * @param logfile which file to write log messages to (can be NULL)
159  * @return GNUNET_OK on success
160  */
161 int
162 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
163 {
164   FILE *altlog;
165   int dirwarn;
166
167   GNUNET_free_non_null (component);
168   GNUNET_asprintf (&component,
169                    "%s-%d",
170                    comp,
171                    getpid());
172   min_level = get_type (loglevel);
173   if (logfile == NULL)
174     return GNUNET_OK;
175   dirwarn = (GNUNET_OK !=  GNUNET_DISK_directory_create_for_file (logfile));
176   altlog = FOPEN (logfile, "a");
177   if (altlog == NULL)
178     {
179       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", logfile);
180       if (dirwarn) 
181         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
182                     _("Failed to create or access directory for log file `%s'\n"), 
183                     logfile);
184       return GNUNET_SYSERR;
185     }
186   if (GNUNET_stderr != NULL)
187     fclose (GNUNET_stderr);
188   GNUNET_stderr = altlog;
189   return GNUNET_OK;
190 }
191
192 /**
193  * Add a custom logger.
194  *
195  * @param logger log function
196  * @param logger_cls closure for logger
197  */
198 void
199 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
200 {
201   struct CustomLogger *entry;
202
203   entry = GNUNET_malloc (sizeof (struct CustomLogger));
204   entry->logger = logger;
205   entry->logger_cls = logger_cls;
206   entry->next = loggers;
207   loggers = entry;
208 }
209
210 /**
211  * Remove a custom logger.
212  *
213  * @param logger log function
214  * @param logger_cls closure for logger
215  */
216 void
217 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
218 {
219   struct CustomLogger *pos;
220   struct CustomLogger *prev;
221
222   prev = NULL;
223   pos = loggers;
224   while ((pos != NULL) &&
225          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
226     {
227       prev = pos;
228       pos = pos->next;
229     }
230   GNUNET_assert (pos != NULL);
231   if (prev == NULL)
232     loggers = pos->next;
233   else
234     prev->next = pos->next;
235   GNUNET_free (pos);
236 }
237
238
239 /**
240  * Actually output the log message.
241  *
242  * @param kind how severe was the issue
243  * @param comp component responsible
244  * @param datestr current date/time
245  * @param msg the actual message
246  */
247 static void
248 output_message (enum GNUNET_ErrorType kind,
249                 const char *comp, const char *datestr, const char *msg)
250 {
251   struct CustomLogger *pos;
252   if (GNUNET_stderr != NULL)
253     fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp, 
254              GNUNET_error_type_to_string (kind), msg);
255   pos = loggers;
256   while (pos != NULL)
257     {
258       pos->logger (pos->logger_cls, kind, comp, datestr, msg);
259       pos = pos->next;
260     }
261 }
262
263
264 /**
265  * Flush an existing bulk report to the output.
266  *
267  * @param datestr our current timestamp
268  */
269 static void
270 flush_bulk (const char *datestr)
271 {
272   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
273   int rev;
274   char *last;
275   char *ft;
276
277   if ((last_bulk_time.value == 0) || (last_bulk_repeat == 0))
278     return;
279   rev = 0;
280   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
281   if (last == NULL)
282     last = &last_bulk[BULK_TRACK_SIZE - 1];
283   else if (last != last_bulk)
284     last--;
285   if (last[0] == '\n')
286     {
287       rev = 1;
288       last[0] = '\0';
289     }
290   ft =
291     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
292                                             (last_bulk_time));
293   snprintf (msg, sizeof (msg),
294             _("Message `%.*s' repeated %u times in the last %s\n"),
295             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
296   GNUNET_free (ft);
297   if (rev == 1)
298     last[0] = '\n';
299   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
300   last_bulk_time = GNUNET_TIME_absolute_get ();
301   last_bulk_repeat = 0;
302 }
303
304
305 /**
306  * Ignore the next n calls to the log function.
307  *
308  * @param n number of log calls to ignore
309  * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
310  */
311 void
312 GNUNET_log_skip (unsigned int n, int check_reset)
313 {
314   if (n == 0)
315     {
316       int ok;
317
318       ok = (0 == skip_log);
319       skip_log = 0;
320       if (check_reset)
321         GNUNET_assert (ok);
322     }
323   else
324     skip_log += n;
325 }
326
327
328 /**
329  * Output a log message using the default mechanism.
330  *
331  * @param kind how severe was the issue
332  * @param comp component responsible
333  * @param message the actual message
334  * @param va arguments to the format string "message"
335  */
336 static void
337 mylog (enum GNUNET_ErrorType kind,
338        const char *comp, const char *message, va_list va)
339 {
340   char date[DATE_STR_SIZE];
341   time_t timetmp;
342   struct tm *tmptr;
343   size_t size;
344   char *buf;
345   va_list vacp;
346
347   if (skip_log > 0)
348     {
349       skip_log--;
350       return;
351     }
352   if ((kind & (~GNUNET_ERROR_TYPE_BULK)) > min_level)
353     return;
354   va_copy (vacp, va);
355   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
356   va_end (vacp);
357   buf = malloc (size);
358   if (buf == NULL)
359     return;                     /* oops */
360   VSNPRINTF (buf, size, message, va);
361   time (&timetmp);
362   memset (date, 0, DATE_STR_SIZE);
363   tmptr = localtime (&timetmp);
364   strftime (date, DATE_STR_SIZE, "%b %d %H:%M:%S", tmptr);
365   if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
366       (last_bulk_time.value != 0) &&
367       (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
368     {
369       last_bulk_repeat++;
370       if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).value >
371            BULK_DELAY_THRESHOLD)
372           || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
373         flush_bulk (date);
374       free (buf);
375       return;
376     }
377   flush_bulk (date);
378   strncpy (last_bulk, buf, sizeof (last_bulk));
379   last_bulk_repeat = 0;
380   last_bulk_kind = kind;
381   last_bulk_time = GNUNET_TIME_absolute_get ();
382   last_bulk_comp = comp;
383   output_message (kind, comp, date, buf);
384   free (buf);
385 }
386
387
388 /**
389  * Main log function.
390  *
391  * @param kind how serious is the error?
392  * @param message what is the message (format string)
393  * @param ... arguments for format string
394  */
395 void
396 GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...)
397 {
398   va_list va;
399   va_start (va, message);
400   mylog (kind, component, message, va);
401   va_end (va);
402 }
403
404
405 /**
406  * Log function that specifies an alternative component.
407  * This function should be used by plugins.
408  *
409  * @param kind how serious is the error?
410  * @param comp component responsible for generating the message
411  * @param message what is the message (format string)
412  * @param ... arguments for format string
413  */
414 void
415 GNUNET_log_from (enum GNUNET_ErrorType kind,
416                  const char *comp, const char *message, ...)
417 {
418   va_list va;
419   va_start (va, message);
420   mylog (kind, comp, message, va);
421   va_end (va);
422 }
423
424
425 /**
426  * Convert error type to string.
427  *
428  * @param kind type to convert
429  * @return string corresponding to the type
430  */
431 const char *
432 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
433 {
434   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
435     return _("ERROR");
436   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
437     return _("WARNING");
438   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
439     return _("INFO");
440   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
441     return _("DEBUG");
442   return _("INVALID");
443 }
444
445
446 /**
447  * Convert a hash to a string (for printing debug messages).
448  * This is one of the very few calls in the entire API that is
449  * NOT reentrant!
450  *
451  * @param hc the hash code
452  * @return string form; will be overwritten by next call to GNUNET_h2s.
453  */
454 const char *
455 GNUNET_h2s (const GNUNET_HashCode * hc)
456 {
457   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
458   GNUNET_CRYPTO_hash_to_enc (hc, &ret);
459   ret.encoding[8] = '\0';
460   return (const char *) ret.encoding;
461 }
462
463
464 /**
465  * Convert a peer identity to a string (for printing debug messages).
466  * This is one of the very few calls in the entire API that is
467  * NOT reentrant!
468  *
469  * @param pid the peer identity
470  * @return string form of the pid; will be overwritten by next
471  *         call to GNUNET_i2s.
472  */
473 const char *
474 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
475 {
476   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
477   GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
478   ret.encoding[4] = '\0';
479   return (const char *) ret.encoding;
480 }
481
482
483
484 /**
485  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
486  * (for printing debug messages).  This is one of the very few calls
487  * in the entire API that is NOT reentrant!
488  *
489  * @param addr the address
490  * @param addrlen the length of the address
491  * @return nicely formatted string for the address
492  *  will be overwritten by next call to GNUNET_a2s.
493  */
494 const char *
495 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
496 {
497   static char buf[INET6_ADDRSTRLEN + 8];
498   static char b2[6];
499   const struct sockaddr_in *v4;
500   const struct sockaddr_in6 *v6;
501
502   if (addr == NULL)
503     return _("unknown address");
504   switch (addr->sa_family)
505     {
506     case AF_INET:
507       v4 = (const struct sockaddr_in *) addr;
508       inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
509       if (0 == ntohs (v4->sin_port))
510         return buf;
511       strcat (buf, ":");
512       sprintf (b2, "%u", ntohs (v4->sin_port));
513       strcat (buf, b2);
514       return buf;
515     case AF_INET6:
516       v6 = (const struct sockaddr_in6 *) addr;
517       buf[0] = '[';
518       inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
519       if (0 == ntohs (v6->sin6_port))
520         return &buf[1];
521       strcat (buf, "]:");
522       sprintf (b2, "%u", ntohs (v6->sin6_port));
523       strcat (buf, b2);
524       return buf;
525     default:
526       return _("invalid address");
527     }
528 }
529
530
531 /**
532  * Initializer
533  */
534 void __attribute__ ((constructor)) GNUNET_util_cl_init ()
535 {
536   GNUNET_stderr = stderr;
537 }
538
539 /* end of common_logging.c */