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