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