ChanServ seen fixes; other cleanups
[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 | '>=' SEVLIT | SEVLIT ',' 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             if (buffer[0] == '=')
309                 buffer++;
310             bound = find_severity(buffer);
311             targets[bound] = 1;
312         }
313         buffer = cont;
314     }
315 }
316
317 static void
318 log_parse_cross(const char *buffer, struct string_list *types, char sevset[LOG_NUM_SEVERITIES])
319 {
320     char *dup, *sep;
321
322     dup = strdup(buffer);
323     sep = strchr(dup, '.');
324     *sep++ = 0;
325     log_parse_logset(dup, types);
326     log_parse_sevset(sep, sevset);
327     free(dup);
328 }
329
330 static void
331 log_parse_options(struct log_type *type, struct dict *conf)
332 {
333     const char *opt;
334     opt = database_get_data(conf, "max_age", RECDB_QSTRING);
335     if (opt)
336         type->max_age = ParseInterval(opt);
337     opt = database_get_data(conf, "max_count", RECDB_QSTRING);
338     if (opt)
339         type->max_count = strtoul(opt, NULL, 10);
340 }
341
342 static void
343 log_conf_read(void)
344 {
345     struct record_data *rd, *rd2;
346     dict_iterator_t it;
347     const char *sep;
348     struct log_type *type;
349     enum log_severity sev;
350     unsigned int ii;
351
352     close_logs();
353     dict_delete(log_dests);
354
355     log_dests = dict_new();
356     dict_set_free_keys(log_dests, free);
357
358     rd = conf_get_node("logs");
359     if (rd && (rd->type == RECDB_OBJECT)) {
360         for (it = dict_first(rd->d.object); it; it = iter_next(it)) {
361             if ((sep = strchr(iter_key(it), '.'))) {
362                 struct logList logList;
363                 char sevset[LOG_NUM_SEVERITIES];
364                 struct string_list *slist;
365
366                 /* It looks like a <type>.<severity> record.  Try to parse it. */
367                 slist = alloc_string_list(4);
368                 log_parse_cross(iter_key(it), slist, sevset);
369                 logList.size = 0;
370                 logList_open(&logList, iter_data(it));
371                 for (ii = 0; ii < slist->used; ++ii) {
372                     type = log_register_type(slist->list[ii], NULL);
373                     for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev) {
374                         if (!sevset[sev])
375                             continue;
376                         logList_join(&type->logs[sev], &logList);
377                     }
378                 }
379                 logList_close(&logList);
380                 free_string_list(slist);
381             } else if ((rd2 = iter_data(it))
382                        && (rd2->type == RECDB_OBJECT)
383                        && (type = log_register_type(iter_key(it), NULL))) {
384                 log_parse_options(type, rd2->d.object);
385             } else {
386                 log_module(MAIN_LOG, LOG_ERROR, "Unknown logs subkey '%s'.", iter_key(it));
387             }
388         }
389     }
390     if (log_debugged)
391         log_debug();
392 }
393
394 void
395 log_debug(void)
396 {
397     enum log_severity sev;
398     struct logDestination *log_stdout;
399     struct logList target;
400
401     log_stdout = log_open("std:out");
402     logList_init(&target);
403     logList_append(&target, log_stdout);
404
405     for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev)
406         logList_join(&log_default->logs[sev], &target);
407
408     logList_close(&target);
409     log_debugged = 1;
410 }
411
412 void
413 log_reopen(void)
414 {
415     dict_iterator_t it;
416     for (it = dict_first(log_dests); it; it = iter_next(it)) {
417         struct logDestination *ld = iter_data(it);
418         ld->vtbl->reopen(ld);
419     }
420 }
421
422 struct log_type *
423 log_register_type(const char *name, const char *default_log)
424 {
425     struct log_type *type;
426     struct logDestination *dest;
427     enum log_severity sev;
428
429     if (!(type = dict_find(log_types, name, NULL))) {
430         type = calloc(1, sizeof(*type));
431         type->name = strdup(name);
432         type->max_age = 600;
433         type->max_count = 1024;
434         dict_insert(log_types, type->name, type);
435     }
436     if (default_log && !type->default_set) {
437         /* If any severity level was unspecified in the config, use the default. */
438         dest = NULL;
439         for (sev = 0; sev < LOG_NUM_SEVERITIES; ++sev) {
440             if (sev == LOG_REPLAY)
441                 continue; /* never default LOG_REPLAY */
442             if (!type->logs[sev].size) {
443                 logList_init(&type->logs[sev]);
444                 if (!dest) {
445                     if (!(dest = log_open(default_log)))
446                         break;
447                     dest->refcnt--;
448                 }
449                 logList_append(&type->logs[sev], dest);
450                 dest->refcnt++;
451             }
452         }
453         type->default_set = 1;
454     }
455     return type;
456 }
457
458 /* logging functions */
459
460 void
461 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)
462 {
463     struct logEntry *entry;
464     unsigned int size, ii;
465     char *str_next;
466
467     /* First make sure severity is appropriate */
468     if ((sev != LOG_COMMAND) && (sev != LOG_OVERRIDE) && (sev != LOG_STAFF)) {
469         log_module(MAIN_LOG, LOG_ERROR, "Illegal audit severity %d", sev);
470         return;
471     }
472     /* Allocate and fill in the log entry */
473     size = sizeof(*entry) + strlen(user->nick) + strlen(command) + 2;
474     if (user->handle_info)
475         size += strlen(user->handle_info->handle) + 1;
476     if (channel_name)
477         size += strlen(channel_name) + 1;
478     if (flags & AUDIT_HOSTMASK)
479         size += strlen(user->ident) + strlen(user->hostname) + 2;
480     entry = calloc(1, size);
481     str_next = (char*)(entry + 1);
482     entry->time = now;
483     entry->slvl = sev;
484     entry->bot = bot;
485     if (channel_name) {
486         size = strlen(channel_name) + 1;
487         entry->channel_name = memcpy(str_next, channel_name, size);
488         str_next += size;
489     }
490     if (true) {
491         size = strlen(user->nick) + 1;
492         entry->user_nick = memcpy(str_next, user->nick, size);
493         str_next += size;
494     }
495     if (user->handle_info) {
496         size = strlen(user->handle_info->handle) + 1;
497         entry->user_account = memcpy(str_next, user->handle_info->handle, size);
498         str_next += size;
499     }
500     if (flags & AUDIT_HOSTMASK) {
501         size = sprintf(str_next, "%s@%s", user->ident, user->hostname) + 1;
502         entry->user_hostmask = str_next;
503         str_next += size;
504     } else {
505         entry->user_hostmask = 0;
506     }
507     if (true) {
508         size = strlen(command) + 1;
509         entry->command = memcpy(str_next, command, size);
510         str_next += size;
511     }
512
513     /* fill in the default text for the event */
514     log_format_audit(entry);
515
516     /* insert into the linked list */
517     entry->next = 0;
518     entry->prev = type->log_newest;
519     if (type->log_newest)
520         type->log_newest->next = entry;
521     else
522         type->log_oldest = entry;
523     type->log_newest = entry;
524     type->log_count++;
525
526     /* remove old elements from the linked list */
527     while (type->log_count > type->max_count)
528         log_type_free_oldest(type);
529     while (type->log_oldest && (type->log_oldest->time + type->max_age < (unsigned long)now))
530         log_type_free_oldest(type);
531     if (type->log_oldest)
532         type->log_oldest->prev = 0;
533     else
534         type->log_newest = 0;
535
536     /* call the destination logs */
537     for (ii=0; ii<type->logs[sev].used; ++ii) {
538         struct logDestination *ld = type->logs[sev].list[ii];
539         ld->vtbl->log_audit(ld, type, entry);
540     }
541     for (ii=0; ii<log_default->logs[sev].used; ++ii) {
542         struct logDestination *ld = log_default->logs[sev].list[ii];
543         ld->vtbl->log_audit(ld, type, entry);
544     }
545 }
546
547 void
548 log_replay(struct log_type *type, int is_write, const char *line)
549 {
550     unsigned int ii;
551
552     for (ii=0; ii<type->logs[LOG_REPLAY].used; ++ii) {
553         struct logDestination *ld = type->logs[LOG_REPLAY].list[ii];
554         ld->vtbl->log_replay(ld, type, is_write, line);
555     }
556     for (ii=0; ii<log_default->logs[LOG_REPLAY].used; ++ii) {
557         struct logDestination *ld = log_default->logs[LOG_REPLAY].list[ii];
558         ld->vtbl->log_replay(ld, type, is_write, line);
559     }
560 }
561
562 void
563 log_module(struct log_type *type, enum log_severity sev, const char *format, ...)
564 {
565     char msgbuf[1024];
566     unsigned int ii;
567     va_list args;
568
569     if (sev > LOG_FATAL) {
570         log_module(MAIN_LOG, LOG_ERROR, "Illegal log_module severity %d", sev);
571         return;
572     }
573     va_start(args, format);
574     vsnprintf(msgbuf, sizeof(msgbuf), format, args);
575     va_end(args);
576     if (log_inited) {
577         for (ii=0; ii<type->logs[sev].used; ++ii) {
578             struct logDestination *ld = type->logs[sev].list[ii];
579             ld->vtbl->log_module(ld, type, sev, msgbuf);
580         }
581         for (ii=0; ii<log_default->logs[sev].used; ++ii) {
582             struct logDestination *ld = log_default->logs[sev].list[ii];
583             ld->vtbl->log_module(ld, type, sev, msgbuf);
584         }
585     } else {
586         /* Special behavior before we start full operation */
587         fprintf(stderr, "%s: %s\n", log_severity_names[sev], msgbuf);
588     }
589 }
590
591 /* audit log searching */
592
593 struct logSearch *
594 log_discrim_create(struct userNode *service, struct userNode *user, unsigned int argc, char *argv[])
595 {
596     unsigned int ii;
597     struct logSearch *discrim;
598
599     /* Assume all criteria require arguments. */
600     if((argc - 1) % 2)
601     {
602         send_message(user, service, "MSG_MISSING_PARAMS", argv[0]);
603         return NULL;
604     }
605
606     discrim = malloc(sizeof(struct logSearch));
607     memset(discrim, 0, sizeof(*discrim));
608     discrim->limit = 25;
609     discrim->max_time = INT_MAX;
610     discrim->severities = ~0;
611
612     for (ii=1; ii<argc-1; ii++) {
613         if (!irccasecmp(argv[ii], "bot")) {
614             struct userNode *bot = GetUserH(argv[++ii]);
615             if (!bot) {
616                 send_message(user, service, "MSG_NICK_UNKNOWN", argv[ii]);
617                 goto fail;
618             } else if (!IsLocal(bot)) {
619                 send_message(user, service, "MSG_NOT_A_SERVICE", argv[ii]);
620                 goto fail;
621             }
622             discrim->masks.bot = bot;
623         } else if (!irccasecmp(argv[ii], "channel")) {
624             discrim->masks.channel_name = argv[++ii];
625         } else if (!irccasecmp(argv[ii], "nick")) {
626             discrim->masks.user_nick = argv[++ii];
627         } else if (!irccasecmp(argv[ii], "account")) {
628             discrim->masks.user_account = argv[++ii];
629         } else if (!irccasecmp(argv[ii], "hostmask")) {
630             discrim->masks.user_hostmask = argv[++ii];
631         } else if (!irccasecmp(argv[ii], "command")) {
632             discrim->masks.command = argv[++ii];
633         } else if (!irccasecmp(argv[ii], "age")) {
634             const char *cmp = argv[++ii];
635             if (cmp[0] == '<') {
636                 if (cmp[1] == '=')
637                     discrim->min_time = now - ParseInterval(cmp+2);
638                 else
639                     discrim->min_time = now - (ParseInterval(cmp+1) - 1);
640             } else if (cmp[0] == '>') {
641                 if (cmp[1] == '=')
642                     discrim->max_time = now - ParseInterval(cmp+2);
643                 else
644                     discrim->max_time = now - (ParseInterval(cmp+1) - 1);
645             } else {
646                 discrim->min_time = now - ParseInterval(cmp+2);
647             }
648         } else if (!irccasecmp(argv[ii], "limit")) {
649             discrim->limit = strtoul(argv[++ii], NULL, 10);
650         } else if (!irccasecmp(argv[ii], "level")) {
651             char *severity = argv[++ii];
652             discrim->severities = 0;
653             while (1) {
654                 enum log_severity sev = find_severity(severity);
655                 if (sev == LOG_NUM_SEVERITIES) {
656                     send_message(user, service, "MSG_INVALID_SEVERITY", severity);
657                     goto fail;
658                 }
659                 discrim->severities |= 1 << sev;
660                 severity = strchr(severity, ',');
661                 if (!severity)
662                     break;
663                 severity++;
664             }
665         } else if (!irccasecmp(argv[ii], "type")) {
666             if (!(discrim->type = dict_find(log_types, argv[++ii], NULL))) {
667                 send_message(user, service, "MSG_INVALID_FACILITY", argv[ii]);
668                 goto fail;
669             }
670         } else {
671             send_message(user, service, "MSG_INVALID_CRITERIA", argv[ii]);
672             goto fail;
673         }
674     }
675
676     return discrim;
677   fail:
678     free(discrim);
679     return NULL;
680 }
681
682 static int
683 entry_match(struct logSearch *discrim, struct logEntry *entry)
684 {
685     if ((entry->time < discrim->min_time)
686         || (entry->time > discrim->max_time)
687         || !(discrim->severities & (1 << entry->slvl))
688         || (discrim->masks.bot && (discrim->masks.bot != entry->bot))
689         /* don't do glob matching, so that !events #a*b does not match #acb */
690         || (discrim->masks.channel_name
691             && (!entry->channel_name
692                 || irccasecmp(entry->channel_name, discrim->masks.channel_name)))
693         || (discrim->masks.user_nick
694             && !match_ircglob(entry->user_nick, discrim->masks.user_nick))
695         || (discrim->masks.user_account
696             && (!entry->user_account
697                 || !match_ircglob(entry->user_account, discrim->masks.user_account)))
698         || (discrim->masks.user_hostmask
699             && entry->user_hostmask
700             && !match_ircglob(entry->user_hostmask, discrim->masks.user_hostmask))
701         || (discrim->masks.command
702             && !match_ircglob(entry->command, discrim->masks.command))) {
703         return 0;
704     }
705     return 1;
706 }
707
708 void
709 log_report_entry(struct logEntry *match, void *extra)
710 {
711     struct logReport *rpt = extra;
712     send_message_type(4, rpt->user, rpt->reporter, "%s", match->default_desc);
713 }
714
715 unsigned int
716 log_entry_search(struct logSearch *discrim, entry_search_func esf, void *data)
717 {
718     unsigned int matched = 0;
719
720     if (discrim->type) {
721         struct logEntry *entry;
722
723         for (entry = discrim->type->log_oldest; entry; entry = entry->next) {
724             if (entry_match(discrim, entry)) {
725                 esf(entry, data);
726                 if (++matched >= discrim->limit)
727                     break;
728             }
729         }
730     } else {
731         dict_iterator_t it;
732
733         for (it = dict_first(log_types); it; it = iter_next(it)) {
734             discrim->type = iter_data(it);
735             matched += log_entry_search(discrim, esf, data);
736         }
737     }
738
739     return matched;
740 }
741
742 /* generic helper functions */
743
744 static void
745 log_format_timestamp(time_t when, struct string_buffer *sbuf)
746 {
747     struct tm local;
748     localtime_r(&when, &local);
749     if (sbuf->size < 24) {
750         sbuf->size = 24;
751         free(sbuf->list);
752         sbuf->list = calloc(1, 24);
753     }
754     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);
755 }
756
757 static void
758 log_format_audit(struct logEntry *entry)
759 {
760     struct string_buffer sbuf;
761     memset(&sbuf, 0, sizeof(sbuf));
762     log_format_timestamp(entry->time, &sbuf);
763     string_buffer_append_string(&sbuf, " (");
764     string_buffer_append_string(&sbuf, entry->bot->nick);
765     if (entry->channel_name) {
766         string_buffer_append(&sbuf, ':');
767         string_buffer_append_string(&sbuf, entry->channel_name);
768     }
769     string_buffer_append_string(&sbuf, ") [");
770     string_buffer_append_string(&sbuf, entry->user_nick);
771     if (entry->user_hostmask) {
772         string_buffer_append(&sbuf, '!');
773         string_buffer_append_string(&sbuf, entry->user_hostmask);
774     }
775     if (entry->user_account) {
776         string_buffer_append(&sbuf, ':');
777         string_buffer_append_string(&sbuf, entry->user_account);
778     }
779     string_buffer_append_string(&sbuf, "]: ");
780     string_buffer_append_string(&sbuf, entry->command);
781     entry->default_desc = strdup(sbuf.list);
782     free(sbuf.list);
783 }
784
785 /* shared stub log operations act as a noop */
786
787 static void
788 ldNop_reopen(UNUSED_ARG(struct logDestination *self_)) {
789     /* no operation necessary */
790 }
791
792 static void
793 ldNop_replay(UNUSED_ARG(struct logDestination *self_), UNUSED_ARG(struct log_type *type), UNUSED_ARG(int is_write), UNUSED_ARG(const char *line)) {
794     /* no operation necessary */
795 }
796
797 /* file: log type */
798
799 struct logDest_file {
800     struct logDestination base;
801     char *fname;
802     FILE *output;
803 };
804 static struct logDest_vtable ldFile_vtbl;
805
806 static struct logDestination *
807 ldFile_open(const char *args) {
808     struct logDest_file *ld;
809     ld = calloc(1, sizeof(*ld));
810     ld->base.vtbl = &ldFile_vtbl;
811     ld->fname = strdup(args);
812     ld->output = fopen(ld->fname, "a");
813     return &ld->base;
814 }
815
816 static void
817 ldFile_reopen(struct logDestination *self_) {
818     struct logDest_file *self = (struct logDest_file*)self_;
819     fclose(self->output);
820     self->output = fopen(self->fname, "a");
821 }
822
823 static void
824 ldFile_close(struct logDestination *self_) {
825     struct logDest_file *self = (struct logDest_file*)self_;
826     fclose(self->output);
827     free(self->fname);
828     free(self);
829 }
830
831 static void
832 ldFile_audit(struct logDestination *self_, UNUSED_ARG(struct log_type *type), struct logEntry *entry) {
833     struct logDest_file *self = (struct logDest_file*)self_;
834     fputs(entry->default_desc, self->output);
835     fputc('\n', self->output);
836     fflush(self->output);
837 }
838
839 static void
840 ldFile_replay(struct logDestination *self_, UNUSED_ARG(struct log_type *type), int is_write, const char *line) {
841     struct logDest_file *self = (struct logDest_file*)self_;
842     struct string_buffer sbuf;
843     memset(&sbuf, 0, sizeof(sbuf));
844     log_format_timestamp(now, &sbuf);
845     string_buffer_append_string(&sbuf, is_write ? "W: " : "   ");
846     string_buffer_append_string(&sbuf, line);
847     fputs(sbuf.list, self->output);
848     fputc('\n', self->output);
849     free(sbuf.list);
850     fflush(self->output);
851 }
852
853 static void
854 ldFile_module(struct logDestination *self_, struct log_type *type, enum log_severity sev, const char *message) {
855     struct logDest_file *self = (struct logDest_file*)self_;
856     struct string_buffer sbuf;
857     memset(&sbuf, 0, sizeof(sbuf));
858     log_format_timestamp(now, &sbuf);
859     fprintf(self->output, "%s (%s:%s) %s\n", sbuf.list, type->name, log_severity_names[sev], message);
860     free(sbuf.list);
861     fflush(self->output);
862 }
863
864 static struct logDest_vtable ldFile_vtbl = {
865     "file",
866     ldFile_open,
867     ldFile_reopen,
868     ldFile_close,
869     ldFile_audit,
870     ldFile_replay,
871     ldFile_module
872 };
873
874 /* std: log type */
875
876 static struct logDest_vtable ldStd_vtbl;
877
878 static struct logDestination *
879 ldStd_open(const char *args) {
880     struct logDest_file *ld;
881     ld = calloc(1, sizeof(*ld));
882     ld->base.vtbl = &ldStd_vtbl;
883     ld->fname = strdup(args);
884
885     /* Print to stderr if given "err" and default to stdout otherwise. */
886     if (atoi(args))
887         ld->output = fdopen(atoi(args), "a");
888     else if (!strcasecmp(args, "err"))
889         ld->output = stdout;
890     else
891         ld->output = stderr;
892
893     return &ld->base;
894 }
895
896 static void
897 ldStd_close(struct logDestination *self_) {
898     struct logDest_file *self = (struct logDest_file*)self_;
899     free(self->fname);
900     free(self);
901 }
902
903 static void
904 ldStd_replay(struct logDestination *self_, UNUSED_ARG(struct log_type *type), int is_write, const char *line) {
905     struct logDest_file *self = (struct logDest_file*)self_;
906     fprintf(self->output, "%s%s\n", is_write ? "W: " : "   ", line);
907 }
908
909 static void
910 ldStd_module(struct logDestination *self_, UNUSED_ARG(struct log_type *type), enum log_severity sev, const char *message) {
911     struct logDest_file *self = (struct logDest_file*)self_;
912     fprintf(self->output, "%s: %s\n", log_severity_names[sev], message);
913 }
914
915 static struct logDest_vtable ldStd_vtbl = {
916     "std",
917     ldStd_open,
918     ldNop_reopen,
919     ldStd_close,
920     ldFile_audit,
921     ldStd_replay,
922     ldStd_module
923 };
924
925 /* irc: log type */
926
927 struct logDest_irc {
928     struct logDestination base;
929     char *target;
930 };
931 static struct logDest_vtable ldIrc_vtbl;
932
933 static struct logDestination *
934 ldIrc_open(const char *args) {
935     struct logDest_irc *ld;
936     ld = calloc(1, sizeof(*ld));
937     ld->base.vtbl = &ldIrc_vtbl;
938     ld->target = strdup(args);
939     return &ld->base;
940 }
941
942 static void
943 ldIrc_close(struct logDestination *self_) {
944     struct logDest_irc *self = (struct logDest_irc*)self_;
945     free(self->target);
946     free(self);
947 }
948
949 static void
950 ldIrc_audit(struct logDestination *self_, UNUSED_ARG(struct log_type *type), struct logEntry *entry) {
951     struct logDest_irc *self = (struct logDest_irc*)self_;
952
953     if (entry->channel_name) {
954         send_target_message(4, self->target, entry->bot, "(%s", strchr(strchr(entry->default_desc, ' '), ':')+1);
955     } else {
956         send_target_message(4, self->target, entry->bot, "%s", strchr(entry->default_desc, ')')+2);
957     }
958 }
959
960 static void
961 ldIrc_module(struct logDestination *self_, struct log_type *type, enum log_severity sev, const char *message) {
962     struct logDest_irc *self = (struct logDest_irc*)self_;
963     extern struct userNode *opserv;
964
965     send_target_message(4, self->target, opserv, "%s %s: %s\n", type->name, log_severity_names[sev], message);
966 }
967
968 static struct logDest_vtable ldIrc_vtbl = {
969     "irc",
970     ldIrc_open,
971     ldNop_reopen,
972     ldIrc_close,
973     ldIrc_audit,
974     ldNop_replay, /* totally ignore this - it would be a recipe for disaster */
975     ldIrc_module
976 };
977
978 void
979 log_init(void)
980 {
981     log_types = dict_new();
982     dict_set_free_keys(log_types, free);
983     dict_set_free_data(log_types, log_type_free);
984     log_dest_types = dict_new();
985     /* register log types */
986     dict_insert(log_dest_types, ldFile_vtbl.type_name, &ldFile_vtbl);
987     dict_insert(log_dest_types, ldStd_vtbl.type_name, &ldStd_vtbl);
988     dict_insert(log_dest_types, ldIrc_vtbl.type_name, &ldIrc_vtbl);
989     conf_register_reload(log_conf_read);
990     log_default = log_register_type("*", NULL);
991     reg_exit_func(cleanup_logs);
992     message_register_table(msgtab);
993     log_inited = 1;
994 }