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