License update
[srvx.git] / src / log.c
1 /* log.c - Diagnostic and error logging
2  * Copyright 2000-2004 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "conf.h"
22 #include "log.h"
23 #include "helpfile.h" /* send_message, message_register, etc */
24 #include "nickserv.h"
25
26 struct logDestination;
27
28 struct logDest_vtable {
29     const char *type_name;
30     struct logDestination* (*open)(const char *args);
31     void (*reopen)(struct logDestination *self);
32     void (*close)(struct logDestination *self);
33     void (*log_audit)(struct logDestination *self, struct log_type *type, struct logEntry *entry);
34     void (*log_replay)(struct logDestination *self, struct log_type *type, int is_write, const char *line);
35     void (*log_module)(struct logDestination *self, struct log_type *type, enum log_severity sev, const char *message);
36 };
37
38 struct logDestination {
39     struct logDest_vtable *vtbl;
40     char *name;
41     int refcnt;
42 };
43
44 DECLARE_LIST(logList, struct logDestination*);
45
46 struct log_type {
47     char *name;
48     struct logList logs[LOG_NUM_SEVERITIES];
49     struct logEntry *log_oldest;
50     struct logEntry *log_newest;
51     unsigned int log_count;
52     unsigned int max_age;
53     unsigned int max_count;
54     unsigned int default_set : 1;
55 };
56
57 static const char *log_severity_names[] = {
58     "replay",   /* 0 */
59     "debug",
60     "command",
61     "info",
62     "override",
63     "staff",    /* 5 */
64     "warning",
65     "error",
66     "fatal",
67     0
68 };
69
70 static struct dict *log_dest_types;
71 static struct dict *log_dests;
72 static struct dict *log_types;
73 static struct log_type *log_default;
74 static int log_inited, log_debugged;
75
76 DEFINE_LIST(logList, struct logDestination*);
77 static void log_format_audit(struct logEntry *entry);
78 static const struct message_entry msgtab[] = {
79     { "MSG_INVALID_FACILITY", "$b%s$b is an invalid log facility." },
80     { "MSG_INVALID_SEVERITY", "$b%s$b is an invalid severity level." },
81     { NULL, NULL }
82 };
83
84 static struct logDestination *
85 log_open(const char *name)
86 {
87     struct logDest_vtable *vtbl;
88     struct logDestination *ld;
89     char *sep;
90     char type_name[32];
91
92     if ((ld = dict_find(log_dests, name, NULL))) {
93         ld->refcnt++;
94         return ld;
95     }
96     if ((sep = strchr(name, ':'))) {
97         memcpy(type_name, name, sep-name);
98         type_name[sep-name] = 0;
99     } else {
100         strcpy(type_name, name);
101     }
102     if (!(vtbl = dict_find(log_dest_types, type_name, NULL))) {
103         log_module(MAIN_LOG, LOG_ERROR, "Invalid log type for log '%s'.", name);
104         return 0;
105     }
106     if (!(ld = vtbl->open(sep ? sep+1 : 0)))
107         return 0;
108     ld->name = strdup(name);
109     dict_insert(log_dests, ld->name, ld);
110     ld->refcnt = 1;
111     return ld;
112 }
113
114 static void
115 logList_open(struct logList *ll, struct record_data *rd)
116 {
117     struct logDestination *ld;
118     unsigned int ii;
119
120     if (!ll->size)
121         logList_init(ll);
122     switch (rd->type) {
123     case RECDB_QSTRING:
124         if ((ld = log_open(rd->d.qstring)))
125             logList_append(ll, ld);
126         break;
127     case RECDB_STRING_LIST:
128         for (ii=0; ii<rd->d.slist->used; ++ii) {
129             if ((ld = log_open(rd->d.slist->list[ii])))
130                 logList_append(ll, ld);
131         }
132         break;
133     default:
134         break;
135     }
136 }
137
138 static void
139 logList_join(struct logList *target, const struct logList *source)
140 {
141     unsigned int ii, jj, kk;
142
143     if (!source->used)
144         return;
145     jj = target->used;
146     target->used += source->used;
147     target->size += source->used;
148     target->list = realloc(target->list, target->size * sizeof(target->list[0]));
149     for (ii = 0; ii < source->used; ++ii, ++jj) {
150         int dup;
151         for (dup = 0, kk = 0; kk < jj; kk++) {
152             if (target->list[kk] == source->list[ii]) {
153                 dup = 1;
154                 break;
155             }
156         }
157         if (dup) {
158             jj--;
159             target->used--;
160             continue;
161         }
162         target->list[jj] = source->list[ii];
163         target->list[jj]->refcnt++;
164     }
165 }
166
167 static void
168 logList_close(struct logList *ll)
169 {
170     unsigned int ii;
171     for (ii=0; ii<ll->used; ++ii) {
172         if (!--ll->list[ii]->refcnt) {
173             struct logDestination *ld = ll->list[ii];
174             ld->vtbl->close(ld);
175         }
176     }
177     logList_clean(ll);
178 }
179
180 static void
181 close_logs(void)
182 {
183     dict_iterator_t it;
184     struct log_type *lt;
185     enum log_severity ls;
186
187     for (it = dict_first(log_types); it; it = iter_next(it)) {
188         lt = iter_data(it);
189         for (ls = 0; ls < LOG_NUM_SEVERITIES; ls++) {
190             logList_close(&lt->logs[ls]);
191
192             lt->logs[ls].size = 0;
193             lt->logs[ls].used = 0;
194             lt->logs[ls].list = 0;
195         }
196     }
197 }
198
199 static void
200 log_type_free_oldest(struct log_type *lt)
201 {
202     struct logEntry *next;
203
204     if (!lt->log_oldest)
205         return;
206     next = lt->log_oldest->next;
207     free(lt->log_oldest->default_desc);
208     free(lt->log_oldest);
209     lt->log_oldest = next;
210     lt->log_count--;
211 }
212
213 static void
214 log_type_free(void *ptr)
215 {
216     struct log_type *lt = ptr;
217
218     while (lt->log_oldest)
219         log_type_free_oldest(lt);
220     free(lt);
221 }
222
223 static void
224 cleanup_logs(void)
225 {
226
227     close_logs();
228     dict_delete(log_types);
229     dict_delete(log_dests);
230     dict_delete(log_dest_types);
231 }
232
233 static enum log_severity
234 find_severity(const char *text)
235 {
236     enum log_severity ls;
237     for (ls = 0; ls < LOG_NUM_SEVERITIES; ++ls)
238         if (!ircncasecmp(text, log_severity_names[ls], strlen(log_severity_names[ls])))
239             return ls;
240     return LOG_NUM_SEVERITIES;
241 }
242
243 /* Log keys are based on syslog.conf syntax:
244  *   KEY := LOGSET '.' SEVSET
245  *   LOGSET := LOGLIT | LOGLIT ',' LOGSET
246  *   LOGLIT := a registered log type
247  *   SEVSET := '*' | SEVLIT | '<' SEVLIT | '<=' SEVLIT | '>' SEVLIT | '>=' SEVLIT | SEVLIG ',' SEVSET
248  *   SEVLIT := one of log_severity_names
249  * A KEY contains the Cartesian product of the logs in its LOGSET
250  * and the severities in its SEVSET.
251  */
252
253 static void
254 log_parse_logset(char *buffer, struct string_list *slist)
255 {
256     slist->used = 0;
257     while (buffer) {
258         char *cont = strchr(buffer, ',');
259         if (cont)
260             *cont++ = 0;
261         string_list_append(slist, strdup(buffer));
262         buffer = cont;
263     }
264 }
265
266 static void
267 log_parse_sevset(char *buffer, char targets[LOG_NUM_SEVERITIES])
268 {
269     memset(targets, 0, LOG_NUM_SEVERITIES);
270     while (buffer) {
271         char *cont;
272         enum log_severity bound;
273         int first;
274
275         cont = strchr(buffer, ',');
276         if (cont) *cont++ = 0;
277         if (buffer[0] == '*' && buffer[1] == 0) {
278             for (bound = 0; bound < LOG_NUM_SEVERITIES; bound++) {
279                 /* make people explicitly specify replay targets */
280                 if (bound != LOG_REPLAY)
281                     targets[bound] = 1;
282             }
283         } else if (buffer[0] == '<') {
284             if (buffer[1] == '=')
285                 bound = find_severity(buffer+2) + 1;
286             else
287                 bound = find_severity(buffer+1);
288             for (first = 1; bound > 0; bound--) {
289                 /* make people explicitly specify replay targets */
290                 if (bound != LOG_REPLAY || first) {
291                     targets[bound] = 1;
292                     first = 0;
293                 }
294             }
295         } else if (buffer[0] == '>') {
296             if (buffer[1] == '=')
297                 bound = find_severity(buffer+2);
298             else
299                 bound = find_severity(buffer+1) + 1;
300             for (first = 1; bound < LOG_NUM_SEVERITIES; bound++) {
301                 /* make people explicitly specify replay targets */
302                 if (bound != LOG_REPLAY || first) {
303                     targets[bound] = 1;
304                     first = 0;
305                 }
306             }
307         } else {
308             bound = find_severity(buffer);
309             targets[bound] = 1;
310         }
311         buffer = cont;
312     }
313 }
314
315 static void
316 log_parse_cross(const char *buffer, struct string_list *types, char sevset[LOG_NUM_SEVERITIES])
317 {
318     char *dup, *sep;
319
320     dup = strdup(buffer);
321     sep = strchr(dup, '.');
322     *sep++ = 0;
323     log_parse_logset(dup, types);
324     log_parse_sevset(sep, sevset);
325     free(dup);
326 }
327
328 static void
329 log_parse_options(struct log_type *type, struct dict *conf)
330 {
331     const char *opt;
332     opt = database_get_data(conf, "max_age", RECDB_QSTRING);
333     if (opt)
334         type->max_age = ParseInterval(opt);
335     opt = database_get_data(conf, "max_count", RECDB_QSTRING);
336     if (opt)
337         type->max_count = strtoul(opt, NULL, 10);
338 }
339
340 static void
341 log_conf_read(void)
342 {
343     struct record_data *rd, *rd2;
344     dict_iterator_t it;
345     const char *sep;
346     struct log_type *type;
347     enum log_severity sev;
348     unsigned int ii;
349
350     close_logs();
351     dict_delete(log_dests);
352
353     log_dests = dict_new();
354     dict_set_free_keys(log_dests, free);
355
356     rd = conf_get_node("logs");
357     if (rd && (rd->type == RECDB_OBJECT)) {
358         for (it = dict_first(rd->d.object); it; it = iter_next(it)) {
359             if ((sep = strchr(iter_key(it), '.'))) {
360                 struct logList logList;
361                 char sevset[LOG_NUM_SEVERITIES];
362                 struct string_list *slist;
363
364                 /* It looks like a <type>.<severity> record.  Try to parse it. */
365                 slist = alloc_string_list(4);
366                 log_parse_cross(iter_key(it), slist, sevset);
367                 logList.size = 0;
368                 logList_open(&logList, iter_data(it));
369                 for (ii = 0; ii < slist->used; ++ii) {
370                     type = log_register_type(slist->list[ii], NULL);
371                     for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev) {
372                         if (!sevset[sev]) continue;
373                         logList_join(&type->logs[sev], &logList);
374                     }
375                 }
376                 logList_close(&logList);
377                 free_string_list(slist);
378             } else if ((rd2 = iter_data(it))
379                        && (rd2->type == RECDB_OBJECT)
380                        && (type = log_register_type(iter_key(it), NULL))) {
381                 log_parse_options(type, rd2->d.object);
382             } else {
383                 log_module(MAIN_LOG, LOG_ERROR, "Unknown logs subkey '%s'.", iter_key(it));
384             }
385         }
386     }
387     if (log_debugged)
388         log_debug();
389 }
390
391 void
392 log_debug(void)
393 {
394     enum log_severity sev;
395     struct logDestination *log_stdout;
396     struct logList target;
397
398     log_stdout = log_open("std:out");
399     logList_init(&target);
400     logList_append(&target, log_stdout);
401
402     for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev)
403         logList_join(&log_default->logs[sev], &target);
404
405     logList_close(&target);
406     log_debugged = 1;
407 }
408
409 void
410 log_reopen(void)
411 {
412     dict_iterator_t it;
413     for (it = dict_first(log_dests); it; it = iter_next(it)) {
414         struct logDestination *ld = iter_data(it);
415         ld->vtbl->reopen(ld);
416     }
417 }
418
419 struct log_type *
420 log_register_type(const char *name, const char *default_log)
421 {
422     struct log_type *type;
423     struct logDestination *dest;
424     enum log_severity sev;
425
426     if (!(type = dict_find(log_types, name, NULL))) {
427         type = calloc(1, sizeof(*type));
428         type->name = strdup(name);
429         type->max_age = 600;
430         type->max_count = 1024;
431         dict_insert(log_types, type->name, type);
432     }
433     if (default_log && !type->default_set) {
434         /* If any severity level was unspecified in the config, use the default. */
435         dest = NULL;
436         for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev) {
437             if (sev == LOG_REPLAY)
438                 continue; /* never default LOG_REPLAY */
439             if (!type->logs[sev].size) {
440                 logList_init(&type->logs[sev]);
441                 if (!dest) {
442                     if (!(dest = log_open(default_log)))
443                         break;
444                     dest->refcnt--;
445                 }
446                 logList_append(&type->logs[sev], dest);
447                 dest->refcnt++;
448             }
449         }
450         type->default_set = 1;
451     }
452     return type;
453 }
454
455 /* logging functions */
456
457 void
458 log_audit(struct log_type *type, enum log_severity sev, struct userNode *user, struct userNode *bot, const char *channel_name, unsigned int flags, const char *command)
459 {
460     struct logEntry *entry;
461     unsigned int size, ii;
462     char *str_next;
463
464     /* First make sure severity is appropriate */
465     if ((sev != LOG_COMMAND) && (sev != LOG_OVERRIDE) && (sev != LOG_STAFF)) {
466         log_module(MAIN_LOG, LOG_ERROR, "Illegal audit severity %d", sev);
467         return;
468     }
469     /* Allocate and fill in the log entry */
470     size = sizeof(*entry) + strlen(user->nick) + strlen(command) + 2;
471     if (user->handle_info)
472         size += strlen(user->handle_info->handle) + 1;
473     if (channel_name)
474         size += strlen(channel_name) + 1;
475     if (flags & AUDIT_HOSTMASK)
476         size += strlen(user->ident) + strlen(user->hostname) + 2;
477     entry = calloc(1, size);
478     str_next = (char*)(entry + 1);
479     entry->time = now;
480     entry->slvl = sev;
481     entry->bot = bot;
482     if (channel_name) {
483         size = strlen(channel_name) + 1;
484         entry->channel_name = memcpy(str_next, channel_name, size);
485         str_next += size;
486     }
487     if (true) {
488         size = strlen(user->nick) + 1;
489         entry->user_nick = memcpy(str_next, user->nick, size);
490         str_next += size;
491     }
492     if (user->handle_info) {
493         size = strlen(user->handle_info->handle) + 1;
494         entry->user_account = memcpy(str_next, user->handle_info->handle, size);
495         str_next += size;
496     }
497     if (flags & AUDIT_HOSTMASK) {
498         size = sprintf(str_next, "%s@%s", user->ident, user->hostname) + 1;
499         entry->user_hostmask = str_next;
500         str_next += size;
501     } else {
502         entry->user_hostmask = 0;
503     }
504     if (true) {
505         size = strlen(command) + 1;
506         entry->command = memcpy(str_next, command, size);
507         str_next += size;
508     }
509
510     /* fill in the default text for the event */
511     log_format_audit(entry);
512
513     /* insert into the linked list */
514     entry->next = 0;
515     entry->prev = type->log_newest;
516     if (type->log_newest)
517         type->log_newest->next = entry;
518     else
519         type->log_oldest = entry;
520     type->log_newest = entry;
521     type->log_count++;
522
523     /* remove old elements from the linked list */
524     while (type->log_count > type->max_count)
525         log_type_free_oldest(type);
526     while (type->log_oldest && (type->log_oldest->time + type->max_age < (unsigned long)now))
527         log_type_free_oldest(type);
528     if (type->log_oldest)
529         type->log_oldest->prev = 0;
530     else
531         type->log_newest = 0;
532
533     /* call the destination logs */
534     for (ii=0; ii<type->logs[sev].used; ++ii) {
535         struct logDestination *ld = type->logs[sev].list[ii];
536         ld->vtbl->log_audit(ld, type, entry);
537     }
538     for (ii=0; ii<log_default->logs[sev].used; ++ii) {
539         struct logDestination *ld = log_default->logs[sev].list[ii];
540         ld->vtbl->log_audit(ld, type, entry);
541     }
542 }
543
544 void
545 log_replay(struct log_type *type, int is_write, const char *line)
546 {
547     unsigned int ii;
548
549     for (ii=0; ii<type->logs[LOG_REPLAY].used; ++ii) {
550         struct logDestination *ld = type->logs[LOG_REPLAY].list[ii];
551         ld->vtbl->log_replay(ld, type, is_write, line);
552     }
553     for (ii=0; ii<log_default->logs[LOG_REPLAY].used; ++ii) {
554         struct logDestination *ld = log_default->logs[LOG_REPLAY].list[ii];
555         ld->vtbl->log_replay(ld, type, is_write, line);
556     }
557 }
558
559 void
560 log_module(struct log_type *type, enum log_severity sev, const char *format, ...)
561 {
562     char msgbuf[1024];
563     unsigned int ii;
564     va_list args;
565
566     if (sev > LOG_FATAL) {
567         log_module(MAIN_LOG, LOG_ERROR, "Illegal log_module severity %d", sev);
568         return;
569     }
570     va_start(args, format);
571     vsnprintf(msgbuf, sizeof(msgbuf), format, args);
572     va_end(args);
573     if (log_inited) {
574         for (ii=0; ii<type->logs[sev].used; ++ii) {
575             struct logDestination *ld = type->logs[sev].list[ii];
576             ld->vtbl->log_module(ld, type, sev, msgbuf);
577         }
578         for (ii=0; ii<log_default->logs[sev].used; ++ii) {
579             struct logDestination *ld = log_default->logs[sev].list[ii];
580             ld->vtbl->log_module(ld, type, sev, msgbuf);
581         }
582     } else {
583         /* Special behavior before we start full operation */
584         fprintf(stderr, "%s: %s\n", log_severity_names[sev], msgbuf);
585     }
586 }
587
588 /* audit log searching */
589
590 struct logSearch *
591 log_discrim_create(struct userNode *service, struct userNode *user, unsigned int argc, char *argv[])
592 {
593     unsigned int ii;
594     struct logSearch *discrim;
595
596     /* Assume all criteria require arguments. */
597     if((argc - 1) % 2)
598     {
599         send_message(user, service, "MSG_MISSING_PARAMS", argv[0]);
600         return NULL;
601     }
602
603     discrim = malloc(sizeof(struct logSearch));
604     memset(discrim, 0, sizeof(*discrim));
605     discrim->limit = 25;
606     discrim->max_time = INT_MAX;
607     discrim->severities = ~0;
608
609     for (ii=1; ii<argc-1; ii++) {
610         if (!irccasecmp(argv[ii], "bot")) {
611             struct userNode *bot = GetUserH(argv[++ii]);
612             if (!bot) {
613                 send_message(user, service, "MSG_NICK_UNKNOWN", argv[ii]);
614                 goto fail;
615             } else if (!IsLocal(bot)) {
616                 send_message(user, service, "MSG_NOT_A_SERVICE", argv[ii]);
617                 goto fail;
618             }
619             discrim->masks.bot = bot;
620         } else if (!irccasecmp(argv[ii], "channel")) {
621             discrim->masks.channel_name = argv[++ii];
622         } else if (!irccasecmp(argv[ii], "nick")) {
623             discrim->masks.user_nick = argv[++ii];
624         } else if (!irccasecmp(argv[ii], "account")) {
625             discrim->masks.user_account = argv[++ii];
626         } else if (!irccasecmp(argv[ii], "hostmask")) {
627             discrim->masks.user_hostmask = argv[++ii];
628         } else if (!irccasecmp(argv[ii], "command")) {
629             discrim->masks.command = argv[++ii];
630         } else if (!irccasecmp(argv[ii], "age")) {
631             const char *cmp = argv[++ii];
632             if (cmp[0] == '<') {
633                 if (cmp[1] == '=')
634                     discrim->min_time = now - ParseInterval(cmp+2);
635                 else
636                     discrim->min_time = now - (ParseInterval(cmp+1) - 1);
637             } else if (cmp[0] == '>') {
638                 if (cmp[1] == '=')
639                     discrim->max_time = now - ParseInterval(cmp+2);
640                 else
641                     discrim->max_time = now - (ParseInterval(cmp+1) - 1);
642             } else {
643                 discrim->min_time = now - ParseInterval(cmp+2);
644             }
645         } else if (!irccasecmp(argv[ii], "limit")) {
646             discrim->limit = strtoul(argv[++ii], NULL, 10);
647         } else if (!irccasecmp(argv[ii], "level")) {
648             char *severity = argv[++ii];
649             discrim->severities = 0;
650             while (1) {
651                 enum log_severity sev = find_severity(severity);
652                 if (sev == LOG_NUM_SEVERITIES) {
653                     send_message(user, service, "MSG_INVALID_SEVERITY", severity);
654                     goto fail;
655                 }
656                 discrim->severities |= 1 << sev;
657                 severity = strchr(severity, ',');
658                 if (!severity)
659                     break;
660                 severity++;
661             }
662         } else if (!irccasecmp(argv[ii], "type")) {
663             if (!(discrim->type = dict_find(log_types, argv[++ii], NULL))) {
664                 send_message(user, service, "MSG_INVALID_FACILITY", argv[ii]);
665                 goto fail;
666             }
667         } else {
668             send_message(user, service, "MSG_INVALID_CRITERIA", argv[ii]);
669             goto fail;
670         }
671     }
672
673     return discrim;
674   fail:
675     free(discrim);
676     return NULL;
677 }
678
679 static int
680 entry_match(struct logSearch *discrim, struct logEntry *entry)
681 {
682     if ((entry->time < discrim->min_time)
683         || (entry->time > discrim->max_time)
684         || !(discrim->severities & (1 << entry->slvl))
685         || (discrim->masks.bot && (discrim->masks.bot != entry->bot))
686         /* don't do glob matching, so that !events #a*b does not match #acb */
687         || (discrim->masks.channel_name
688             && (!entry->channel_name
689                 || irccasecmp(entry->channel_name, discrim->masks.channel_name)))
690         || (discrim->masks.user_nick
691             && !match_ircglob(entry->user_nick, discrim->masks.user_nick))
692         || (discrim->masks.user_account
693             && (!entry->user_account
694                 || !match_ircglob(entry->user_account, discrim->masks.user_account)))
695         || (discrim->masks.user_hostmask
696             && entry->user_hostmask
697             && !match_ircglob(entry->user_hostmask, discrim->masks.user_hostmask))
698         || (discrim->masks.command
699             && !match_ircglob(entry->command, discrim->masks.command))) {
700         return 0;
701     }
702     return 1;
703 }
704
705 void
706 log_report_entry(struct logEntry *match, void *extra)
707 {
708     struct logReport *rpt = extra;
709     send_message_type(4, rpt->user, rpt->reporter, "%s", match->default_desc);
710 }
711
712 unsigned int
713 log_entry_search(struct logSearch *discrim, entry_search_func esf, void *data)
714 {
715     unsigned int matched = 0;
716
717     if (discrim->type) {
718         struct logEntry *entry;
719
720         for (entry = discrim->type->log_oldest; entry; entry = entry->next) {
721             if (entry_match(discrim, entry)) {
722                 esf(entry, data);
723                 if (++matched >= discrim->limit)
724                     break;
725             }
726         }
727     } else {
728         dict_iterator_t it;
729
730         for (it = dict_first(log_types); it; it = iter_next(it)) {
731             discrim->type = iter_data(it);
732             matched += log_entry_search(discrim, esf, data);
733         }
734     }
735
736     return matched;
737 }
738
739 /* generic helper functions */
740
741 static void
742 log_format_timestamp(time_t when, struct string_buffer *sbuf)
743 {
744     struct tm local;
745     localtime_r(&when, &local);
746     if (sbuf->size < 24) {
747         sbuf->size = 24;
748         free(sbuf->list);
749         sbuf->list = calloc(1, 24);
750     }
751     sbuf->used = sprintf(sbuf->list, "[%02d:%02d:%02d %02d/%02d/%04d]", local.tm_hour, local.tm_min, local.tm_sec, local.tm_mon+1, local.tm_mday, local.tm_year+1900);
752 }
753
754 static void
755 log_format_audit(struct logEntry *entry)
756 {
757     struct string_buffer sbuf;
758     memset(&sbuf, 0, sizeof(sbuf));
759     log_format_timestamp(entry->time, &sbuf);
760     string_buffer_append_string(&sbuf, " (");
761     string_buffer_append_string(&sbuf, entry->bot->nick);
762     if (entry->channel_name) {
763         string_buffer_append(&sbuf, ':');
764         string_buffer_append_string(&sbuf, entry->channel_name);
765     }
766     string_buffer_append_string(&sbuf, ") [");
767     string_buffer_append_string(&sbuf, entry->user_nick);
768     if (entry->user_hostmask) {
769         string_buffer_append(&sbuf, '!');
770         string_buffer_append_string(&sbuf, entry->user_hostmask);
771     }
772     if (entry->user_account) {
773         string_buffer_append(&sbuf, ':');
774         string_buffer_append_string(&sbuf, entry->user_account);
775     }
776     string_buffer_append_string(&sbuf, "]: ");
777     string_buffer_append_string(&sbuf, entry->command);
778     entry->default_desc = strdup(sbuf.list);
779     free(sbuf.list);
780 }
781
782 /* shared stub log operations act as a noop */
783
784 static void
785 ldNop_reopen(UNUSED_ARG(struct logDestination *self_)) {
786     /* no operation necessary */
787 }
788
789 static void
790 ldNop_replay(UNUSED_ARG(struct logDestination *self_), UNUSED_ARG(struct log_type *type), UNUSED_ARG(int is_write), UNUSED_ARG(const char *line)) {
791     /* no operation necessary */
792 }
793
794 /* file: log type */
795
796 struct logDest_file {
797     struct logDestination base;
798     char *fname;
799     FILE *output;
800 };
801 static struct logDest_vtable ldFile_vtbl;
802
803 static struct logDestination *
804 ldFile_open(const char *args) {
805     struct logDest_file *ld;
806     ld = calloc(1, sizeof(*ld));
807     ld->base.vtbl = &ldFile_vtbl;
808     ld->fname = strdup(args);
809     ld->output = fopen(ld->fname, "a");
810     return &ld->base;
811 }
812
813 static void
814 ldFile_reopen(struct logDestination *self_) {
815     struct logDest_file *self = (struct logDest_file*)self_;
816     fclose(self->output);
817     self->output = fopen(self->fname, "a");
818 }
819
820 static void
821 ldFile_close(struct logDestination *self_) {
822     struct logDest_file *self = (struct logDest_file*)self_;
823     fclose(self->output);
824     free(self->fname);
825     free(self);
826 }
827
828 static void
829 ldFile_audit(struct logDestination *self_, UNUSED_ARG(struct log_type *type), struct logEntry *entry) {
830     struct logDest_file *self = (struct logDest_file*)self_;
831     fputs(entry->default_desc, self->output);
832     fputc('\n', self->output);
833     fflush(self->output);
834 }
835
836 static void
837 ldFile_replay(struct logDestination *self_, UNUSED_ARG(struct log_type *type), int is_write, const char *line) {
838     struct logDest_file *self = (struct logDest_file*)self_;
839     struct string_buffer sbuf;
840     memset(&sbuf, 0, sizeof(sbuf));
841     log_format_timestamp(now, &sbuf);
842     string_buffer_append_string(&sbuf, is_write ? "W: " : "   ");
843     string_buffer_append_string(&sbuf, line);
844     fputs(sbuf.list, self->output);
845     fputc('\n', self->output);
846     free(sbuf.list);
847     fflush(self->output);
848 }
849
850 static void
851 ldFile_module(struct logDestination *self_, struct log_type *type, enum log_severity sev, const char *message) {
852     struct logDest_file *self = (struct logDest_file*)self_;
853     struct string_buffer sbuf;
854     memset(&sbuf, 0, sizeof(sbuf));
855     log_format_timestamp(now, &sbuf);
856     fprintf(self->output, "%s (%s:%s) %s\n", sbuf.list, type->name, log_severity_names[sev], message);
857     free(sbuf.list);
858     fflush(self->output);
859 }
860
861 static struct logDest_vtable ldFile_vtbl = {
862     "file",
863     ldFile_open,
864     ldFile_reopen,
865     ldFile_close,
866     ldFile_audit,
867     ldFile_replay,
868     ldFile_module
869 };
870
871 /* std: log type */
872
873 static struct logDest_vtable ldStd_vtbl;
874
875 static struct logDestination *
876 ldStd_open(const char *args) {
877     struct logDest_file *ld;
878     ld = calloc(1, sizeof(*ld));
879     ld->base.vtbl = &ldStd_vtbl;
880     ld->fname = strdup(args);
881
882     /* Print to stderr if given "err" and default to stdout otherwise. */
883     if (atoi(args))
884         ld->output = fdopen(atoi(args), "a");
885     else if (!strcasecmp(args, "err"))
886         ld->output = stdout;
887     else
888         ld->output = stderr;
889
890     return &ld->base;
891 }
892
893 static void
894 ldStd_close(struct logDestination *self_) {
895     struct logDest_file *self = (struct logDest_file*)self_;
896     free(self->fname);
897     free(self);
898 }
899
900 static void
901 ldStd_replay(struct logDestination *self_, UNUSED_ARG(struct log_type *type), int is_write, const char *line) {
902     struct logDest_file *self = (struct logDest_file*)self_;
903     fprintf(self->output, "%s%s\n", is_write ? "W: " : "   ", line);
904 }
905
906 static void
907 ldStd_module(struct logDestination *self_, UNUSED_ARG(struct log_type *type), enum log_severity sev, const char *message) {
908     struct logDest_file *self = (struct logDest_file*)self_;
909     fprintf(self->output, "%s: %s\n", log_severity_names[sev], message);
910 }
911
912 static struct logDest_vtable ldStd_vtbl = {
913     "std",
914     ldStd_open,
915     ldNop_reopen,
916     ldStd_close,
917     ldFile_audit,
918     ldStd_replay,
919     ldStd_module
920 };
921
922 /* irc: log type */
923
924 struct logDest_irc {
925     struct logDestination base;
926     char *target;
927 };
928 static struct logDest_vtable ldIrc_vtbl;
929
930 static struct logDestination *
931 ldIrc_open(const char *args) {
932     struct logDest_irc *ld;
933     ld = calloc(1, sizeof(*ld));
934     ld->base.vtbl = &ldIrc_vtbl;
935     ld->target = strdup(args);
936     return &ld->base;
937 }
938
939 static void
940 ldIrc_close(struct logDestination *self_) {
941     struct logDest_irc *self = (struct logDest_irc*)self_;
942     free(self->target);
943     free(self);
944 }
945
946 static void
947 ldIrc_audit(struct logDestination *self_, UNUSED_ARG(struct log_type *type), struct logEntry *entry) {
948     struct logDest_irc *self = (struct logDest_irc*)self_;
949
950     if (entry->channel_name) {
951         send_target_message(4, self->target, entry->bot, "(%s", strchr(strchr(entry->default_desc, ' '), ':')+1);
952     } else {
953         send_target_message(4, self->target, entry->bot, "%s", strchr(entry->default_desc, ')')+2);
954     }
955 }
956
957 static void
958 ldIrc_module(struct logDestination *self_, struct log_type *type, enum log_severity sev, const char *message) {
959     struct logDest_irc *self = (struct logDest_irc*)self_;
960     extern struct userNode *opserv;
961
962     send_target_message(4, self->target, opserv, "%s %s: %s\n", type->name, log_severity_names[sev], message);
963 }
964
965 static struct logDest_vtable ldIrc_vtbl = {
966     "irc",
967     ldIrc_open,
968     ldNop_reopen,
969     ldIrc_close,
970     ldIrc_audit,
971     ldNop_replay, /* totally ignore this - it would be a recipe for disaster */
972     ldIrc_module
973 };
974
975 void
976 log_init(void)
977 {
978     log_types = dict_new();
979     dict_set_free_keys(log_types, free);
980     dict_set_free_data(log_types, log_type_free);
981     log_dest_types = dict_new();
982     /* register log types */
983     dict_insert(log_dest_types, ldFile_vtbl.type_name, &ldFile_vtbl);
984     dict_insert(log_dest_types, ldStd_vtbl.type_name, &ldStd_vtbl);
985     dict_insert(log_dest_types, ldIrc_vtbl.type_name, &ldIrc_vtbl);
986     conf_register_reload(log_conf_read);
987     log_default = log_register_type("*", NULL);
988     reg_exit_func(cleanup_logs);
989     message_register_table(msgtab);
990     log_inited = 1;
991 }