updates.
[silc.git] / lib / silcutil / silclog.c
1 /*
2
3   silclog.c
4
5   Author: Johnny Mnemonic <johnny@themnemonic.org>
6
7   Copyright (C) 1997 - 2002 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /* $Id$ */
21
22 #include "silcincludes.h"
23
24 /* Minimum time delay for log flushing calls (in seconds) */
25 #define SILC_LOG_FLUSH_MIN_DELAY 2
26
27 /* nice macro for looping through all logs -- makes the code more readable */
28 #define SILC_FOREACH_LOG(__x__) for (__x__ = 0; __x__ < SILC_LOG_MAX; __x__++)
29
30 /* Our working struct -- at the moment we keep it private, but this could
31  * change in the future */
32 struct SilcLogStruct {
33   char *filename;
34   FILE *fp;
35   SilcUInt32 maxsize;
36   char *typename;
37   SilcLogType type;
38   SilcLogCb cb;
39   void *context;
40 };
41 typedef struct SilcLogStruct *SilcLog;
42
43 /* These are the known logging channels.  We initialize this struct with most
44  * of the fields set to NULL, because we'll fill in those values at runtime. */
45 static struct SilcLogStruct silclogs[SILC_LOG_MAX] = {
46   {NULL, NULL, 0, "Info", SILC_LOG_INFO, NULL, NULL},
47   {NULL, NULL, 0, "Warning", SILC_LOG_WARNING, NULL, NULL},
48   {NULL, NULL, 0, "Error", SILC_LOG_ERROR, NULL, NULL},
49   {NULL, NULL, 0, "Fatal", SILC_LOG_FATAL, NULL, NULL},
50 };
51
52 /* If TRUE, log files will be flushed for each log input */
53 bool silc_log_quick = FALSE;
54
55 /* Set TRUE/FALSE to enable/disable debugging */
56 bool silc_debug = FALSE;
57 bool silc_debug_hexdump = FALSE;
58
59 /* Flush delay (in seconds) */
60 long silc_log_flushdelay = 300;
61
62 /* Regular pattern matching expression for the debug output */
63 char *silc_log_debug_string = NULL;
64
65 /* Debug callbacks. If set, these are triggered for each specific output. */
66 static SilcLogDebugCb silc_log_debug_cb = NULL;
67 static void *silc_log_debug_context = NULL;
68 static SilcLogHexdumpCb silc_log_hexdump_cb = NULL;
69 static void *silc_log_hexdump_context = NULL;
70
71 /* Did we register already our functions to the scheduler? */
72 static bool silc_log_scheduled = FALSE;
73 static bool silc_log_no_init = FALSE;
74
75 /* This is only needed during starting up -- don't lose any logging message */
76 static bool silc_log_starting = TRUE;
77
78 /* The type wrapper utility. Translates a SilcLogType id to the corresponding
79  * logfile, or NULL if not found. */
80 static SilcLog silc_log_find_by_type(SilcLogType type)
81 {
82   /* this is not really needed, but i think it's more secure */
83   switch (type) {
84     case SILC_LOG_INFO:
85       return &silclogs[SILC_LOG_INFO];
86     case SILC_LOG_WARNING:
87       return &silclogs[SILC_LOG_WARNING];
88     case SILC_LOG_ERROR:
89       return &silclogs[SILC_LOG_ERROR];
90     case SILC_LOG_FATAL:
91       return &silclogs[SILC_LOG_FATAL];
92     default:
93       return NULL;
94   }
95   return NULL;
96 }
97
98 /* Given an open log file, checks the size and rotates it if there is a
99  * max size set lower then the current size */
100 static void silc_log_checksize(SilcLog log)
101 {
102   char newname[127];
103   long size;
104
105   if (!log || !log->fp || !log->maxsize)
106     return; /* we are not interested */
107
108   if ((size = ftell(log->fp)) < 0) {
109     /* OMG, EBADF is here.. we'll try our best.. */
110     FILE *oldfp = log->fp;
111     fclose(oldfp); /* we can discard the error */
112     log->fp = NULL; /* make sure we don't get here recursively */
113     SILC_LOG_ERROR(("Error while checking size of the log file %s, fp=%p",
114                     log->filename, oldfp));
115     return;
116   }
117   if (size < log->maxsize) return;
118
119   /* It's too big */
120   fprintf(log->fp, "[%s] [%s] Cycling log file, over max "
121           "logsize (%lu kilobytes)\n",
122           silc_get_time(), log->typename, log->maxsize / 1024);
123   fflush(log->fp);
124   fclose(log->fp);
125   snprintf(newname, sizeof(newname), "%s.old", log->filename);
126   unlink(newname);
127
128   /* I heard the following syscall may cause portability issues, but I don't
129    * have any other solution since SILC library doesn't provide any other
130    * function like this. -Johnny */
131   rename(log->filename, newname);
132   if (!(log->fp = fopen(log->filename, "w")))
133     SILC_LOG_WARNING(("Couldn't reopen logfile %s for type \"%s\": %s",
134                       log->filename, log->typename, strerror(errno)));
135 }
136
137 /* Reset a logging channel (close and reopen) */
138
139 static bool silc_log_reset(SilcLog log)
140 {
141   if (!log) return FALSE;
142   if (log->fp) {
143     fflush(log->fp);
144     fclose(log->fp);
145   }
146   if (!log->filename) return FALSE;
147   if (!(log->fp = fopen(log->filename, "a+"))) {
148     SILC_LOG_WARNING(("Couldn't reset logfile %s for type \"%s\": %s",
149                       log->filename, log->typename, strerror(errno)));
150     return FALSE;
151   }
152
153   return TRUE;
154 }
155
156 /* Internal timeout callback to flush log channels and check file sizes */
157
158 SILC_TASK_CALLBACK(silc_log_fflush_callback)
159 {
160   unsigned int u;
161   if (silc_log_quick) {
162     silc_log_flush_all();
163     SILC_FOREACH_LOG(u)
164       silc_log_checksize(&silclogs[u]);
165   }
166   silc_log_starting = FALSE;
167   if (silc_log_flushdelay < SILC_LOG_FLUSH_MIN_DELAY)
168     silc_log_flushdelay = SILC_LOG_FLUSH_MIN_DELAY;
169   silc_schedule_task_add((SilcSchedule) context, 0, silc_log_fflush_callback,
170                          context, silc_log_flushdelay, 0, SILC_TASK_TIMEOUT,
171                          SILC_TASK_PRI_NORMAL);
172 }
173
174 /* Outputs the log message to the first available channel. Channels are
175  * ordered by importance (see SilcLogType documentation).
176  * More important channels can be printed on less important ones, but not
177  * vice-versa. */
178
179 void silc_log_output(SilcLogType type, char *string)
180 {
181   char *typename = NULL;
182   FILE *fp;
183   SilcLog log;
184
185   if ((type > SILC_LOG_MAX) || !(log = silc_log_find_by_type(type)))
186     goto end;
187
188   /* Save the original typename, because even if we redirect the message
189    * to another channel we'll keep however the original channel name */
190   typename = log->typename;
191
192   /* If there is a custom callback set, use it and return. */
193   if (log->cb) {
194     if ((*log->cb)(type, string, log->context))
195       goto end;
196   }
197
198   if (!silc_log_scheduled) {
199     if (silc_log_no_init == FALSE) {
200       fprintf(stderr,
201               "Warning, trying to output without log files initialization, "
202               "log output is going to stderr\n");
203       silc_log_no_init = TRUE;
204     }
205     /* redirect output */
206     fp = stderr;
207     log = NULL;
208     goto found;
209   }
210
211   /* ok, now we have to find an open stream */
212   while (TRUE) {
213     if (log && (fp = log->fp)) goto found;
214     if (type == 0) break;
215     log = silc_log_find_by_type(--type);
216   }
217
218   /* Couldn't find any open stream.. sorry :( */
219   SILC_LOG_DEBUG(("Warning! couldn't find any available log channel!"));
220   goto end;
221
222  found:
223   fprintf(fp, "[%s] [%s] %s\n", silc_get_time(), typename, string);
224   if (silc_log_quick || silc_log_starting) {
225     fflush(fp);
226     if (log) /* we may have been redirected to stderr */
227       silc_log_checksize(log);
228   }
229
230  end:
231   /* If debugging, also output the logging message to the console */
232   if (typename && silc_debug) {
233     fprintf(stderr, "[Logging] [%s] %s\n", typename, string);
234     fflush(stderr);
235   }
236   silc_free(string);
237 }
238
239 /* returns an internally allocated pointer to a logging channel file */
240 char *silc_log_get_file(SilcLogType type)
241 {
242   SilcLog log;
243
244   if (!(log = silc_log_find_by_type(type)))
245     return NULL;
246   if (log->fp)
247     return log->filename;
248   return NULL;
249 }
250
251 /* Set and initialize the specified logging channel. See the API reference */
252 bool silc_log_set_file(SilcLogType type, char *filename, SilcUInt32 maxsize,
253                        SilcSchedule scheduler)
254 {
255   FILE *fp = NULL;
256   SilcLog log;
257
258   log = silc_log_find_by_type(type);
259   if (!log || !scheduler)
260     return FALSE;
261
262   SILC_LOG_DEBUG(("Setting \"%s\" file to %s (max size=%d)",
263                   log->typename, filename, maxsize));
264
265   /* before assuming the new file, make sure we can open it */
266   if (filename) {
267     if (!(fp = fopen(filename, "a+"))) {
268       fprintf(stderr, "warning: couldn't open log file %s: %s\n",
269               filename, strerror(errno));
270       return FALSE;
271     }
272   }
273
274   /* clean the logging channel */
275   if (log->filename) {
276     if (log->fp)
277       fclose(log->fp);
278     silc_free(log->filename);
279     log->filename = NULL;
280     log->fp = NULL;
281   }
282
283   if (fp) {
284     log->filename = strdup(filename);
285     log->fp = fp;
286     log->maxsize = maxsize;
287   }
288
289   if (silc_log_scheduled)
290     return TRUE;
291
292   /* add schedule hook with a short delay to make sure we'll use right delay */
293   silc_schedule_task_add(scheduler, 0, silc_log_fflush_callback,
294                          (void *) scheduler, 10, 0,
295                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
296
297   silc_log_scheduled = TRUE;
298
299   return TRUE;
300 }
301
302 /* Sets a log callback, set callback to NULL to return to default behaviour */
303
304 void silc_log_set_callback(SilcLogType type, SilcLogCb cb, void *context)
305 {
306   SilcLog log;
307
308   if (!(log = silc_log_find_by_type(type)))
309     return;
310
311   log->cb = cb;
312   log->context = context;
313 }
314
315 /* Resets log callbacks */
316
317 void silc_log_reset_callbacks()
318 {
319   unsigned int u;
320   SILC_FOREACH_LOG(u) {
321     silclogs[u].cb = NULL;
322     silclogs[u].context = NULL;
323   }
324 }
325
326 /* Flushes all opened logging channels */
327
328 void silc_log_flush_all() {
329   unsigned int u;
330   SILC_LOG_DEBUG(("Flushing all logs"));
331   SILC_FOREACH_LOG(u) {
332     if (silclogs[u].fp)
333       fflush(silclogs[u].fp);
334   }
335 }
336
337 /* Resets all known logging channels */
338
339 void silc_log_reset_all() {
340   unsigned int u;
341   SILC_LOG_DEBUG(("Resetting all logs"));
342   SILC_FOREACH_LOG(u)
343     silc_log_reset(&silclogs[u]);
344   /* Immediately flush any possible warning message */
345   silc_log_flush_all();
346 }
347
348 /* Outputs the debug message to stderr. */
349
350 void silc_log_output_debug(char *file, char *function,
351                            int line, char *string)
352 {
353   if (!silc_debug)
354     goto end;
355
356   if (silc_log_debug_string &&
357       !silc_string_regex_match(silc_log_debug_string, file) &&
358       !silc_string_regex_match(silc_log_debug_string, function))
359     goto end;
360
361   if (silc_log_debug_cb) {
362     if ((*silc_log_debug_cb)(file, function, line, string,
363                              silc_log_debug_context))
364       goto end;
365   }
366
367   fprintf(stderr, "%s:%d: %s\n", function, line, string);
368   fflush(stderr);
369
370  end:
371   silc_free(string);
372 }
373
374 /* Hexdumps a message */
375
376 void silc_log_output_hexdump(char *file, char *function,
377                              int line, void *data_in,
378                              SilcUInt32 len, char *string)
379 {
380   int i, k;
381   int off, pos, count;
382   unsigned char *data = (unsigned char *)data_in;
383
384   if (!silc_debug_hexdump)
385     goto end;
386
387   if (silc_log_debug_string &&
388       !silc_string_regex_match(silc_log_debug_string, file) &&
389       !silc_string_regex_match(silc_log_debug_string, function))
390     goto end;
391
392   if (silc_log_hexdump_cb) {
393     if ((*silc_log_hexdump_cb)(file, function, line, data_in, len, string,
394                                silc_log_hexdump_context))
395       goto end;
396   }
397
398   fprintf(stderr, "%s:%d: %s\n", function, line, string);
399
400   k = 0;
401   pos = 0;
402   count = 16;
403   off = len % 16;
404   while (1) {
405     if (off) {
406       if ((len - pos) < 16 && (len - pos <= len - off))
407         count = off;
408     } else {
409       if (pos == len)
410         count = 0;
411     }
412     if (off == len)
413       count = len;
414
415     if (count)
416       fprintf(stderr, "%08X  ", k++ * 16);
417
418     for (i = 0; i < count; i++) {
419       fprintf(stderr, "%02X ", data[pos + i]);
420
421       if ((i + 1) % 4 == 0)
422         fprintf(stderr, " ");
423     }
424
425     if (count && count < 16) {
426       int j;
427
428       for (j = 0; j < 16 - count; j++) {
429         fprintf(stderr, "   ");
430
431         if ((j + count + 1) % 4 == 0)
432           fprintf(stderr, " ");
433       }
434     }
435
436     for (i = 0; i < count; i++) {
437       char ch;
438
439       if (data[pos] < 32 || data[pos] >= 127)
440         ch = '.';
441       else
442         ch = data[pos];
443
444       fprintf(stderr, "%c", ch);
445       pos++;
446     }
447
448     if (count)
449       fprintf(stderr, "\n");
450
451     if (count < 16)
452       break;
453   }
454
455  end:
456   silc_free(string);
457 }
458
459 /* Sets debug callbacks */
460
461 void silc_log_set_debug_callbacks(SilcLogDebugCb debug_cb,
462                                   void *debug_context,
463                                   SilcLogHexdumpCb hexdump_cb,
464                                   void *hexdump_context)
465 {
466   silc_log_debug_cb = debug_cb;
467   silc_log_debug_context = debug_context;
468   silc_log_hexdump_cb = hexdump_cb;
469   silc_log_hexdump_context = hexdump_context;
470 }
471
472 /* Resets debug callbacks */
473
474 void silc_log_reset_debug_callbacks()
475 {
476   silc_log_debug_cb = NULL;
477   silc_log_debug_context = NULL;
478   silc_log_hexdump_cb = NULL;
479   silc_log_hexdump_context = NULL;
480 }
481
482 /* Set current debug string */
483
484 void silc_log_set_debug_string(const char *debug_string)
485 {
486   silc_free(silc_log_debug_string);
487   if ((strchr(debug_string, '(') && strchr(debug_string, ')')) ||
488       strchr(debug_string, '$'))
489     silc_log_debug_string = strdup(debug_string);
490   else
491     silc_log_debug_string = silc_string_regexify(debug_string);
492 }