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