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