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