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