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