]> jfr.im git - irc/evilnet/x3.git/blob - src/helpfile.c
Fix typos and copy errors in memoserv help
[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_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 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_ipos = ipos;
734 continue;
735 }
736 send_line:
737 expand_ipos = ipos;
738 SEND_LINE(0);
739 #undef SEND_LINE
740 }
741 return chars_sent;
742 }
743
744 int
745 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
746 {
747 int res;
748 va_list ap;
749
750 if (IsLocal(dest) && !IsDummy(dest)) return 0;
751 va_start(ap, format);
752 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
753 va_end(ap);
754 return res;
755 }
756
757 int
758 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
759 int res;
760 va_list ap;
761
762 if (IsLocal(dest) && !IsDummy(dest)) return 0;
763 va_start(ap, format);
764 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
765 va_end(ap);
766 return res;
767 }
768
769 int
770 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
771 {
772 int res;
773 va_list ap;
774
775 va_start(ap, format);
776 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
777 va_end(ap);
778 return res;
779 }
780
781 int
782 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
783 {
784 int res;
785
786 va_list ap;
787 va_start(ap, format);
788 res = vsend_message(dest->nick, src, dest->handle_info, 12, expand, format, ap);
789 va_end(ap);
790 return res;
791 }
792
793 int
794 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
795 {
796 struct helpfile *lang_hf;
797 struct record_data *rec;
798 struct language *curr;
799
800 if (!topic)
801 topic = "<index>";
802 if (!hf) {
803 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
804 return false;
805 }
806 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
807 curr;
808 curr = curr->parent) {
809 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
810 if (!lang_hf)
811 continue;
812 rec = dict_find(lang_hf->db, topic, NULL);
813 if (rec && rec->type == RECDB_QSTRING) {
814 _send_help(dest, src, hf->expand, rec->d.qstring);
815 return true;
816 }
817 }
818 rec = dict_find(hf->db, "<missing>", NULL);
819 if (!rec)
820 return false;
821 if (rec->type != RECDB_QSTRING) {
822 send_message(dest, src, "HFMSG_HELP_NOT_STRING");
823 return false;
824 }
825 _send_help(dest, src, hf->expand, rec->d.qstring);
826 return true;
827 }
828
829 int
830 send_help_brief(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
831 {
832 struct helpfile *lang_hf;
833 struct record_data *rec;
834 struct language *curr;
835
836 if (!topic)
837 topic = "<index>";
838 if (!hf) {
839 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
840 return 0;
841 }
842 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
843 curr;
844 curr = curr->parent) {
845 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
846 if (!lang_hf)
847 continue;
848 rec = dict_find(lang_hf->db, topic, NULL);
849 if (rec && rec->type == RECDB_QSTRING)
850 {
851 char* buf;
852 int res;
853
854 buf = malloc(strlen(rec->d.qstring) + 1);
855 strcpy(buf, rec->d.qstring);
856 *strchr(buf, '\n') = 0;
857
858 res = _send_help(dest, src, hf->expand, buf);
859 free(buf);
860 return res;
861 }
862 }
863 rec = dict_find(hf->db, "<missing>", NULL);
864 if (!rec)
865 return 0; /* send_message(dest, src, "MSG_TOPIC_UNKNOWN"); */
866 if (rec->type != RECDB_QSTRING)
867 return 0; /* send_message(dest, src, "HFMSG_HELP_NOT_STRING"); */
868 return _send_help(dest, src, hf->expand, rec->d.qstring);
869 }
870
871 /* Grammar supported by this parser:
872 * condition = expr | prefix expr
873 * expr = atomicexpr | atomicexpr op atomicexpr
874 * op = '&&' | '||' | 'and' | 'or'
875 * atomicexpr = '(' expr ')' | identifier
876 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
877 *
878 * Whitespace is ignored. The parser is implemented as a recursive
879 * descent parser by functions like:
880 * static int helpfile_eval_<element>(const char *start, const char **end);
881 */
882
883 enum helpfile_op {
884 OP_INVALID,
885 OP_BOOL_AND,
886 OP_BOOL_OR
887 };
888
889 static const struct {
890 const char *str;
891 enum helpfile_op op;
892 } helpfile_operators[] = {
893 { "&&", OP_BOOL_AND },
894 { "and", OP_BOOL_AND },
895 { "||", OP_BOOL_OR },
896 { "or", OP_BOOL_OR },
897 { NULL, OP_INVALID }
898 };
899
900 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
901
902 static int helpfile_eval_expr(const char *start, const char **end);
903 static int helpfile_eval_atomicexpr(const char *start, const char **end);
904 static int helpfile_eval_identifier(const char *start, const char **end);
905
906 static int
907 helpfile_eval_identifier(const char *start, const char **end)
908 {
909 /* Skip leading whitespace. */
910 while (isspace(*start) && (start < *end))
911 start++;
912 if (start == *end) {
913 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
914 return -1;
915 }
916
917 if (start[0] == '!') {
918 int res = helpfile_eval_identifier(start+1, end);
919 if (res < 0)
920 return res;
921 return !res;
922 } else if (start[0] == '/') {
923 const char *sep;
924 char *id_str, *value;
925
926 for (sep = start;
927 strchr(identifier_chars, sep[0]) && (sep < *end);
928 ++sep) ;
929 memcpy(id_str = alloca(sep+1-start), start, sep-start);
930 id_str[sep-start] = '\0';
931 value = conf_get_data(id_str+1, RECDB_QSTRING);
932 *end = sep;
933 if (!value)
934 return 0;
935 return enabled_string(value) || true_string(value);
936 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
937 *end = start + 4;
938 return 1;
939 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
940 *end = start + 5;
941 return 0;
942 } else {
943 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", (int)(*end-start), start);
944 return -1;
945 }
946 }
947
948 static int
949 helpfile_eval_atomicexpr(const char *start, const char **end)
950 {
951 const char *sep;
952 int res;
953
954 /* Skip leading whitespace. */
955 while (isspace(*start) && (start < *end))
956 start++;
957 if (start == *end) {
958 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
959 return -1;
960 }
961
962 /* If it's not parenthesized, it better be a valid identifier. */
963 if (*start != '(')
964 return helpfile_eval_identifier(start, end);
965
966 /* Parse the internal expression. */
967 start++;
968 sep = *end;
969 res = helpfile_eval_expr(start, &sep);
970
971 /* Check for the closing parenthesis. */
972 while (isspace(*sep) && (sep < *end))
973 sep++;
974 if ((sep == *end) || (sep[0] != ')')) {
975 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", (int)(*end-sep), sep);
976 return -1;
977 }
978
979 /* Report the end location and result. */
980 *end = sep + 1;
981 return res;
982 }
983
984 static int
985 helpfile_eval_expr(const char *start, const char **end)
986 {
987 const char *sep, *sep2;
988 unsigned int ii, len;
989 int res_a, res_b;
990 enum helpfile_op op;
991
992 /* Parse the first atomicexpr. */
993 sep = *end;
994 res_a = helpfile_eval_atomicexpr(start, &sep);
995 if (res_a < 0)
996 return res_a;
997
998 /* Figure out what follows that. */
999 while (isspace(*sep) && (sep < *end))
1000 sep++;
1001 if (sep == *end)
1002 return res_a;
1003 op = OP_INVALID;
1004 for (ii = 0; helpfile_operators[ii].str; ++ii) {
1005 len = strlen(helpfile_operators[ii].str);
1006 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
1007 continue;
1008 op = helpfile_operators[ii].op;
1009 sep += len;
1010 }
1011 if (op == OP_INVALID) {
1012 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", (int)(*end-sep), sep);
1013 return -1;
1014 }
1015
1016 /* Parse the next atomicexpr. */
1017 sep2 = *end;
1018 res_b = helpfile_eval_atomicexpr(sep, &sep2);
1019 if (res_b < 0)
1020 return res_b;
1021
1022 /* Make sure there's no trailing garbage */
1023 while (isspace(*sep2) && (sep2 < *end))
1024 sep2++;
1025 if (sep2 != *end) {
1026 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", (int)(*end-sep2), sep2);
1027 return -1;
1028 }
1029
1030 /* Record where we stopped parsing. */
1031 *end = sep2;
1032
1033 /* Do the logic on the subexpressions. */
1034 switch (op) {
1035 case OP_BOOL_AND:
1036 return res_a && res_b;
1037 case OP_BOOL_OR:
1038 return res_a || res_b;
1039 default:
1040 return -1;
1041 }
1042 }
1043
1044 static int
1045 helpfile_eval_condition(const char *start, const char **end)
1046 {
1047 const char *term;
1048
1049 /* Skip the prefix if there is one. */
1050 for (term = start; isalnum(*term) && (term < *end); ++term) ;
1051 if (term != start) {
1052 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
1053 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.",(int)(*end-start), start);
1054 return -1;
1055 }
1056 start = term + 2;
1057 }
1058
1059 /* Evaluate the remaining string as an expression. */
1060 return helpfile_eval_expr(start, end);
1061 }
1062
1063 static int
1064 unlistify_help(const char *key, void *data, void *extra)
1065 {
1066 struct record_data *rd = data;
1067 dict_t newdb = extra;
1068
1069 switch (rd->type) {
1070 case RECDB_QSTRING:
1071 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
1072 return 0;
1073 case RECDB_STRING_LIST: {
1074 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
1075 char *dest;
1076 unsigned int totlen, len, i;
1077
1078 for (i=totlen=0; i<slist->used; i++)
1079 totlen = totlen + strlen(slist->list[i]) + 1;
1080 dest = alloca(totlen+1);
1081 for (i=totlen=0; i<slist->used; i++) {
1082 len = strlen(slist->list[i]);
1083 memcpy(dest+totlen, slist->list[i], len);
1084 dest[totlen+len] = '\n';
1085 totlen = totlen + len + 1;
1086 }
1087 dest[totlen] = 0;
1088 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
1089 return 0;
1090 }
1091 case RECDB_OBJECT: {
1092 dict_iterator_t it;
1093
1094 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
1095 const char *k2, *end;
1096 int res;
1097
1098 /* Evaluate the expression for this subentry. */
1099 k2 = iter_key(it);
1100 end = k2 + strlen(k2);
1101 res = helpfile_eval_condition(k2, &end);
1102 /* If the evaluation failed, bail. */
1103 if (res < 0) {
1104 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
1105 return 1;
1106 }
1107 /* If the condition was false, try another. */
1108 if (!res)
1109 continue;
1110 /* If we cannot unlistify the contents, bail. */
1111 if (unlistify_help(key, iter_data(it), extra))
1112 return 1;
1113 return 0;
1114 }
1115 /* If none of the conditions apply, just omit the entry. */
1116 return 0;
1117 }
1118 default:
1119 return 1;
1120 }
1121 }
1122
1123 struct helpfile *
1124 open_helpfile(const char *fname, expand_func_t expand)
1125 {
1126 struct helpfile *hf;
1127 char *slash;
1128 dict_t db = parse_database(fname);
1129 hf = calloc(1, sizeof(*hf));
1130 hf->expand = expand;
1131 hf->db = alloc_database();
1132 dict_set_free_keys(hf->db, free);
1133 if ((slash = strrchr(fname, '/'))) {
1134 hf->name = strdup(slash + 1);
1135 } else {
1136 hf->name = strdup(fname);
1137 dict_insert(language_find("C")->helpfiles, hf->name, hf);
1138 }
1139 if (db) {
1140 dict_foreach(db, unlistify_help, hf->db);
1141 free_database(db);
1142 }
1143 return hf;
1144 }
1145
1146 void close_helpfile(struct helpfile *hf)
1147 {
1148 if (!hf)
1149 return;
1150 free((char*)hf->name);
1151 free_database(hf->db);
1152 free(hf);
1153 }
1154
1155 void message_register_table(const struct message_entry *table)
1156 {
1157 if (!lang_C)
1158 language_find("C");
1159 while (table->msgid) {
1160 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1161 table++;
1162 }
1163 }
1164
1165 void helpfile_init(void)
1166 {
1167 message_register_table(msgtab);
1168 language_read_list();
1169 }
1170
1171 static void helpfile_read_languages(void)
1172 {
1173 dict_iterator_t it;
1174 dict_t dict;
1175
1176 language_read_list();
1177 for (it = dict_first(languages); it; it = iter_next(it))
1178 language_read(iter_key(it));
1179
1180 /* If the user has a strings.db in their languages directory,
1181 * allow that to override C language strings.
1182 */
1183 dict = parse_database("languages/strings.db");
1184 if (dict) {
1185 language_set_messages(lang_C, dict);
1186 free_database(dict);
1187 }
1188 }
1189
1190 void helpfile_finalize(void)
1191 {
1192 conf_register_reload(helpfile_read_languages);
1193 reg_exit_func(language_cleanup, NULL);
1194 }