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