stuff
[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   int ok;
281
282   if (n == 0)
283     {
284       ok = (0 == skip_log);
285       skip_log = 0;
286       GNUNET_assert (ok);
287     }
288   skip_log += n;
289 }
290
291
292 static void
293 mylog (enum GNUNET_ErrorType kind,
294        const char *comp, const char *message, va_list va)
295 {
296   char date[DATE_STR_SIZE];
297   time_t timetmp;
298   struct tm *tmptr;
299   size_t size;
300   char *buf;
301   va_list vacp;
302
303   if (skip_log > 0)
304     {
305       skip_log--;
306       return;
307     }
308   if ((kind & (~GNUNET_ERROR_TYPE_BULK)) > min_level)
309     return;
310   va_copy (vacp, va);
311   size = VSNPRINTF (NULL, 0, message, vacp) + 1;
312   va_end (vacp);
313   buf = malloc (size);
314   if (buf == NULL)
315     return;                     /* oops */
316   VSNPRINTF (buf, size, message, va);
317   time (&timetmp);
318   memset (date, 0, DATE_STR_SIZE);
319   tmptr = localtime (&timetmp);
320   strftime (date, DATE_STR_SIZE, "%b %d %H:%M:%S", tmptr);
321   if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
322       (last_bulk_time.value != 0) &&
323       (0 == strncmp (buf, last_bulk, sizeof (last_bulk))))
324     {
325       last_bulk_repeat++;
326       if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).value >
327            BULK_DELAY_THRESHOLD)
328           || (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
329         flush_bulk (date);
330       free (buf);
331       return;
332     }
333   flush_bulk (date);
334   strncpy (last_bulk, buf, sizeof (last_bulk));
335   last_bulk_repeat = 0;
336   last_bulk_kind = kind;
337   last_bulk_time = GNUNET_TIME_absolute_get ();
338   last_bulk_comp = comp;
339   output_message (kind, comp, date, buf);
340   free (buf);
341 }
342
343
344 void
345 GNUNET_log (enum GNUNET_ErrorType kind, const char *message, ...)
346 {
347   va_list va;
348   va_start (va, message);
349   mylog (kind, component, message, va);
350   va_end (va);
351 }
352
353
354 void
355 GNUNET_log_from (enum GNUNET_ErrorType kind,
356                  const char *comp, const char *message, ...)
357 {
358   va_list va;
359   va_start (va, message);
360   mylog (kind, comp, message, va);
361   va_end (va);
362 }
363
364
365 /**
366  * Convert KIND to String
367  */
368 const char *
369 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
370 {
371   if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
372     return _("ERROR");
373   if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
374     return _("WARNING");
375   if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
376     return _("INFO");
377   if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
378     return _("DEBUG");
379   return _("INVALID");
380 }
381
382
383 /**
384  * Convert a hash to a string (for printing debug messages).
385  * This is one of the very few calls in the entire API that is
386  * NOT reentrant!
387  *
388  * @param pid the peer identity
389  * @return string form; will be overwritten by next call to GNUNET_h2s.
390  */
391 const char *
392 GNUNET_h2s (const GNUNET_HashCode *pid)
393 {
394   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
395   GNUNET_CRYPTO_hash_to_enc (pid, &ret);
396   ret.encoding[8] = '\0';
397   return (const char *) ret.encoding;
398 }
399
400
401 /**
402  * Convert a peer identity to a string (for printing debug messages).
403  * This is one of the very few calls in the entire API that is
404  * NOT reentrant!
405  *
406  * @param pid the peer identity
407  * @return string form of the pid; will be overwritten by next
408  *         call to GNUNET_i2s.
409  */
410 const char *
411 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
412 {
413   static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
414   GNUNET_CRYPTO_hash_to_enc (&pid->hashPubKey, &ret);
415   ret.encoding[4] = '\0';
416   return (const char *) ret.encoding;
417 }
418
419
420
421 /**
422  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
423  * (for printing debug messages).  This is one of the very few calls
424  * in the entire API that is NOT reentrant!
425  *
426  * @param addr the address
427  * @param addrlen the length of the address
428  * @return nicely formatted string for the address
429  *  will be overwritten by next call to GNUNET_a2s.
430  */
431 const char *GNUNET_a2s (const struct sockaddr *addr,
432                         socklen_t addrlen)
433 {
434   static char buf[INET6_ADDRSTRLEN+8];
435   static char b2[6];
436   const struct sockaddr_in * v4;
437   const struct sockaddr_in6 *v6;
438
439   if (addr == NULL)
440     return _("unknown address");
441   switch (addr->sa_family)
442     {
443     case AF_INET:
444       v4 = (const struct sockaddr_in*)addr;
445       inet_ntop(AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
446       if (0 == ntohs(v4->sin_port))
447         return buf;     
448       strcat (buf, ":");
449       sprintf (b2, "%u", ntohs(v4->sin_port));
450       strcat (buf, b2);
451       return buf;
452     case AF_INET6:
453       v6 = (const struct sockaddr_in6*)addr;
454       buf[0] = '[';
455       inet_ntop(AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
456       if (0 == ntohs(v6->sin6_port))
457         return &buf[1]; 
458       strcat (buf, "]:");
459       sprintf (b2, "%u", ntohs(v6->sin6_port));
460       strcat (buf, b2);
461       return buf;      
462     default:
463       return _("invalid address");
464     }
465 }
466
467
468 /**
469  * Initializer
470  */
471 void __attribute__ ((constructor))
472 GNUNET_util_cl_init()
473 {
474   GNUNET_stderr = stderr;
475 }
476
477 /* end of common_logging.c */