b4ceb05bd81514cac9cade01cea1bdca33cb04ac
[srvx.git] / src / helpfile.c
1 /* helpfile.c - Help file loading and display
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 "helpfile.h"
23 #include "log.h"
24 #include "modcmd.h"
25 #include "nickserv.h"
26 #include "spamserv.h"
27
28 #if defined(HAVE_DIRENT_H)
29 #include <dirent.h>
30 #endif
31
32 #if defined(HAVE_SYS_STAT_H)
33 #include <sys/stat.h>
34 #endif
35
36 static const struct message_entry msgtab[] = {
37     { "HFMSG_MISSING_HELPFILE", "The help file could not be found.  Sorry!" },
38     { "HFMSG_HELP_NOT_STRING", "Help file error (help data was not a string)." },
39     { NULL, NULL }
40 };
41
42 #define DEFAULT_LINE_SIZE       MAX_LINE_SIZE
43 #define DEFAULT_TABLE_SIZE      80
44
45 extern struct userNode *global, *chanserv, *opserv, *nickserv, *spamserv;
46 struct userNode *message_dest;
47 struct userNode *message_source;
48 struct language *lang_C;
49 struct dict *languages;
50
51 static void language_cleanup(void)
52 {
53     dict_delete(languages);
54 }
55
56 static void language_free_helpfile(void *data)
57 {
58     struct helpfile *hf = data;
59     close_helpfile(hf);
60 }
61
62 static void language_free(void *data)
63 {
64     struct language *lang = data;
65     dict_delete(lang->messages);
66     dict_delete(lang->helpfiles);
67     free(lang->name);
68     free(lang);
69 }
70
71 static struct language *language_alloc(const char *name)
72 {
73     struct language *lang = calloc(1, sizeof(*lang));
74     lang->name = strdup(name);
75     lang->parent = lang_C;
76     if (!languages) {
77         languages = dict_new();
78         dict_set_free_data(languages, language_free);
79     }
80     dict_insert(languages, lang->name, lang);
81     return lang;
82 }
83
84 /* Language names should use a lang or lang_COUNTRY type system, where
85  * lang is a two-letter code according to ISO-639-1 (or three-letter
86  * code according to ISO-639-2 for languages not in ISO-639-1), and
87  * COUNTRY is the ISO 3166 country code in all upper case.
88  *
89  * See also:
90  * http://www.loc.gov/standards/iso639-2/
91  * http://www.loc.gov/standards/iso639-2/langhome.html
92  * http://www.iso.ch/iso/en/prods-services/iso3166ma/index.html
93  */
94 struct language *language_find(const char *name)
95 {
96     struct language *lang;
97     char alt_name[MAXLEN];
98     const char *uscore;
99
100     if ((lang = dict_find(languages, name, NULL)))
101         return lang;
102     if ((uscore = strchr(name, '_'))) {
103         strncpy(alt_name, name, uscore-name);
104         alt_name[uscore-name] = 0;
105         if ((lang = dict_find(languages, alt_name, NULL)))
106             return lang;
107     }
108     if (!lang_C) {
109         lang_C = language_alloc("C");
110         lang_C->messages = dict_new();
111         lang_C->helpfiles = dict_new();
112     }
113     return lang_C;
114 }
115
116 static void language_set_messages(struct language *lang, dict_t dict)
117 {
118     dict_iterator_t it, it2;
119     struct record_data *rd;
120     char *msg;
121     int extra, missing;
122
123     extra = missing = 0;
124     for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it; ) {
125         const char *msgid = iter_key(it);
126         int diff = it2 ? irccasecmp(msgid, iter_key(it2)) : -1;
127         if (diff < 0) {
128             extra++;
129             it = iter_next(it);
130             continue;
131         } else if (diff > 0) {
132             missing++;
133             it2 = iter_next(it2);
134             continue;
135         }
136         rd = iter_data(it);
137         switch (rd->type) {
138         case RECDB_QSTRING:
139             msg = strdup(rd->d.qstring);
140             break;
141         case RECDB_STRING_LIST:
142             /* XXX: maybe do an unlistify_help() type thing */
143         default:
144             log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
145             continue;
146         }
147         dict_insert(lang->messages, strdup(msgid), msg);
148         it = iter_next(it);
149         it2 = iter_next(it2);
150     }
151     while (it2) {
152         missing++;
153         it2 = iter_next(it2);
154     }
155     if (extra || missing)
156         log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages.", lang->name, extra, missing);
157 }
158
159 static struct language *language_read(const char *name)
160 {
161     DIR *dir;
162     struct dirent *dirent;
163     struct language *lang;
164     struct helpfile *hf;
165     char filename[MAXLEN], *uscore;
166     FILE *file;
167     dict_t dict;
168
169     /* Never try to read the C language from disk. */
170     if (!irccasecmp(name, "C"))
171         return lang_C;
172
173     /* Open the directory stream; if we can't, fail. */
174     snprintf(filename, sizeof(filename), "languages/%s", name);
175     if (!(dir = opendir(filename))) {
176         log_module(MAIN_LOG, LOG_ERROR, "Unable to open language directory languages/%s: %s", name, strerror(errno));
177         return NULL;
178     }
179     if (!(lang = dict_find(languages, name, NULL)))
180         lang = language_alloc(name);
181
182     /* Find the parent language. */
183     snprintf(filename, sizeof(filename), "languages/%s/parent", name);
184     if (!(file = fopen(filename, "r"))
185         || !fgets(filename, sizeof(filename), file)) {
186         strcpy(filename, "C");
187     }
188     if (!(lang->parent = language_find(filename))) {
189         uscore = strchr(filename, '_');
190         if (uscore) {
191             *uscore = 0;
192             lang->parent = language_find(filename);
193         }
194         if (!lang->parent)
195             lang->parent = lang_C;
196     }
197
198     /* (Re-)initialize the language's dicts. */
199     dict_delete(lang->messages);
200     lang->messages = dict_new();
201     dict_set_free_keys(lang->messages, free);
202     dict_set_free_data(lang->messages, free);
203     lang->helpfiles = dict_new();
204     dict_set_free_data(lang->helpfiles, language_free_helpfile);
205
206     /* Read all the translations from the directory. */
207     while ((dirent = readdir(dir))) {
208         snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
209         if (!strcmp(dirent->d_name, "parent")) {
210             continue;
211         } else if (!strcmp(dirent->d_name, "strings.db")) {
212             dict = parse_database(filename);
213             language_set_messages(lang, dict);
214             free_database(dict);
215         } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
216             hf = open_helpfile(filename, hf->expand);
217             dict_insert(lang->helpfiles, hf->name, hf);
218         }
219     }
220
221     /* All done. */
222     closedir(dir);
223     return lang;
224 }
225
226 static void language_read_list(void)
227 {
228     struct stat sbuf;
229     struct dirent *dirent;
230     DIR *dir;
231     char namebuf[MAXLEN];
232
233     if (!(dir = opendir("languages")))
234         return;
235     while ((dirent = readdir(dir))) {
236         if (dirent->d_name[0] == '.')
237             continue;
238         snprintf(namebuf, sizeof(namebuf), "languages/%s", dirent->d_name);
239         if (!strcmp(dirent->d_name, "strings.db")) {
240             continue;
241         }
242         if (stat(namebuf, &sbuf) < 0) {
243             log_module(MAIN_LOG, LOG_INFO, "Skipping language entry '%s' (unable to stat).", dirent->d_name);
244             continue;
245         }
246         if (!S_ISDIR(sbuf.st_mode)) {
247             log_module(MAIN_LOG, LOG_INFO, "Skipping language entry '%s' (not directory).", dirent->d_name);
248             continue;
249         }
250         if (!dict_find(languages, dirent->d_name, NULL))
251             language_alloc(dirent->d_name);
252     }
253     closedir(dir);
254 }
255
256 const char *language_find_message(struct language *lang, const char *msgid) {
257     struct language *curr;
258     const char *msg;
259     if (!lang)
260         lang = lang_C;
261     for (curr = lang; curr; curr = curr->parent)
262         if ((msg = dict_find(curr->messages, msgid, NULL)))
263             return msg;
264     log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
265     return NULL;
266 }
267
268 void
269 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
270     unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
271     char line[MAX_LINE_SIZE+1];
272     struct handle_info *hi;
273
274     if (IsChannelName(to) || *to == '$') {
275         message_dest = NULL;
276         hi = NULL;
277     } else {
278         message_dest = GetUserH(to);
279         if (!message_dest) {
280             log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
281             return;
282         }
283         hi = message_dest->handle_info;
284 #ifdef WITH_PROTOCOL_P10
285         to = message_dest->numeric;
286 #endif
287     }
288     message_source = from;
289
290     /* If size or irc_send are 0, we should try to use a default. */
291     if (size)
292         {} /* keep size */
293     else if (!hi)
294         size = DEFAULT_TABLE_SIZE;
295     else if (hi->table_width)
296         size = hi->table_width;
297     else if (hi->screen_width)
298         size = hi->screen_width;
299     else
300         size = DEFAULT_TABLE_SIZE;
301
302     if (irc_send)
303         {} /* use that function */
304     else if (hi)
305         irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
306     else
307         irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
308
309     /* Limit size to how much we can show at once */
310     if (size > sizeof(line))
311         size = sizeof(line);
312
313     /* Figure out how wide columns should be */
314     max_width = alloca(table.width * sizeof(int));
315     for (jj=tot_width=0; jj<table.width; jj++) {
316         /* Find the widest width for this column */
317         max_width[jj] = 0;
318         for (ii=0; ii<table.length; ii++) {
319             len = strlen(table.contents[ii][jj]);
320             if (len > max_width[jj])
321                 max_width[jj] = len;
322         }
323         /* Separate columns with spaces */
324         tot_width += max_width[jj] + 1;
325     }
326     /* How many rows to put in a line? */
327     if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
328         nreps = size / tot_width;
329     else
330         nreps = 1;
331     /* Send headers line.. */
332     if (table.flags & TABLE_NO_HEADERS) {
333         ii = 0;
334     } else {
335         /* Sending headers needs special treatment: either show them
336          * once, or repeat them as many times as we repeat the columns
337          * in a row. */
338         for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
339             for (jj=0; 1; ) {
340                 len = strlen(table.contents[0][jj]);
341                 spaces = max_width[jj] - len;
342                 if (table.flags & TABLE_PAD_LEFT)
343                     while (spaces--)
344                         line[pos++] = ' ';
345                 memcpy(line+pos, table.contents[0][jj], len);
346                 pos += len;
347                 if (++jj == table.width)
348                     break;
349                 if (!(table.flags & TABLE_PAD_LEFT))
350                     while (spaces--)
351                         line[pos++] = ' ';
352                 line[pos++] = ' ';
353             }
354         }
355         line[pos] = 0;
356         irc_send(from, to, line);
357         ii = 1;
358     }
359     /* Send the table. */
360     for (jj=0, pos=0, reps=0; ii<table.length; ) {
361         while (1) {
362             len = strlen(table.contents[ii][jj]);
363             spaces = max_width[jj] - len;
364             if (table.flags & TABLE_PAD_LEFT)
365                 while (spaces--) line[pos++] = ' ';
366             memcpy(line+pos, table.contents[ii][jj], len);
367             pos += len;
368             if (++jj == table.width) {
369                 jj = 0, ++ii, ++reps;
370                 if ((reps == nreps) || (ii == table.length)) {
371                     line[pos] = 0;
372                     irc_send(from, to, line);
373                     pos = reps = 0;
374                     break;
375                 }
376             }
377             if (!(table.flags & TABLE_PAD_LEFT))
378                 while (spaces--)
379                     line[pos++] = ' ';
380             line[pos++] = ' ';
381         }
382     }
383     if (!(table.flags & TABLE_NO_FREE)) {
384         /* Deallocate table memory (but not the string memory). */
385         for (ii=0; ii<table.length; ii++)
386             free(table.contents[ii]);
387         free(table.contents);
388     }
389 }
390
391 static int
392 vsend_message(const char *dest, struct userNode *src, struct handle_info *handle, int msg_type, expand_func_t expand_f, const char *format, va_list al)
393 {
394     void (*irc_send)(struct userNode *from, const char *to, const char *msg);
395     static struct string_buffer input;
396     unsigned int size, ipos, pos, length, chars_sent, use_color;
397     unsigned int expand_pos, expand_ipos, newline_ipos;
398     char line[MAX_LINE_SIZE];
399
400     if (IsChannelName(dest) || *dest == '$') {
401         message_dest = NULL;
402     } else if (!(message_dest = GetUserH(dest))) {
403         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
404         return 0;
405     } else if (message_dest->dead) {
406         /* No point in sending to a user who is leaving. */
407         return 0;
408     } else {
409 #ifdef WITH_PROTOCOL_P10
410         dest = message_dest->numeric;
411 #endif
412     }
413     message_source = src;
414     if (!(msg_type & MSG_TYPE_NOXLATE)
415         && !(format = handle_find_message(handle, format)))
416         return 0;
417     /* fill in a buffer with the string */
418     input.used = 0;
419     string_buffer_append_vprintf(&input, format, al);
420
421     /* figure out how to send the messages */
422     if (handle) {
423         msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
424         use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
425         size = handle->screen_width;
426         if (size > sizeof(line))
427             size = sizeof(line);
428     } else {
429         size = sizeof(line);
430         use_color = 1;
431     }
432     if (!size || !(msg_type & MSG_TYPE_MULTILINE))
433         size = DEFAULT_LINE_SIZE;
434     switch (msg_type & 3) {
435         case 0:
436             irc_send = irc_notice;
437             break;
438         case 2:
439             irc_send = irc_wallchops;
440             break;
441         case 1:
442         default:
443             irc_send = irc_privmsg;
444     }
445
446     /* This used to be two passes, but if you do that and allow
447      * arbitrary sizes for ${}-expansions (as with help indexes),
448      * that requires a very big intermediate buffer.
449      */
450     expand_ipos = newline_ipos = ipos = 0;
451     expand_pos = pos = 0;
452     chars_sent = 0;
453     while (input.list[ipos]) {
454         char ch, *value, *free_value;
455
456         while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
457             line[pos++] = ch;
458             ipos++;
459         }
460
461         if (!input.list[ipos])
462             goto send_line;
463         if (input.list[ipos] == '\n') {
464             ipos++;
465             goto send_line;
466         }
467         if (pos == size) {
468             unsigned int new_ipos;
469             /* Scan backwards for a space in the input, until we hit
470              * either the last newline or the last variable expansion.
471              * Print the line up to that point, and start from there.
472              */
473             for (new_ipos = ipos;
474                  (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
475                  --new_ipos)
476                 if (input.list[new_ipos] == ' ')
477                     break;
478             pos -= ipos - new_ipos;
479             if (new_ipos == newline_ipos) {
480                 /* Single word was too big to fit on one line; skip
481                  * forward to its end and print it as a whole.
482                  */
483                 while (input.list[new_ipos]
484                        && (input.list[new_ipos] != ' ')
485                        && (input.list[new_ipos] != '\n')
486                        && (input.list[new_ipos] != '$'))
487                     line[pos++] = input.list[new_ipos++];
488             }
489             ipos = new_ipos;
490             while (input.list[ipos] == ' ')
491                 ipos++;
492             goto send_line;
493         }
494
495         free_value = 0;
496         switch (input.list[++ipos]) {
497         /* Literal '$' or end of string. */
498         case 0:
499             ipos--;
500         case '$':
501             value = "$";
502             break;
503         /* The following two expand to mIRC color codes if enabled
504            by the user. */
505         case 'b':
506             value = use_color ? "\002" : "";
507             break;
508         case 'o':
509             value = use_color ? "\017" : "";
510             break;
511         case 'r':
512             value = use_color ? "\026" : "";
513             break;
514         case 'u':
515             value = use_color ? "\037" : "";
516             break;
517         /* Service nicks. */
518         case 'S':
519             value = src->nick;
520             break;
521         case 'G':
522             value = global ? global->nick : "Global";
523             break;
524         case 'C':
525             value = chanserv ? chanserv->nick : "ChanServ";
526             break;
527         case 'O':
528             value = opserv ? opserv->nick : "OpServ";
529             break;
530         case 'N':
531             value = nickserv ? nickserv->nick : "NickServ";
532             break;
533         case 'X':
534             value = spamserv ? spamserv->nick : "SpamServ";
535             break;
536         case 's':
537             value = self->name;
538             break;
539         case 'H':
540             value = handle ? handle->handle : "Account";
541             break;
542 #define SEND_LINE(TRUNCED) do { \
543     line[pos] = 0; \
544     if (pos > 0) { \
545         if (!(msg_type & MSG_TYPE_MULTILINE) && (pos > 1) && TRUNCED) \
546             line[pos-2] = line[pos-1] = '.'; \
547         irc_send(src, dest, line); \
548     } \
549     chars_sent += pos; \
550     pos = 0; \
551     newline_ipos = ipos; \
552     if (!(msg_type & MSG_TYPE_MULTILINE)) return chars_sent; \
553 } while (0)
554         /* Custom expansion handled by helpfile-specific function. */
555         case '{':
556         case '(': {
557             struct helpfile_expansion exp;
558             char *name_end = input.list + ipos + 1, *colon = NULL;
559
560             while (*name_end != '}' && *name_end != ')' && *name_end) {
561                 if (*name_end == ':') {
562                     colon = name_end;
563                     *colon = '\0';
564                 }
565                 name_end++;
566             }
567             if (!*name_end)
568                 goto fallthrough;
569             *name_end = '\0';
570             if (colon) {
571                 struct module *module = module_find(input.list + ipos + 1);
572                 if (module && module->expand_help)
573                     exp = module->expand_help(colon + 1);
574                 else {
575                     *colon = ':';
576                     goto fallthrough;
577                 }
578             } else if (expand_f)
579                 exp = expand_f(input.list + ipos + 1);
580             else
581                 goto fallthrough;
582             switch (exp.type) {
583             case HF_STRING:
584                 free_value = value = exp.value.str;
585                 if (!value)
586                     value = "";
587                 break;
588             case HF_TABLE:
589                 /* Must send current line, then emit table. */
590                 SEND_LINE(0);
591                 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
592                 value = "";
593                 break;
594             default:
595                 value = "";
596                 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, (void*)expand_f);
597                 break;
598             }
599             ipos = name_end - input.list;
600             break;
601         }
602         default:
603         fallthrough:
604             value = alloca(3);
605             value[0] = '$';
606             value[1] = input.list[ipos];
607             value[2] = 0;
608         }
609         ipos++;
610         while ((pos + strlen(value) > size) || strchr(value, '\n')) {
611             unsigned int avail;
612             avail = size - pos - 1;
613             length = strcspn(value, "\n ");
614             if (length <= avail) {
615                 strncpy(line+pos, value, length);
616                 pos += length;
617                 value += length;
618                 /* copy over spaces, until (possible) end of line */
619                 while (*value == ' ') {
620                     if (pos < size-1)
621                         line[pos++] = *value;
622                     value++;
623                 }
624             } else {
625                 /* word to send is too big to send now.. what to do? */
626                 if (pos > 0) {
627                     /* try to put it on a separate line */
628                     SEND_LINE(1);
629                 } else {
630                     /* already at start of line; only send part of it */
631                     strncpy(line, value, avail);
632                     pos += avail;
633                     value += length;
634                     /* skip any trailing spaces */
635                     while (*value == ' ')
636                         value++;
637                 }
638             }
639             /* if we're looking at a newline, send the accumulated text */
640             if (*value == '\n') {
641                 SEND_LINE(0);
642                 value++;
643             }
644         }
645         length = strlen(value);
646         memcpy(line + pos, value, length);
647         if (free_value)
648             free(free_value);
649         pos += length;
650         if ((pos < size-1) && input.list[ipos]) {
651             expand_pos = pos;
652             expand_ipos = ipos;
653             continue;
654         }
655       send_line:
656         expand_pos = pos;
657         expand_ipos = ipos;
658         SEND_LINE(0);
659 #undef SEND_LINE
660     }
661     return chars_sent;
662 }
663
664 int
665 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
666 {
667     int res;
668     va_list ap;
669
670     if (IsLocal(dest) && !IsDummy(dest)) return 0;
671     va_start(ap, format);
672     res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
673     va_end(ap);
674     return res;
675 }
676
677 int
678 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
679     int res;
680     va_list ap;
681
682     if (IsLocal(dest) && !IsDummy(dest)) return 0;
683     va_start(ap, format);
684     res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
685     va_end(ap);
686     return res;
687 }
688
689 int
690 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
691 {
692     int res;
693     va_list ap;
694
695     va_start(ap, format);
696     res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
697     va_end(ap);
698     return res;
699 }
700
701 int
702 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
703 {
704     int res;
705
706     va_list ap;
707     va_start(ap, format);
708     res = vsend_message(dest->nick, src, dest->handle_info, 12, expand, format, ap);
709     va_end(ap);
710     return res;
711 }
712
713 int
714 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
715 {
716     struct helpfile *lang_hf;
717     struct record_data *rec;
718     struct language *curr;
719
720     if (!topic)
721         topic = "<index>";
722     if (!hf) {
723         _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
724         return 0;
725     }
726     for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
727          curr;
728          curr = curr->parent) {
729         lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
730         if (!lang_hf)
731             continue;
732         rec = dict_find(lang_hf->db, topic, NULL);
733         if (rec && rec->type == RECDB_QSTRING)
734             return _send_help(dest, src, hf->expand, rec->d.qstring);
735     }
736     rec = dict_find(hf->db, "<missing>", NULL);
737     if (!rec)
738         return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
739     if (rec->type != RECDB_QSTRING)
740         return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
741     return _send_help(dest, src, hf->expand, rec->d.qstring);
742 }
743
744 /* Grammar supported by this parser:
745  * condition = expr | prefix expr
746  * expr = atomicexpr | atomicexpr op atomicexpr
747  * op = '&&' | '||' | 'and' | 'or'
748  * atomicexpr = '(' expr ')' | identifier
749  * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
750  *
751  * Whitespace is ignored. The parser is implemented as a recursive
752  * descent parser by functions like:
753  *   static int helpfile_eval_<element>(const char *start, const char **end);
754  */
755
756 enum helpfile_op {
757     OP_INVALID,
758     OP_BOOL_AND,
759     OP_BOOL_OR
760 };
761
762 static const struct {
763     const char *str;
764     enum helpfile_op op;
765 } helpfile_operators[] = {
766     { "&&", OP_BOOL_AND },
767     { "and", OP_BOOL_AND },
768     { "||", OP_BOOL_OR },
769     { "or", OP_BOOL_OR },
770     { NULL, OP_INVALID }
771 };
772
773 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
774
775 static int helpfile_eval_expr(const char *start, const char **end);
776 static int helpfile_eval_atomicexpr(const char *start, const char **end);
777 static int helpfile_eval_identifier(const char *start, const char **end);
778
779 static int
780 helpfile_eval_identifier(const char *start, const char **end)
781 {
782     /* Skip leading whitespace. */
783     while (isspace(*start) && (start < *end))
784         start++;
785     if (start == *end) {
786         log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
787         return -1;
788     }
789
790     if (start[0] == '!') {
791         int res = helpfile_eval_identifier(start+1, end);
792         if (res < 0)
793             return res;
794         return !res;
795     } else if (start[0] == '/') {
796         const char *sep;
797         char *id_str, *value;
798
799         for (sep = start;
800              strchr(identifier_chars, sep[0]) && (sep < *end);
801              ++sep) ;
802         memcpy(id_str = alloca(sep+1-start), start, sep-start);
803         id_str[sep-start] = '\0';
804         value = conf_get_data(id_str+1, RECDB_QSTRING);
805         *end = sep;
806         if (!value)
807             return 0;
808         return enabled_string(value) || true_string(value);
809     } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
810         *end = start + 4;
811         return 1;
812     } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
813         *end = start + 5;
814         return 0;
815     } else {
816         log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", (int)(*end-start), start);
817         return -1;
818     }
819 }
820
821 static int
822 helpfile_eval_atomicexpr(const char *start, const char **end)
823 {
824     const char *sep;
825     int res;
826
827     /* Skip leading whitespace. */
828     while (isspace(*start) && (start < *end))
829         start++;
830     if (start == *end) {
831         log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
832         return -1;
833     }
834
835     /* If it's not parenthesized, it better be a valid identifier. */
836     if (*start != '(')
837         return helpfile_eval_identifier(start, end);
838
839     /* Parse the internal expression. */
840     start++;
841     sep = *end;
842     res = helpfile_eval_expr(start, &sep);
843
844     /* Check for the closing parenthesis. */
845     while (isspace(*sep) && (sep < *end))
846         sep++;
847     if ((sep == *end) || (sep[0] != ')')) {
848         log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", (int)(*end-sep), sep);
849         return -1;
850     }
851
852     /* Report the end location and result. */
853     *end = sep + 1;
854     return res;
855 }
856
857 static int
858 helpfile_eval_expr(const char *start, const char **end)
859 {
860     const char *sep, *sep2;
861     unsigned int ii, len;
862     int res_a, res_b;
863     enum helpfile_op op;
864
865     /* Parse the first atomicexpr. */
866     sep = *end;
867     res_a = helpfile_eval_atomicexpr(start, &sep);
868     if (res_a < 0)
869         return res_a;
870
871     /* Figure out what follows that. */
872     while (isspace(*sep) && (sep < *end))
873         sep++;
874     if (sep == *end)
875         return res_a;
876     op = OP_INVALID;
877     for (ii = 0; helpfile_operators[ii].str; ++ii) {
878         len = strlen(helpfile_operators[ii].str);
879         if (ircncasecmp(sep, helpfile_operators[ii].str, len))
880             continue;
881         op = helpfile_operators[ii].op;
882         sep += len;
883     }
884     if (op == OP_INVALID) {
885         log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", (int)(*end-sep), sep);
886         return -1;
887     }
888
889     /* Parse the next atomicexpr. */
890     sep2 = *end;
891     res_b = helpfile_eval_atomicexpr(sep, &sep2);
892     if (res_b < 0)
893         return res_b;
894
895     /* Make sure there's no trailing garbage */
896     while (isspace(*sep2) && (sep2 < *end))
897         sep2++;
898     if (sep2 != *end) {
899         log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", (int)(*end-sep2), sep2);
900         return -1;
901     }
902
903     /* Record where we stopped parsing. */
904     *end = sep2;
905
906     /* Do the logic on the subexpressions. */
907     switch (op) {
908     case OP_BOOL_AND:
909         return res_a && res_b;
910     case OP_BOOL_OR:
911         return res_a || res_b;
912     default:
913         return -1;
914     }
915 }
916
917 static int
918 helpfile_eval_condition(const char *start, const char **end)
919 {
920     const char *term;
921
922     /* Skip the prefix if there is one. */
923     for (term = start; isalnum(*term) && (term < *end); ++term) ;
924     if (term != start) {
925         if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
926             log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", (int)(*end-start), start);
927             return -1;
928         }
929         start = term + 2;
930     }
931
932     /* Evaluate the remaining string as an expression. */
933     return helpfile_eval_expr(start, end);
934 }
935
936 static int
937 unlistify_help(const char *key, void *data, void *extra)
938 {
939     struct record_data *rd = data;
940     dict_t newdb = extra;
941
942     switch (rd->type) {
943     case RECDB_QSTRING:
944         dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
945         return 0;
946     case RECDB_STRING_LIST: {
947         struct string_list *slist = GET_RECORD_STRING_LIST(rd);
948         char *dest;
949         unsigned int totlen, len, i;
950
951         for (i=totlen=0; i<slist->used; i++)
952             totlen = totlen + strlen(slist->list[i]) + 1;
953         dest = alloca(totlen+1);
954         for (i=totlen=0; i<slist->used; i++) {
955             len = strlen(slist->list[i]);
956             memcpy(dest+totlen, slist->list[i], len);
957             dest[totlen+len] = '\n';
958             totlen = totlen + len + 1;
959         }
960         dest[totlen] = 0;
961         dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
962         return 0;
963     }
964     case RECDB_OBJECT: {
965         dict_iterator_t it;
966
967         for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
968             const char *k2, *end;
969             int res;
970
971             /* Evaluate the expression for this subentry. */
972             k2 = iter_key(it);
973             end = k2 + strlen(k2);
974             res = helpfile_eval_condition(k2, &end);
975             /* If the evaluation failed, bail. */
976             if (res < 0) {
977                 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
978                 return 1;
979             }
980             /* If the condition was false, try another. */
981             if (!res)
982                 continue;
983             /* If we cannot unlistify the contents, bail. */
984             if (unlistify_help(key, iter_data(it), extra))
985                 return 1;
986             return 0;
987         }
988         /* If none of the conditions apply, just omit the entry. */
989         return 0;
990     }
991     default:
992         return 1;
993     }
994 }
995
996 struct helpfile *
997 open_helpfile(const char *fname, expand_func_t expand)
998 {
999     struct helpfile *hf;
1000     char *slash;
1001     dict_t db = parse_database(fname);
1002     hf = calloc(1, sizeof(*hf));
1003     hf->expand = expand;
1004     hf->db = alloc_database();
1005     dict_set_free_keys(hf->db, free);
1006     if ((slash = strrchr(fname, '/'))) {
1007         hf->name = strdup(slash + 1);
1008     } else {
1009         hf->name = strdup(fname);
1010         dict_insert(language_find("C")->helpfiles, hf->name, hf);
1011     }
1012     if (db) {
1013         dict_foreach(db, unlistify_help, hf->db);
1014         free_database(db);
1015     }
1016     return hf;
1017 }
1018
1019 void close_helpfile(struct helpfile *hf)
1020 {
1021     if (!hf)
1022         return;
1023     free((char*)hf->name);
1024     free_database(hf->db);
1025     free(hf);
1026 }
1027
1028 void message_register_table(const struct message_entry *table)
1029 {
1030     if (!lang_C)
1031         language_find("C");
1032     while (table->msgid) {
1033         dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1034         table++;
1035     }
1036 }
1037
1038 void helpfile_init(void)
1039 {
1040     message_register_table(msgtab);
1041     language_read_list();
1042 }
1043
1044 static void helpfile_read_languages(void)
1045 {
1046     dict_iterator_t it;
1047     dict_t dict;
1048
1049     language_read_list();
1050     for (it = dict_first(languages); it; it = iter_next(it))
1051         language_read(iter_key(it));
1052
1053     /* If the user has a strings.db in their languages directory,
1054      * allow that to override C language strings.
1055      */
1056     dict = parse_database("languages/strings.db");
1057     if (dict) {
1058         language_set_messages(lang_C, dict);
1059         free_database(dict);
1060     }
1061 }
1062
1063 void helpfile_finalize(void)
1064 {
1065     conf_register_reload(helpfile_read_languages);
1066     reg_exit_func(language_cleanup);
1067 }