Merge branch 'HostServ' of ssh://git.pk910.de:16110/srvx into HostServ
[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_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     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 'A':
540             value = handle ? handle->handle : "Account";
541             break;
542         case 'U':
543             value = message_dest ? message_dest->nick : "Nick";
544             break;
545         case 'I':
546             value = message_dest ? (IsFakeIdent(message_dest) ? message_dest->fakeident : message_dest->ident) : "Ident";
547             break;
548         case 'H':
549             value = message_dest ? (IsFakeHost(message_dest) ? message_dest->fakehost : message_dest->hostname) : "Hostname";
550             break;
551 #define SEND_LINE(TRUNCED) do { \
552     line[pos] = 0; \
553     if (pos > 0) { \
554         if (!(msg_type & MSG_TYPE_MULTILINE) && (pos > 1) && TRUNCED) \
555             line[pos-2] = line[pos-1] = '.'; \
556         irc_send(src, dest, line); \
557     } \
558     chars_sent += pos; \
559     pos = 0; \
560     newline_ipos = ipos; \
561     if (!(msg_type & MSG_TYPE_MULTILINE)) return chars_sent; \
562 } while (0)
563         /* Custom expansion handled by helpfile-specific function. */
564         case '{':
565         case '(': {
566             struct helpfile_expansion exp;
567             char *name_end = input.list + ipos + 1, *colon = NULL;
568
569             while (*name_end != '}' && *name_end != ')' && *name_end) {
570                 if (*name_end == ':') {
571                     colon = name_end;
572                     *colon = '\0';
573                 }
574                 name_end++;
575             }
576             if (!*name_end)
577                 goto fallthrough;
578             *name_end = '\0';
579             if (colon) {
580                 struct module *module = module_find(input.list + ipos + 1);
581                 if (module && module->expand_help)
582                     exp = module->expand_help(colon + 1);
583                 else {
584                     *colon = ':';
585                     goto fallthrough;
586                 }
587             } else if (expand_f)
588                 exp = expand_f(input.list + ipos + 1);
589             else
590                 goto fallthrough;
591             switch (exp.type) {
592             case HF_STRING:
593                 free_value = value = exp.value.str;
594                 if (!value)
595                     value = "";
596                 break;
597             case HF_TABLE:
598                 /* Must send current line, then emit table. */
599                 SEND_LINE(0);
600                 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
601                 value = "";
602                 break;
603             default:
604                 value = "";
605                 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, (void*)expand_f);
606                 break;
607             }
608             ipos = name_end - input.list;
609             break;
610         }
611         default:
612         fallthrough:
613             value = alloca(3);
614             value[0] = '$';
615             value[1] = input.list[ipos];
616             value[2] = 0;
617         }
618         ipos++;
619         while ((pos + strlen(value) > size) || strchr(value, '\n')) {
620             unsigned int avail;
621             avail = size - pos - 1;
622             length = strcspn(value, "\n ");
623             if (length <= avail) {
624                 strncpy(line+pos, value, length);
625                 pos += length;
626                 value += length;
627                 /* copy over spaces, until (possible) end of line */
628                 while (*value == ' ') {
629                     if (pos < size-1)
630                         line[pos++] = *value;
631                     value++;
632                 }
633             } else {
634                 /* word to send is too big to send now.. what to do? */
635                 if (pos > 0) {
636                     /* try to put it on a separate line */
637                     SEND_LINE(1);
638                 } else {
639                     /* already at start of line; only send part of it */
640                     strncpy(line, value, avail);
641                     pos += avail;
642                     value += length;
643                     /* skip any trailing spaces */
644                     while (*value == ' ')
645                         value++;
646                 }
647             }
648             /* if we're looking at a newline, send the accumulated text */
649             if (*value == '\n') {
650                 SEND_LINE(0);
651                 value++;
652             }
653         }
654         length = strlen(value);
655         memcpy(line + pos, value, length);
656         if (free_value)
657             free(free_value);
658         pos += length;
659         if ((pos < size-1) && input.list[ipos]) {
660             expand_ipos = ipos;
661             continue;
662         }
663       send_line:
664         expand_ipos = ipos;
665         SEND_LINE(0);
666 #undef SEND_LINE
667     }
668     return chars_sent;
669 }
670
671 int
672 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
673 {
674     int res;
675     va_list ap;
676
677     if (IsLocal(dest) && !IsDummy(dest)) return 0;
678     va_start(ap, format);
679     res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
680     va_end(ap);
681     return res;
682 }
683
684 int
685 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
686     int res;
687     va_list ap;
688
689     if (IsLocal(dest) && !IsDummy(dest)) return 0;
690     va_start(ap, format);
691     res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
692     va_end(ap);
693     return res;
694 }
695
696 int
697 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
698 {
699     int res;
700     va_list ap;
701
702     va_start(ap, format);
703     res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
704     va_end(ap);
705     return res;
706 }
707
708 int
709 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
710 {
711     int res;
712
713     va_list ap;
714     va_start(ap, format);
715     res = vsend_message(dest->nick, src, dest->handle_info, 12, expand, format, ap);
716     va_end(ap);
717     return res;
718 }
719
720 int
721 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
722 {
723     struct helpfile *lang_hf;
724     struct record_data *rec;
725     struct language *curr;
726
727     if (!topic)
728         topic = "<index>";
729     if (!hf) {
730         _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
731         return 0;
732     }
733     for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
734          curr;
735          curr = curr->parent) {
736         lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
737         if (!lang_hf)
738             continue;
739         rec = dict_find(lang_hf->db, topic, NULL);
740         if (rec && rec->type == RECDB_QSTRING)
741             return _send_help(dest, src, hf->expand, rec->d.qstring);
742     }
743     rec = dict_find(hf->db, "<missing>", NULL);
744     if (!rec)
745         return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
746     if (rec->type != RECDB_QSTRING)
747         return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
748     return _send_help(dest, src, hf->expand, rec->d.qstring);
749 }
750
751 /* Grammar supported by this parser:
752  * condition = expr | prefix expr
753  * expr = atomicexpr | atomicexpr op atomicexpr
754  * op = '&&' | '||' | 'and' | 'or'
755  * atomicexpr = '(' expr ')' | identifier
756  * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
757  *
758  * Whitespace is ignored. The parser is implemented as a recursive
759  * descent parser by functions like:
760  *   static int helpfile_eval_<element>(const char *start, const char **end);
761  */
762
763 enum helpfile_op {
764     OP_INVALID,
765     OP_BOOL_AND,
766     OP_BOOL_OR
767 };
768
769 static const struct {
770     const char *str;
771     enum helpfile_op op;
772 } helpfile_operators[] = {
773     { "&&", OP_BOOL_AND },
774     { "and", OP_BOOL_AND },
775     { "||", OP_BOOL_OR },
776     { "or", OP_BOOL_OR },
777     { NULL, OP_INVALID }
778 };
779
780 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
781
782 static int helpfile_eval_expr(const char *start, const char **end);
783 static int helpfile_eval_atomicexpr(const char *start, const char **end);
784 static int helpfile_eval_identifier(const char *start, const char **end);
785
786 static int
787 helpfile_eval_identifier(const char *start, const char **end)
788 {
789     /* Skip leading whitespace. */
790     while (isspace(*start) && (start < *end))
791         start++;
792     if (start == *end) {
793         log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
794         return -1;
795     }
796
797     if (start[0] == '!') {
798         int res = helpfile_eval_identifier(start+1, end);
799         if (res < 0)
800             return res;
801         return !res;
802     } else if (start[0] == '/') {
803         const char *sep;
804         char *id_str, *value;
805
806         for (sep = start;
807              strchr(identifier_chars, sep[0]) && (sep < *end);
808              ++sep) ;
809         memcpy(id_str = alloca(sep+1-start), start, sep-start);
810         id_str[sep-start] = '\0';
811         value = conf_get_data(id_str+1, RECDB_QSTRING);
812         *end = sep;
813         if (!value)
814             return 0;
815         return enabled_string(value) || true_string(value);
816     } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
817         *end = start + 4;
818         return 1;
819     } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
820         *end = start + 5;
821         return 0;
822     } else {
823         log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", (int)(*end-start), start);
824         return -1;
825     }
826 }
827
828 static int
829 helpfile_eval_atomicexpr(const char *start, const char **end)
830 {
831     const char *sep;
832     int res;
833
834     /* Skip leading whitespace. */
835     while (isspace(*start) && (start < *end))
836         start++;
837     if (start == *end) {
838         log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
839         return -1;
840     }
841
842     /* If it's not parenthesized, it better be a valid identifier. */
843     if (*start != '(')
844         return helpfile_eval_identifier(start, end);
845
846     /* Parse the internal expression. */
847     start++;
848     sep = *end;
849     res = helpfile_eval_expr(start, &sep);
850
851     /* Check for the closing parenthesis. */
852     while (isspace(*sep) && (sep < *end))
853         sep++;
854     if ((sep == *end) || (sep[0] != ')')) {
855         log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", (int)(*end-sep), sep);
856         return -1;
857     }
858
859     /* Report the end location and result. */
860     *end = sep + 1;
861     return res;
862 }
863
864 static int
865 helpfile_eval_expr(const char *start, const char **end)
866 {
867     const char *sep, *sep2;
868     unsigned int ii, len;
869     int res_a, res_b;
870     enum helpfile_op op;
871
872     /* Parse the first atomicexpr. */
873     sep = *end;
874     res_a = helpfile_eval_atomicexpr(start, &sep);
875     if (res_a < 0)
876         return res_a;
877
878     /* Figure out what follows that. */
879     while (isspace(*sep) && (sep < *end))
880         sep++;
881     if (sep == *end)
882         return res_a;
883     op = OP_INVALID;
884     for (ii = 0; helpfile_operators[ii].str; ++ii) {
885         len = strlen(helpfile_operators[ii].str);
886         if (ircncasecmp(sep, helpfile_operators[ii].str, len))
887             continue;
888         op = helpfile_operators[ii].op;
889         sep += len;
890     }
891     if (op == OP_INVALID) {
892         log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", (int)(*end-sep), sep);
893         return -1;
894     }
895
896     /* Parse the next atomicexpr. */
897     sep2 = *end;
898     res_b = helpfile_eval_atomicexpr(sep, &sep2);
899     if (res_b < 0)
900         return res_b;
901
902     /* Make sure there's no trailing garbage */
903     while (isspace(*sep2) && (sep2 < *end))
904         sep2++;
905     if (sep2 != *end) {
906         log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", (int)(*end-sep2), sep2);
907         return -1;
908     }
909
910     /* Record where we stopped parsing. */
911     *end = sep2;
912
913     /* Do the logic on the subexpressions. */
914     switch (op) {
915     case OP_BOOL_AND:
916         return res_a && res_b;
917     case OP_BOOL_OR:
918         return res_a || res_b;
919     default:
920         return -1;
921     }
922 }
923
924 static int
925 helpfile_eval_condition(const char *start, const char **end)
926 {
927     const char *term;
928
929     /* Skip the prefix if there is one. */
930     for (term = start; isalnum(*term) && (term < *end); ++term) ;
931     if (term != start) {
932         if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
933             log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", (int)(*end-start), start);
934             return -1;
935         }
936         start = term + 2;
937     }
938
939     /* Evaluate the remaining string as an expression. */
940     return helpfile_eval_expr(start, end);
941 }
942
943 static int
944 unlistify_help(const char *key, void *data, void *extra)
945 {
946     struct record_data *rd = data;
947     dict_t newdb = extra;
948
949     switch (rd->type) {
950     case RECDB_QSTRING:
951         dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
952         return 0;
953     case RECDB_STRING_LIST: {
954         struct string_list *slist = GET_RECORD_STRING_LIST(rd);
955         char *dest;
956         unsigned int totlen, len, i;
957
958         for (i=totlen=0; i<slist->used; i++)
959             totlen = totlen + strlen(slist->list[i]) + 1;
960         dest = alloca(totlen+1);
961         for (i=totlen=0; i<slist->used; i++) {
962             len = strlen(slist->list[i]);
963             memcpy(dest+totlen, slist->list[i], len);
964             dest[totlen+len] = '\n';
965             totlen = totlen + len + 1;
966         }
967         dest[totlen] = 0;
968         dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
969         return 0;
970     }
971     case RECDB_OBJECT: {
972         dict_iterator_t it;
973
974         for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
975             const char *k2, *end;
976             int res;
977
978             /* Evaluate the expression for this subentry. */
979             k2 = iter_key(it);
980             end = k2 + strlen(k2);
981             res = helpfile_eval_condition(k2, &end);
982             /* If the evaluation failed, bail. */
983             if (res < 0) {
984                 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
985                 return 1;
986             }
987             /* If the condition was false, try another. */
988             if (!res)
989                 continue;
990             /* If we cannot unlistify the contents, bail. */
991             if (unlistify_help(key, iter_data(it), extra))
992                 return 1;
993             return 0;
994         }
995         /* If none of the conditions apply, just omit the entry. */
996         return 0;
997     }
998     default:
999         return 1;
1000     }
1001 }
1002
1003 struct helpfile *
1004 open_helpfile(const char *fname, expand_func_t expand)
1005 {
1006     struct helpfile *hf;
1007     char *slash;
1008     dict_t db = parse_database(fname);
1009     hf = calloc(1, sizeof(*hf));
1010     hf->expand = expand;
1011     hf->db = alloc_database();
1012     dict_set_free_keys(hf->db, free);
1013     if ((slash = strrchr(fname, '/'))) {
1014         hf->name = strdup(slash + 1);
1015     } else {
1016         hf->name = strdup(fname);
1017         dict_insert(language_find("C")->helpfiles, hf->name, hf);
1018     }
1019     if (db) {
1020         dict_foreach(db, unlistify_help, hf->db);
1021         free_database(db);
1022     }
1023     return hf;
1024 }
1025
1026 void close_helpfile(struct helpfile *hf)
1027 {
1028     if (!hf)
1029         return;
1030     free((char*)hf->name);
1031     free_database(hf->db);
1032     free(hf);
1033 }
1034
1035 void message_register_table(const struct message_entry *table)
1036 {
1037     if (!lang_C)
1038         language_find("C");
1039     while (table->msgid) {
1040         dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1041         table++;
1042     }
1043 }
1044
1045 void helpfile_init(void)
1046 {
1047     message_register_table(msgtab);
1048     language_read_list();
1049 }
1050
1051 static void helpfile_read_languages(void)
1052 {
1053     dict_iterator_t it;
1054     dict_t dict;
1055
1056     language_read_list();
1057     for (it = dict_first(languages); it; it = iter_next(it))
1058         language_read(iter_key(it));
1059
1060     /* If the user has a strings.db in their languages directory,
1061      * allow that to override C language strings.
1062      */
1063     dict = parse_database("languages/strings.db");
1064     if (dict) {
1065         language_set_messages(lang_C, dict);
1066         free_database(dict);
1067     }
1068 }
1069
1070 void helpfile_finalize(void)
1071 {
1072     conf_register_reload(helpfile_read_languages);
1073     reg_exit_func(language_cleanup);
1074 }