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