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