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