don't fail if conditional log output didn't actually happen
[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 const 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 static FILE *GNUNET_stderr;
127
128 /**
129  * Convert a textual description of a loglevel
130  * to the respective GNUNET_GE_KIND.
131  * @returns GNUNET_GE_INVALID if log does not parse
132  */
133 static enum GNUNET_ErrorType
134 get_type (const char *log)
135 {
136   if (0 == strcasecmp (log, _("DEBUG")))
137     return GNUNET_ERROR_TYPE_DEBUG;
138   if (0 == strcasecmp (log, _("INFO")))
139     return GNUNET_ERROR_TYPE_INFO;
140   if (0 == strcasecmp (log, _("WARNING")))
141     return GNUNET_ERROR_TYPE_WARNING;
142   if (0 == strcasecmp (log, _("ERROR")))
143     return GNUNET_ERROR_TYPE_ERROR;
144   return GNUNET_ERROR_TYPE_INVALID;
145 }
146
147 /**
148  * Setup logging.
149  *
150  * @param comp default component to use
151  * @param loglevel what types of messages should be logged
152  */
153 int
154 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
155 {
156   FILE *altlog;
157
158   component = comp;
159   min_level = get_type (loglevel);
160   if (logfile == NULL)
161     return GNUNET_OK;
162   altlog = fopen (logfile, "a");
163   if (altlog == NULL)
164     {
165       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", logfile);
166       return GNUNET_SYSERR;
167     }
168   if (GNUNET_stderr != NULL)
169     fclose (GNUNET_stderr);
170   GNUNET_stderr = altlog;
171   return GNUNET_OK;
172 }
173
174 /**
175  * Add a custom logger.
176  *
177  * @param logger log function
178  * @param logger_cls closure for logger
179  */
180 void
181 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
182 {
183   struct CustomLogger *entry;
184
185   entry = GNUNET_malloc (sizeof (struct CustomLogger));
186   entry->logger = logger;
187   entry->logger_cls = logger_cls;
188   entry->next = loggers;
189   loggers = entry;
190 }
191
192 /**
193  * Remove a custom logger.
194  *
195  * @param logger log function
196  * @param logger_cls closure for logger
197  */
198 void
199 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
200 {
201   struct CustomLogger *pos;
202   struct CustomLogger *prev;
203
204   prev = NULL;
205   pos = loggers;
206   while ((pos != NULL) &&
207          ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
208     {
209       prev = pos;
210       pos = pos->next;
211     }
212   GNUNET_assert (pos != NULL);
213   if (prev == NULL)
214     loggers = pos->next;
215   else
216     prev->next = pos->next;
217   GNUNET_free (pos);
218 }
219
220 static void
221 output_message (enum GNUNET_ErrorType kind,
222                 const char *comp, const char *datestr, const char *msg)
223 {
224   struct CustomLogger *pos;
225   if (GNUNET_stderr != NULL)
226     fprintf (GNUNET_stderr, "%s %s %s %s", datestr, comp,
227              GNUNET_error_type_to_string (kind), msg);
228   pos = loggers;
229   while (pos != NULL)
230     {
231       pos->logger (pos->logger_cls, kind, comp, datestr, msg);
232       pos = pos->next;
233     }
234 }
235
236 static void
237 flush_bulk (const char *datestr)
238 {
239   char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
240   int rev;
241   char *last;
242   char *ft;
243
244   if ((last_bulk_time.value == 0) || (last_bulk_repeat == 0))
245     return;
246   rev = 0;
247   last = memchr (last_bulk, '\0', BULK_TRACK_SIZE);
248   if (last == NULL)
249     last = &last_bulk[BULK_TRACK_SIZE - 1];
250   else if (last != last_bulk)
251     last--;
252   if (last[0] == '\n')
253     {
254       rev = 1;
255       last[0] = '\0';
256     }
257   ft =
258     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
259                                             (last_bulk_time));
260   snprintf (msg, sizeof (msg),
261             _("Message `%.*s' repeated %u times in the last %s\n"),
262             BULK_TRACK_SIZE, last_bulk, last_bulk_repeat, ft);
263   GNUNET_free (ft);
264   if (rev == 1)
265     last[0] = '\n';
266   output_message (last_bulk_kind, last_bulk_comp, datestr, msg);
267   last_bulk_time = GNUNET_TIME_absolute_get ();
268   last_bulk_repeat = 0;
269 }
270
271
272 /**
273  * Ignore the next n calls to the log function.
274  *
275  * @param n number of log calls to ignore
276  */
277 void
278 GNUNET_log_skip (unsigned int n)
279 {
280   if (n == 0)
281       skip_log = 0;
282   else
283     skip_log += n;
284 }
285
286
287 static void
288 mylog (enum GNUNET_ErrorType kind,
289        const char *comp, const char *message, va_list va)
290 {
291   char date[DATE_STR_SIZE];
292   time_t timetmp;
293   struct tm *tmptr;
294   size_t size;
295   char *buf;
296   va_list vacp;
297
298   if (skip_log > 0)
299     {
300       skip_log--;
301       return;
302     }
303   if ((kind & (~GNUNET_ERROR_TYPE_BULK)) > min_level)
304     return;
305   va_copy (vacp, va);
306   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
307   va_end (vacp);
308   buf = malloc (size);
309   if (buf == NULL)
310     return;                     /* oops */
311   VSNPRINTF (buf, size, message, va);
312   time (&timetmp);
313   memset (date, 0, DATE_STR_SIZE);
314   tmptr = localtime (&timetmp);
315   strftime (date, DATE_STR_SIZE, "%b %d %H:%M:%S", tmptr);
316   if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
317       (last_bulk_time.value != 0) &&
318       (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
319     {
320       last_bulk_repeat++;
321       if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).value >
322            BULK_DELAY_THRESHOLD)
323           || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
324         flush_bulk (date);
325       free (buf);
326       return;
327     }
328   flush_bulk (date);
329   strncpy (last_bulk, buf, sizeof (last_bulk));
330   last_bulk_repeat = 0;
331   last_bulk_kind = kind;
332   last_bulk_time = GNUNET_TIME_absolute_get ();
333   last_bulk_comp = comp;
334   output_message (kind, comp, date, buf);
335   free (buf);
336 }
337
338
339 void
340 GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...)
341 {
342   va_list va;
343   va_start (va, message);
344   mylog (kind, component, message, va);
345   va_end (va);
346 }
347
348
349 void
350 GNUNET_log_from (enum GNUNET_ErrorType kind,
351                  const char *comp, const char *message, ...)
352 {
353   va_list va;
354   va_start (va, message);
355   mylog (kind, comp, message, va);
356   va_end (va);
357 }
358
359
360 /**
361  * Convert KIND to String
362  */
363 const char *
364 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
365 {
366   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
367     return _("ERROR");
368   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
369     return _("WARNING");
370   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
371     return _("INFO");
372   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
373     return _("DEBUG");
374   return _("INVALID");
375 }
376
377
378 /**
379  * Convert a hash to a string (for printing debug messages).
380  * This is one of the very few calls in the entire API that is
381  * NOT reentrant!
382  *
383  * @param pid the peer identity
384  * @return string form; will be overwritten by next call to GNUNET_h2s.
385  */
386 const char *
387 GNUNET_h2s (const GNUNET_HashCode *pid)
388 {
389   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
390   GNUNET_CRYPTO_hash_to_enc (pid, &ret);
391   ret.encoding[8] = '\0';
392   return (const char *) ret.encoding;
393 }
394
395
396 /**
397  * Convert a peer identity to a string (for printing debug messages).
398  * This is one of the very few calls in the entire API that is
399  * NOT reentrant!
400  *
401  * @param pid the peer identity
402  * @return string form of the pid; will be overwritten by next
403  *         call to GNUNET_i2s.
404  */
405 const char *
406 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
407 {
408   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
409   GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
410   ret.encoding[4] = '\0';
411   return (const char *) ret.encoding;
412 }
413
414
415
416 /**
417  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
418  * (for printing debug messages).  This is one of the very few calls
419  * in the entire API that is NOT reentrant!
420  *
421  * @param addr the address
422  * @param addrlen the length of the address
423  * @return nicely formatted string for the address
424  *  will be overwritten by next call to GNUNET_a2s.
425  */
426 const char *GNUNET_a2s (const struct sockaddr *addr,
427                         socklen_t addrlen)
428 {
429   static char buf[INET6_ADDRSTRLEN+8];
430   static char b2[6];
431   const struct sockaddr_in * v4;
432   const struct sockaddr_in6 *v6;
433
434   if (addr == NULL)
435     return _("unknown address");
436   switch (addr->sa_family)
437     {
438     case AF_INET:
439       v4 = (const struct sockaddr_in*)addr;
440       inet_ntop(AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
441       if (0 == ntohs(v4->sin_port))
442         return buf;     
443       strcat (buf, ":");
444       sprintf (b2, "%u", ntohs(v4->sin_port));
445       strcat (buf, b2);
446       return buf;
447     case AF_INET6:
448       v6 = (const struct sockaddr_in6*)addr;
449       buf[0] = '[';
450       inet_ntop(AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
451       if (0 == ntohs(v6->sin6_port))
452         return &buf[1]; 
453       strcat (buf, "]:");
454       sprintf (b2, "%u", ntohs(v6->sin6_port));
455       strcat (buf, b2);
456       return buf;      
457     default:
458       return _("invalid address");
459     }
460 }
461
462
463 /**
464  * Initializer
465  */
466 void __attribute__ ((constructor))
467 GNUNET_util_cl_init()
468 {
469   GNUNET_stderr = stderr;
470 }
471
472 /* end of common_logging.c */