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