]> jfr.im git - irc/evilnet/x3.git/blob - src/helpfile.c
Fixed header comments
[irc/evilnet/x3.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 x3.
5 *
6 * x3 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 log_module(MAIN_LOG, LOG_ERROR, "Unable to open language directory languages/%s: %s", name, strerror(errno));
176 return NULL;
177 }
178 if (!(lang = dict_find(languages, name, NULL)))
179 lang = language_alloc(name);
180
181 /* Find the parent language. */
182 snprintf(filename, sizeof(filename), "languages/%s/parent", name);
183 if (!(file = fopen(filename, "r"))
184 || !fgets(filename, sizeof(filename), file)) {
185 strcpy(filename, "C");
186 }
187 if (!(lang->parent = language_find(filename))) {
188 uscore = strchr(filename, '_');
189 if (uscore) {
190 *uscore = 0;
191 lang->parent = language_find(filename);
192 }
193 if (!lang->parent)
194 lang->parent = lang_C;
195 }
196
197 /* (Re-)initialize the language's dicts. */
198 dict_delete(lang->messages);
199 lang->messages = dict_new();
200 dict_set_free_keys(lang->messages, free);
201 dict_set_free_data(lang->messages, free);
202 lang->helpfiles = dict_new();
203 dict_set_free_data(lang->helpfiles, language_free_helpfile);
204
205 /* Read all the translations from the directory. */
206 while ((dirent = readdir(dir))) {
207 snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
208 if (!strcmp(dirent->d_name,"parent")) {
209 continue;
210 } else if (!strcmp(dirent->d_name, "strings.db")) {
211 dict = parse_database(filename);
212 language_set_messages(lang, dict);
213 free_database(dict);
214 } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
215 hf = open_helpfile(filename, hf->expand);
216 dict_insert(lang->helpfiles, hf->name, hf);
217 }
218 }
219
220 /* All done. */
221 closedir(dir);
222 return lang;
223 }
224
225 static void language_read_list(void)
226 {
227 struct stat sbuf;
228 struct dirent *dirent;
229 DIR *dir;
230 char namebuf[MAXLEN];
231
232 if (!(dir = opendir("languages")))
233 return;
234 while ((dirent = readdir(dir))) {
235 if (dirent->d_name[0] == '.')
236 continue;
237 snprintf(namebuf, sizeof(namebuf), "languages/%s", dirent->d_name);
238 if (stat(namebuf, &sbuf) < 0) {
239 log_module(MAIN_LOG, LOG_INFO, "Skipping language entry '%s' (unable to stat).", dirent->d_name);
240 continue;
241 }
242 if (!S_ISDIR(sbuf.st_mode)) {
243 log_module(MAIN_LOG, LOG_INFO, "Skipping language entry '%s' (not directory).", dirent->d_name);
244 continue;
245 }
246 language_alloc(dirent->d_name);
247 }
248 closedir(dir);
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 int strlen_vis(char *str)
264 {
265 int count;
266 for(count=0;*str;str++)
267 if(!iscntrl(*str))
268 count++;
269 return count;
270 }
271
272 void
273 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
274 unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
275 char line[MAX_LINE_SIZE+1];
276 struct handle_info *hi;
277 char *sepstr = NULL;
278 int sepsize = 0;
279
280 if (IsChannelName(to) || *to == '$') {
281 message_dest = NULL;
282 hi = NULL;
283 } else {
284 message_dest = GetUserH(to);
285 if (!message_dest) {
286 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
287 return;
288 }
289 hi = message_dest->handle_info;
290 #ifdef WITH_PROTOCOL_P10
291 to = message_dest->numeric;
292 #endif
293 }
294 message_source = from;
295
296 /* If size or irc_send are 0, we should try to use a default. */
297 if (size)
298 {} /* keep size */
299 else if (!hi)
300 size = DEFAULT_TABLE_SIZE;
301 else if (hi->table_width)
302 size = hi->table_width;
303 else if (hi->screen_width)
304 size = hi->screen_width;
305 else
306 size = DEFAULT_TABLE_SIZE;
307
308 if (irc_send)
309 {} /* use that function */
310 else if (hi)
311 irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
312 else
313 irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
314
315 /* Limit size to how much we can show at once */
316 if (size > sizeof(line))
317 size = sizeof(line);
318
319 /* Figure out how wide columns should be */
320 max_width = alloca(table.width * sizeof(int));
321 for (jj=tot_width=0; jj<table.width; jj++) {
322 /* Find the widest width for this column */
323 max_width[jj] = 0;
324 for (ii=0; ii<table.length; ii++) {
325 len = strlen(table.contents[ii][jj]);
326 if (len > max_width[jj])
327 max_width[jj] = len;
328 }
329 /* Separate columns with spaces */
330 tot_width += max_width[jj] + 1;
331 }
332 /* How many rows to put in a line? */
333 if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
334 nreps = size / tot_width;
335 else
336 nreps = 1;
337 /* Send headers line.. */
338 if (table.flags & TABLE_NO_HEADERS) {
339 ii = 0;
340 } else {
341 /* Sending headers needs special treatment: either show them
342 * once, or repeat them as many times as we repeat the columns
343 * in a row. */
344 for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
345 for (jj=0; 1; ) {
346 len = strlen(table.contents[0][jj]);
347 //line[pos++] = '\02'; /* bold header */
348 spaces = max_width[jj] - len;
349 if (table.flags & TABLE_PAD_LEFT)
350 while (spaces--)
351 line[pos++] = ' ';
352 memcpy(line+pos, table.contents[0][jj], len);
353 pos += len;
354 //line[pos++] = '\02'; /* end bold header */
355 if (++jj == table.width)
356 break;
357 if (!(table.flags & TABLE_PAD_LEFT))
358 while (spaces--)
359 line[pos++] = ' ';
360 line[pos++] = ' ';
361 }
362 }
363 line[pos] = 0;
364 sepsize = strlen_vis(line);
365 sepstr = malloc(sepsize + 1);
366 memset(sepstr, '-', sepsize);
367 sepstr[sepsize] = 0;
368 if(hi && hi->userlist_style != HI_STYLE_CLEAN)
369 irc_send(from, to, sepstr); /* ----------------- */
370 irc_send(from, to, line); /* alpha beta roe */
371 if(hi && hi->userlist_style != HI_STYLE_CLEAN)
372 irc_send(from, to, sepstr); /* ----------------- */
373 ii = 1;
374 }
375 /* Send the table. */
376 for (jj=0, pos=0, reps=0; ii<table.length; ) {
377 while (1) {
378 len = strlen(table.contents[ii][jj]);
379 spaces = max_width[jj] - len;
380 if (table.flags & TABLE_PAD_LEFT)
381 while (spaces--) line[pos++] = ' ';
382 memcpy(line+pos, table.contents[ii][jj], len);
383 pos += len;
384 if (++jj == table.width) {
385 jj = 0, ++ii, ++reps;
386 if ((reps == nreps) || (ii == table.length)) {
387 line[pos] = 0;
388 irc_send(from, to, line);
389 pos = reps = 0;
390 break;
391 }
392 }
393 if (!(table.flags & TABLE_PAD_LEFT))
394 while (spaces--)
395 line[pos++] = ' ';
396 line[pos++] = ' ';
397 }
398 }
399 if (!(table.flags & TABLE_NO_HEADERS)) {
400 /* Send end bar & free its memory */
401 if(sepsize > 5)
402 {
403 sepstr[sepsize/2-1] = 'E';
404 sepstr[sepsize/2] = 'n';
405 sepstr[sepsize/2+1]= 'd';
406 }
407
408 if(hi && hi->userlist_style != HI_STYLE_CLEAN)
409 irc_send(from, to, sepstr);
410 free(sepstr);
411 }
412
413 if (!(table.flags & TABLE_NO_FREE)) {
414 /* Deallocate table memory (but not the string memory). */
415 for (ii=0; ii<table.length; ii++)
416 free(table.contents[ii]);
417 free(table.contents);
418 }
419 }
420
421 static int
422 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)
423 {
424 void (*irc_send)(struct userNode *from, const char *to, const char *msg);
425 static struct string_buffer input;
426 unsigned int size, ipos, pos, length, chars_sent, use_color;
427 unsigned int expand_pos, expand_ipos, newline_ipos;
428 char line[MAX_LINE_SIZE];
429
430 if (IsChannelName(dest) || *dest == '$') {
431 message_dest = NULL;
432 } else if (!(message_dest = GetUserH(dest))) {
433 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
434 return 0;
435 } else if (message_dest->dead) {
436 /* No point in sending to a user who is leaving. */
437 return 0;
438 } else {
439 #ifdef WITH_PROTOCOL_P10
440 dest = message_dest->numeric;
441 #endif
442 }
443 message_source = src;
444 if (!(msg_type & MSG_TYPE_NOXLATE)
445 && !(format = handle_find_message(handle, format)))
446 return 0;
447 /* fill in a buffer with the string */
448 input.used = 0;
449 string_buffer_append_vprintf(&input, format, al);
450
451 /* figure out how to send the messages */
452 if (handle) {
453 msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
454 use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
455 size = handle->screen_width;
456 if (size > sizeof(line))
457 size = sizeof(line);
458 } else {
459 size = sizeof(line);
460 use_color = 1;
461 }
462 if (!size || !(msg_type & MSG_TYPE_MULTILINE))
463 size = DEFAULT_LINE_SIZE;
464 switch (msg_type & 3) {
465 case 0:
466 irc_send = irc_notice;
467 break;
468 case 2:
469 irc_send = irc_wallchops;
470 break;
471 case 1:
472 default:
473 irc_send = irc_privmsg;
474 }
475
476 /* This used to be two passes, but if you do that and allow
477 * arbitrary sizes for ${}-expansions (as with help indexes),
478 * that requires a very big intermediate buffer.
479 */
480 expand_ipos = newline_ipos = ipos = 0;
481 expand_pos = pos = 0;
482 chars_sent = 0;
483 while (input.list[ipos]) {
484 char ch, *value, *free_value;
485
486 while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
487 line[pos++] = ch;
488 ipos++;
489 }
490
491 if (!input.list[ipos])
492 goto send_line;
493 if (input.list[ipos] == '\n') {
494 ipos++;
495 goto send_line;
496 }
497 if (pos == size) {
498 unsigned int new_ipos;
499 /* Scan backwards for a space in the input, until we hit
500 * either the last newline or the last variable expansion.
501 * Print the line up to that point, and start from there.
502 */
503 for (new_ipos = ipos;
504 (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
505 --new_ipos)
506 if (input.list[new_ipos] == ' ')
507 break;
508 pos -= ipos - new_ipos;
509 if (new_ipos == newline_ipos) {
510 /* Single word was too big to fit on one line; skip
511 * forward to its end and print it as a whole.
512 */
513 while (input.list[new_ipos]
514 && (input.list[new_ipos] != ' ')
515 && (input.list[new_ipos] != '\n')
516 && (input.list[new_ipos] != '$'))
517 line[pos++] = input.list[new_ipos++];
518 }
519 ipos = new_ipos;
520 while (input.list[ipos] == ' ')
521 ipos++;
522 goto send_line;
523 }
524
525 free_value = 0;
526 switch (input.list[++ipos]) {
527 /* Literal '$' or end of string. */
528 case 0:
529 ipos--;
530 case '$':
531 value = "$";
532 break;
533 /* The following two expand to mIRC color codes if enabled
534 by the user. */
535 case 'b':
536 value = use_color ? "\002" : "";
537 break;
538 case 'o':
539 value = use_color ? "\017" : "";
540 break;
541 case 'r':
542 value = use_color ? "\026" : "";
543 break;
544 case 'u':
545 value = use_color ? "\037" : "";
546 break;
547 /* Service nicks. */
548 case 'S':
549 value = src->nick;
550 break;
551 case 'G':
552 value = global ? global->nick : "Global";
553 break;
554 case 'C':
555 value = chanserv ? chanserv->nick : "ChanServ";
556 break;
557 case 'O':
558 value = opserv ? opserv->nick : "OpServ";
559 break;
560 case 'N':
561 value = nickserv ? nickserv->nick : "NickServ";
562 break;
563 case 's':
564 value = self->name;
565 break;
566 case 'H':
567 value = handle ? handle->handle : "Account";
568 break;
569 #define SEND_LINE(TRUNCED) do { \
570 line[pos] = 0; \
571 if (pos > 0) { \
572 if (!(msg_type & MSG_TYPE_MULTILINE) && (pos > 1) && TRUNCED) \
573 line[pos-2] = line[pos-1] = '.'; \
574 irc_send(src, dest, line); \
575 } \
576 chars_sent += pos; \
577 pos = 0; \
578 newline_ipos = ipos; \
579 if (!(msg_type & MSG_TYPE_MULTILINE)) return chars_sent; \
580 } while (0)
581 /* Custom expansion handled by helpfile-specific function. */
582 case '{':
583 case '(': {
584 struct helpfile_expansion exp;
585 char *name_end = input.list + ipos + 1, *colon = NULL;
586
587 while (*name_end != '}' && *name_end != ')' && *name_end) {
588 if (*name_end == ':') {
589 colon = name_end;
590 *colon = '\0';
591 }
592 name_end++;
593 }
594 if (!*name_end)
595 goto fallthrough;
596 *name_end = '\0';
597 if (colon) {
598 struct module *module = module_find(input.list + ipos + 1);
599 if (module && module->expand_help)
600 exp = module->expand_help(colon + 1);
601 else {
602 *colon = ':';
603 goto fallthrough;
604 }
605 } else if (expand_f)
606 exp = expand_f(input.list + ipos + 1);
607 else
608 goto fallthrough;
609 switch (exp.type) {
610 case HF_STRING:
611 free_value = value = exp.value.str;
612 if (!value)
613 value = "";
614 break;
615 case HF_TABLE:
616 /* Must send current line, then emit table. */
617 SEND_LINE(0);
618 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
619 value = "";
620 break;
621 default:
622 value = "";
623 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
624 break;
625 }
626 ipos = name_end - input.list;
627 break;
628 }
629 default:
630 fallthrough:
631 value = alloca(3);
632 value[0] = '$';
633 value[1] = input.list[ipos];
634 value[2] = 0;
635 }
636 ipos++;
637 while ((pos + strlen(value) > size) || strchr(value, '\n')) {
638 unsigned int avail;
639 avail = size - pos - 1;
640 length = strcspn(value, "\n ");
641 if (length <= avail) {
642 strncpy(line+pos, value, length);
643 pos += length;
644 value += length;
645 /* copy over spaces, until (possible) end of line */
646 while (*value == ' ') {
647 if (pos < size-1)
648 line[pos++] = *value;
649 value++;
650 }
651 } else {
652 /* word to send is too big to send now.. what to do? */
653 if (pos > 0) {
654 /* try to put it on a separate line */
655 SEND_LINE(1);
656 } else {
657 /* already at start of line; only send part of it */
658 strncpy(line, value, avail);
659 pos += avail;
660 value += length;
661 /* skip any trailing spaces */
662 while (*value == ' ')
663 value++;
664 }
665 }
666 /* if we're looking at a newline, send the accumulated text */
667 if (*value == '\n') {
668 SEND_LINE(0);
669 value++;
670 }
671 }
672 length = strlen(value);
673 memcpy(line + pos, value, length);
674 if (free_value)
675 free(free_value);
676 pos += length;
677 if ((pos < size-1) && input.list[ipos]) {
678 expand_pos = pos;
679 expand_ipos = ipos;
680 continue;
681 }
682 send_line:
683 expand_pos = pos;
684 expand_ipos = ipos;
685 SEND_LINE(0);
686 #undef SEND_LINE
687 }
688 return chars_sent;
689 }
690
691 int
692 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
693 {
694 int res;
695 va_list ap;
696
697 if (IsLocal(dest)) return 0;
698 va_start(ap, format);
699 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
700 va_end(ap);
701 return res;
702 }
703
704 int
705 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
706 int res;
707 va_list ap;
708
709 if (IsLocal(dest)) return 0;
710 va_start(ap, format);
711 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
712 va_end(ap);
713 return res;
714 }
715
716 int
717 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
718 {
719 int res;
720 va_list ap;
721
722 va_start(ap, format);
723 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
724 va_end(ap);
725 return res;
726 }
727
728 int
729 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
730 {
731 int res;
732
733 va_list ap;
734 va_start(ap, format);
735 res = vsend_message(dest->nick, src, dest->handle_info, 12, expand, format, ap);
736 va_end(ap);
737 return res;
738 }
739
740 int
741 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
742 {
743 struct helpfile *lang_hf;
744 struct record_data *rec;
745 struct language *curr;
746
747 if (!topic)
748 topic = "<index>";
749 if (!hf) {
750 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
751 return false;
752 }
753 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
754 curr;
755 curr = curr->parent) {
756 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
757 if (!lang_hf)
758 continue;
759 rec = dict_find(lang_hf->db, topic, NULL);
760 if (rec && rec->type == RECDB_QSTRING) {
761 _send_help(dest, src, hf->expand, rec->d.qstring);
762 return true;
763 }
764 }
765 rec = dict_find(hf->db, "<missing>", NULL);
766 if (!rec)
767 return false;
768 if (rec->type != RECDB_QSTRING) {
769 send_message(dest, src, "HFMSG_HELP_NOT_STRING");
770 return false;
771 }
772 _send_help(dest, src, hf->expand, rec->d.qstring);
773 return true;
774 }
775
776 int
777 send_help_brief(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
778 {
779 struct helpfile *lang_hf;
780 struct record_data *rec;
781 struct language *curr;
782
783 if (!topic)
784 topic = "<index>";
785 if (!hf) {
786 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
787 return 0;
788 }
789 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
790 curr;
791 curr = curr->parent) {
792 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
793 if (!lang_hf)
794 continue;
795 rec = dict_find(lang_hf->db, topic, NULL);
796 if (rec && rec->type == RECDB_QSTRING)
797 {
798 char* buf;
799 int res;
800
801 buf = malloc(strlen(rec->d.qstring) + 1);
802 strcpy(buf, rec->d.qstring);
803 *strchr(buf, '\n') = 0;
804
805 res = _send_help(dest, src, hf->expand, buf);
806 free(buf);
807 return res;
808 }
809 }
810 rec = dict_find(hf->db, "<missing>", NULL);
811 if (!rec)
812 return 0; /* send_message(dest, src, "MSG_TOPIC_UNKNOWN"); */
813 if (rec->type != RECDB_QSTRING)
814 return 0; /* send_message(dest, src, "HFMSG_HELP_NOT_STRING"); */
815 return _send_help(dest, src, hf->expand, rec->d.qstring);
816 }
817
818 /* Grammar supported by this parser:
819 * condition = expr | prefix expr
820 * expr = atomicexpr | atomicexpr op atomicexpr
821 * op = '&&' | '||' | 'and' | 'or'
822 * atomicexpr = '(' expr ')' | identifier
823 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
824 *
825 * Whitespace is ignored. The parser is implemented as a recursive
826 * descent parser by functions like:
827 * static int helpfile_eval_<element>(const char *start, const char **end);
828 */
829
830 enum helpfile_op {
831 OP_INVALID,
832 OP_BOOL_AND,
833 OP_BOOL_OR
834 };
835
836 static const struct {
837 const char *str;
838 enum helpfile_op op;
839 } helpfile_operators[] = {
840 { "&&", OP_BOOL_AND },
841 { "and", OP_BOOL_AND },
842 { "||", OP_BOOL_OR },
843 { "or", OP_BOOL_OR },
844 { NULL, OP_INVALID }
845 };
846
847 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
848
849 static int helpfile_eval_expr(const char *start, const char **end);
850 static int helpfile_eval_atomicexpr(const char *start, const char **end);
851 static int helpfile_eval_identifier(const char *start, const char **end);
852
853 static int
854 helpfile_eval_identifier(const char *start, const char **end)
855 {
856 /* Skip leading whitespace. */
857 while (isspace(*start) && (start < *end))
858 start++;
859 if (start == *end) {
860 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
861 return -1;
862 }
863
864 if (start[0] == '!') {
865 int res = helpfile_eval_identifier(start+1, end);
866 if (res < 0)
867 return res;
868 return !res;
869 } else if (start[0] == '/') {
870 const char *sep;
871 char *id_str, *value;
872
873 for (sep = start;
874 strchr(identifier_chars, sep[0]) && (sep < *end);
875 ++sep) ;
876 memcpy(id_str = alloca(sep+1-start), start, sep-start);
877 id_str[sep-start] = '\0';
878 value = conf_get_data(id_str+1, RECDB_QSTRING);
879 *end = sep;
880 if (!value)
881 return 0;
882 return enabled_string(value) || true_string(value);
883 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
884 *end = start + 4;
885 return 1;
886 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
887 *end = start + 5;
888 return 0;
889 } else {
890 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", (int)(*end-start), start);
891 return -1;
892 }
893 }
894
895 static int
896 helpfile_eval_atomicexpr(const char *start, const char **end)
897 {
898 const char *sep;
899 int res;
900
901 /* Skip leading whitespace. */
902 while (isspace(*start) && (start < *end))
903 start++;
904 if (start == *end) {
905 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
906 return -1;
907 }
908
909 /* If it's not parenthesized, it better be a valid identifier. */
910 if (*start != '(')
911 return helpfile_eval_identifier(start, end);
912
913 /* Parse the internal expression. */
914 start++;
915 sep = *end;
916 res = helpfile_eval_expr(start, &sep);
917
918 /* Check for the closing parenthesis. */
919 while (isspace(*sep) && (sep < *end))
920 sep++;
921 if ((sep == *end) || (sep[0] != ')')) {
922 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", (int)(*end-sep), sep);
923 return -1;
924 }
925
926 /* Report the end location and result. */
927 *end = sep + 1;
928 return res;
929 }
930
931 static int
932 helpfile_eval_expr(const char *start, const char **end)
933 {
934 const char *sep, *sep2;
935 unsigned int ii, len;
936 int res_a, res_b;
937 enum helpfile_op op;
938
939 /* Parse the first atomicexpr. */
940 sep = *end;
941 res_a = helpfile_eval_atomicexpr(start, &sep);
942 if (res_a < 0)
943 return res_a;
944
945 /* Figure out what follows that. */
946 while (isspace(*sep) && (sep < *end))
947 sep++;
948 if (sep == *end)
949 return res_a;
950 op = OP_INVALID;
951 for (ii = 0; helpfile_operators[ii].str; ++ii) {
952 len = strlen(helpfile_operators[ii].str);
953 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
954 continue;
955 op = helpfile_operators[ii].op;
956 sep += len;
957 }
958 if (op == OP_INVALID) {
959 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", (int)(*end-sep), sep);
960 return -1;
961 }
962
963 /* Parse the next atomicexpr. */
964 sep2 = *end;
965 res_b = helpfile_eval_atomicexpr(sep, &sep2);
966 if (res_b < 0)
967 return res_b;
968
969 /* Make sure there's no trailing garbage */
970 while (isspace(*sep2) && (sep2 < *end))
971 sep2++;
972 if (sep2 != *end) {
973 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", (int)(*end-sep2), sep2);
974 return -1;
975 }
976
977 /* Record where we stopped parsing. */
978 *end = sep2;
979
980 /* Do the logic on the subexpressions. */
981 switch (op) {
982 case OP_BOOL_AND:
983 return res_a && res_b;
984 case OP_BOOL_OR:
985 return res_a || res_b;
986 default:
987 return -1;
988 }
989 }
990
991 static int
992 helpfile_eval_condition(const char *start, const char **end)
993 {
994 const char *term;
995
996 /* Skip the prefix if there is one. */
997 for (term = start; isalnum(*term) && (term < *end); ++term) ;
998 if (term != start) {
999 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
1000 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.",(int)(*end-start), start);
1001 return -1;
1002 }
1003 start = term + 2;
1004 }
1005
1006 /* Evaluate the remaining string as an expression. */
1007 return helpfile_eval_expr(start, end);
1008 }
1009
1010 static int
1011 unlistify_help(const char *key, void *data, void *extra)
1012 {
1013 struct record_data *rd = data;
1014 dict_t newdb = extra;
1015
1016 switch (rd->type) {
1017 case RECDB_QSTRING:
1018 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
1019 return 0;
1020 case RECDB_STRING_LIST: {
1021 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
1022 char *dest;
1023 unsigned int totlen, len, i;
1024
1025 for (i=totlen=0; i<slist->used; i++)
1026 totlen = totlen + strlen(slist->list[i]) + 1;
1027 dest = alloca(totlen+1);
1028 for (i=totlen=0; i<slist->used; i++) {
1029 len = strlen(slist->list[i]);
1030 memcpy(dest+totlen, slist->list[i], len);
1031 dest[totlen+len] = '\n';
1032 totlen = totlen + len + 1;
1033 }
1034 dest[totlen] = 0;
1035 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
1036 return 0;
1037 }
1038 case RECDB_OBJECT: {
1039 dict_iterator_t it;
1040
1041 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
1042 const char *k2, *end;
1043 int res;
1044
1045 /* Evaluate the expression for this subentry. */
1046 k2 = iter_key(it);
1047 end = k2 + strlen(k2);
1048 res = helpfile_eval_condition(k2, &end);
1049 /* If the evaluation failed, bail. */
1050 if (res < 0) {
1051 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
1052 return 1;
1053 }
1054 /* If the condition was false, try another. */
1055 if (!res)
1056 continue;
1057 /* If we cannot unlistify the contents, bail. */
1058 if (unlistify_help(key, iter_data(it), extra))
1059 return 1;
1060 return 0;
1061 }
1062 /* If none of the conditions apply, just omit the entry. */
1063 return 0;
1064 }
1065 default:
1066 return 1;
1067 }
1068 }
1069
1070 struct helpfile *
1071 open_helpfile(const char *fname, expand_func_t expand)
1072 {
1073 struct helpfile *hf;
1074 char *slash;
1075 dict_t db = parse_database(fname);
1076 hf = calloc(1, sizeof(*hf));
1077 hf->expand = expand;
1078 hf->db = alloc_database();
1079 dict_set_free_keys(hf->db, free);
1080 if ((slash = strrchr(fname, '/'))) {
1081 hf->name = strdup(slash + 1);
1082 } else {
1083 hf->name = strdup(fname);
1084 dict_insert(language_find("C")->helpfiles, hf->name, hf);
1085 }
1086 if (db) {
1087 dict_foreach(db, unlistify_help, hf->db);
1088 free_database(db);
1089 }
1090 return hf;
1091 }
1092
1093 void close_helpfile(struct helpfile *hf)
1094 {
1095 if (!hf)
1096 return;
1097 free((char*)hf->name);
1098 free_database(hf->db);
1099 free(hf);
1100 }
1101
1102 void message_register_table(const struct message_entry *table)
1103 {
1104 if (!lang_C)
1105 language_find("C");
1106 while (table->msgid) {
1107 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1108 table++;
1109 }
1110 }
1111
1112 void helpfile_init(void)
1113 {
1114 message_register_table(msgtab);
1115 language_read_list();
1116 }
1117
1118 void helpfile_finalize(void)
1119 {
1120 dict_iterator_t it;
1121 for (it = dict_first(languages); it; it = iter_next(it))
1122 language_read(iter_key(it));
1123 reg_exit_func(language_cleanup);
1124 }