1 /* helpfile.c - Help file loading and display
2 * Copyright 2000-2004 srvx Development Team
4 * This file is part of srvx.
6 * srvx is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
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.
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.
29 static const struct message_entry msgtab[] = {
30 { "HFMSG_MISSING_HELPFILE", "The help file could not be found. Sorry!" },
31 { "HFMSG_HELP_NOT_STRING", "Help file error (help data was not a string)." },
35 #define DEFAULT_LINE_SIZE MAX_LINE_SIZE
36 #define DEFAULT_TABLE_SIZE 80
38 extern struct userNode *global, *chanserv, *opserv, *nickserv;
39 struct userNode *message_dest;
40 struct userNode *message_source;
41 struct language *lang_C;
42 struct dict *languages;
44 static void language_cleanup(void)
46 dict_delete(languages);
49 static void language_free_helpfile(void *data)
51 struct helpfile *hf = data;
55 static void language_free(void *data)
57 struct language *lang = data;
58 dict_delete(lang->messages);
59 dict_delete(lang->helpfiles);
64 static struct language *language_alloc(const char *name)
66 struct language *lang = calloc(1, sizeof(*lang));
67 lang->name = strdup(name);
68 lang->parent = lang_C;
70 languages = dict_new();
71 dict_set_free_data(languages, language_free);
73 dict_insert(languages, lang->name, lang);
77 /* Language names should use a lang or lang_COUNTRY type system, where
78 * lang is a two-letter code according to ISO-639-1 (or three-letter
79 * code according to ISO-639-2 for languages not in ISO-639-1), and
80 * COUNTRY is the ISO 3166 country code in all upper case.
83 * http://www.loc.gov/standards/iso639-2/
84 * http://www.loc.gov/standards/iso639-2/langhome.html
85 * http://www.iso.ch/iso/en/prods-services/iso3166ma/index.html
87 struct language *language_find(const char *name)
89 struct language *lang;
90 char alt_name[MAXLEN];
93 if ((lang = dict_find(languages, name, NULL)))
95 if ((uscore = strchr(name, '_'))) {
96 strncpy(alt_name, name, uscore-name);
97 alt_name[uscore-name] = 0;
98 if ((lang = dict_find(languages, alt_name, NULL)))
102 lang_C = language_alloc("C");
103 lang_C->messages = dict_new();
104 lang_C->helpfiles = dict_new();
109 static void language_set_messages(struct language *lang, dict_t dict)
111 dict_iterator_t it, it2;
112 struct record_data *rd;
117 for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it; ) {
118 const char *msgid = iter_key(it);
119 int diff = it2 ? irccasecmp(msgid, iter_key(it2)) : -1;
124 } else if (diff > 0) {
126 it2 = iter_next(it2);
132 msg = strdup(rd->d.qstring);
134 case RECDB_STRING_LIST:
135 /* XXX: maybe do an unlistify_help() type thing */
137 log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
140 dict_insert(lang->messages, strdup(msgid), msg);
142 it2 = iter_next(it2);
146 it2 = iter_next(it2);
148 if (extra || missing)
149 log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages.", lang->name, extra, missing);
152 static struct language *language_read(const char *name)
155 struct dirent *dirent;
156 struct language *lang;
158 char filename[MAXLEN], *uscore;
162 /* Never try to read the C language from disk. */
163 if (!irccasecmp(name, "C"))
166 /* Open the directory stream; if we can't, fail. */
167 snprintf(filename, sizeof(filename), "languages/%s", name);
168 if (!(dir = opendir(filename)))
170 if (!(lang = dict_find(languages, name, NULL)))
171 lang = language_alloc(name);
173 /* Find the parent language. */
174 snprintf(filename, sizeof(filename), "languages/%s/parent", name);
175 if (!(file = fopen(filename, "r"))
176 || !fgets(filename, sizeof(filename), file)) {
177 strcpy(filename, "C");
179 if (!(lang->parent = language_find(filename))) {
180 uscore = strchr(filename, '_');
183 lang->parent = language_find(filename);
186 lang->parent = lang_C;
189 /* (Re-)initialize the language's dicts. */
190 dict_delete(lang->messages);
191 lang->messages = dict_new();
192 dict_set_free_keys(lang->messages, free);
193 dict_set_free_data(lang->messages, free);
194 lang->helpfiles = dict_new();
195 dict_set_free_data(lang->helpfiles, language_free_helpfile);
197 /* Read all the translations from the directory. */
198 while ((dirent = readdir(dir))) {
199 snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
200 if (!strcmp(dirent->d_name,"parent")) {
202 } else if (!strcmp(dirent->d_name, "strings.db")) {
203 dict = parse_database(filename);
204 language_set_messages(lang, dict);
206 } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
207 hf = open_helpfile(filename, hf->expand);
208 dict_insert(lang->helpfiles, hf->name, hf);
217 static void language_read_list(void)
219 struct dirent *dirent;
222 if (!(dir = opendir("languages")))
224 while ((dirent = readdir(dir))) {
225 if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, ".."))
227 language_alloc(dirent->d_name);
232 static void language_read_all(void)
234 struct string_list *slist;
235 struct dirent *dirent;
239 /* Read into an in-memory list and sort so we are likely to load
240 * parent languages before their children (de_DE sorts after de).
242 if (!(dir = opendir("languages")))
244 slist = alloc_string_list(4);
245 while ((dirent = readdir(dir)))
246 string_list_append(slist, strdup(dirent->d_name));
248 string_list_sort(slist);
249 for (ii = 0; ii < slist->used; ++ii) {
250 if (!strcmp(slist->list[ii], ".") || !strcmp(slist->list[ii], ".."))
252 language_read(slist->list[ii]);
254 free_string_list(slist);
257 const char *language_find_message(struct language *lang, const char *msgid) {
258 struct language *curr;
262 for (curr = lang; curr; curr = curr->parent)
263 if ((msg = dict_find(curr->messages, msgid, NULL)))
265 log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
270 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
271 unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
272 char line[MAX_LINE_SIZE+1];
273 struct handle_info *hi;
275 if (IsChannelName(to) || *to == '$') {
279 message_dest = GetUserH(to);
281 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
284 hi = message_dest->handle_info;
285 #ifdef WITH_PROTOCOL_P10
286 to = message_dest->numeric;
289 message_source = from;
291 /* If size or irc_send are 0, we should try to use a default. */
295 size = DEFAULT_TABLE_SIZE;
296 else if (hi->table_width)
297 size = hi->table_width;
298 else if (hi->screen_width)
299 size = hi->screen_width;
301 size = DEFAULT_TABLE_SIZE;
304 {} /* use that function */
306 irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
308 irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
310 /* Limit size to how much we can show at once */
311 if (size > sizeof(line))
314 /* Figure out how wide columns should be */
315 max_width = alloca(table.width * sizeof(int));
316 for (jj=tot_width=0; jj<table.width; jj++) {
317 /* Find the widest width for this column */
319 for (ii=0; ii<table.length; ii++) {
320 len = strlen(table.contents[ii][jj]);
321 if (len > max_width[jj])
324 /* Separate columns with spaces */
325 tot_width += max_width[jj] + 1;
327 /* How many rows to put in a line? */
328 if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
329 nreps = size / tot_width;
332 /* Send headers line.. */
333 if (table.flags & TABLE_NO_HEADERS) {
336 /* Sending headers needs special treatment: either show them
337 * once, or repeat them as many times as we repeat the columns
339 for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
341 len = strlen(table.contents[0][jj]);
342 spaces = max_width[jj] - len;
343 if (table.flags & TABLE_PAD_LEFT)
346 memcpy(line+pos, table.contents[0][jj], len);
348 if (++jj == table.width)
350 if (!(table.flags & TABLE_PAD_LEFT))
357 irc_send(from, to, line);
360 /* Send the table. */
361 for (jj=0, pos=0, reps=0; ii<table.length; ) {
363 len = strlen(table.contents[ii][jj]);
364 spaces = max_width[jj] - len;
365 if (table.flags & TABLE_PAD_LEFT)
366 while (spaces--) line[pos++] = ' ';
367 memcpy(line+pos, table.contents[ii][jj], len);
369 if (++jj == table.width) {
370 jj = 0, ++ii, ++reps;
371 if ((reps == nreps) || (ii == table.length)) {
373 irc_send(from, to, line);
378 if (!(table.flags & TABLE_PAD_LEFT))
384 if (!(table.flags & TABLE_NO_FREE)) {
385 /* Deallocate table memory (but not the string memory). */
386 for (ii=0; ii<table.length; ii++)
387 free(table.contents[ii]);
388 free(table.contents);
393 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)
395 void (*irc_send)(struct userNode *from, const char *to, const char *msg);
396 static struct string_buffer input;
397 unsigned int size, ipos, pos, length, chars_sent, use_color;
398 unsigned int expand_pos, expand_ipos, newline_ipos;
399 char line[MAX_LINE_SIZE];
401 if (IsChannelName(dest) || *dest == '$') {
403 } else if (!(message_dest = GetUserH(dest))) {
404 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
406 } else if (message_dest->dead) {
407 /* No point in sending to a user who is leaving. */
410 #ifdef WITH_PROTOCOL_P10
411 dest = message_dest->numeric;
414 message_source = src;
415 if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
417 /* fill in a buffer with the string */
419 string_buffer_append_vprintf(&input, format, al);
421 /* figure out how to send the messages */
423 msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
424 use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
425 size = handle->screen_width;
426 if (size > sizeof(line))
433 size = DEFAULT_LINE_SIZE;
434 switch (msg_type & 3) {
436 irc_send = irc_notice;
439 irc_send = irc_wallchops;
443 irc_send = irc_privmsg;
446 /* This used to be two passes, but if you do that and allow
447 * arbitrary sizes for ${}-expansions (as with help indexes),
448 * that requires a very big intermediate buffer.
450 expand_ipos = newline_ipos = ipos = 0;
451 expand_pos = pos = 0;
453 while (input.list[ipos]) {
454 char ch, *value, *free_value;
456 while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
461 if (!input.list[ipos])
463 if (input.list[ipos] == '\n') {
468 unsigned int new_ipos;
469 /* Scan backwards for a space in the input, until we hit
470 * either the last newline or the last variable expansion.
471 * Print the line up to that point, and start from there.
473 for (new_ipos = ipos;
474 (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
476 if (input.list[new_ipos] == ' ')
478 pos -= ipos - new_ipos;
479 if (new_ipos == newline_ipos) {
480 /* Single word was too big to fit on one line; skip
481 * forward to its end and print it as a whole.
483 while (input.list[new_ipos]
484 && (input.list[new_ipos] != ' ')
485 && (input.list[new_ipos] != '\n')
486 && (input.list[new_ipos] != '$'))
487 line[pos++] = input.list[new_ipos++];
490 while (input.list[ipos] == ' ')
496 switch (input.list[++ipos]) {
497 /* Literal '$' or end of string. */
503 /* The following two expand to mIRC color codes if enabled
506 value = use_color ? "\002" : "";
509 value = use_color ? "\017" : "";
512 value = use_color ? "\026" : "";
515 value = use_color ? "\037" : "";
522 value = global ? global->nick : "Global";
525 value = chanserv ? chanserv->nick : "ChanServ";
528 value = opserv ? opserv->nick : "OpServ";
531 value = nickserv ? nickserv->nick : "NickServ";
537 value = handle ? handle->handle : "Account";
539 #define SEND_LINE() do { line[pos] = 0; if (pos > 0) irc_send(src, dest, line); chars_sent += pos; pos = 0; newline_ipos = ipos; } while (0)
540 /* Custom expansion handled by helpfile-specific function. */
543 struct helpfile_expansion exp;
544 char *name_end = input.list + ipos + 1, *colon = NULL;
546 while (*name_end != '}' && *name_end != ')' && *name_end) {
547 if (*name_end == ':') {
557 struct module *module = module_find(input.list + ipos + 1);
558 if (module && module->expand_help)
559 exp = module->expand_help(colon + 1);
565 exp = expand_f(input.list + ipos + 1);
570 free_value = value = exp.value.str;
575 /* Must send current line, then emit table. */
577 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
582 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
585 ipos = name_end - input.list;
592 value[1] = input.list[ipos];
596 while ((pos + strlen(value) > size) || strchr(value, '\n')) {
598 avail = size - pos - 1;
599 length = strcspn(value, "\n ");
600 if (length <= avail) {
601 strncpy(line+pos, value, length);
604 /* copy over spaces, until (possible) end of line */
605 while (*value == ' ') {
607 line[pos++] = *value;
611 /* word to send is too big to send now.. what to do? */
613 /* try to put it on a separate line */
616 /* already at start of line; only send part of it */
617 strncpy(line, value, avail);
620 /* skip any trailing spaces */
621 while (*value == ' ')
625 /* if we're looking at a newline, send the accumulated text */
626 if (*value == '\n') {
631 length = strlen(value);
632 memcpy(line + pos, value, length);
636 if ((pos < size-1) && input.list[ipos]) {
651 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
656 if (IsLocal(dest)) return 0;
657 va_start(ap, format);
658 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
664 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
668 if (IsLocal(dest)) return 0;
669 va_start(ap, format);
670 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
676 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
681 va_start(ap, format);
682 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
688 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
693 va_start(ap, format);
694 res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
700 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
702 struct helpfile *lang_hf;
703 struct record_data *rec;
704 struct language *curr;
709 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
712 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
714 curr = curr->parent) {
715 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
718 rec = dict_find(lang_hf->db, topic, NULL);
719 if (rec && rec->type == RECDB_QSTRING)
720 return _send_help(dest, src, hf->expand, rec->d.qstring);
722 rec = dict_find(hf->db, "<missing>", NULL);
724 return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
725 if (rec->type != RECDB_QSTRING)
726 return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
727 return _send_help(dest, src, hf->expand, rec->d.qstring);
730 /* Grammar supported by this parser:
731 * condition = expr | prefix expr
732 * expr = atomicexpr | atomicexpr op atomicexpr
733 * op = '&&' | '||' | 'and' | 'or'
734 * atomicexpr = '(' expr ')' | identifier
735 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
737 * Whitespace is ignored. The parser is implemented as a recursive
738 * descent parser by functions like:
739 * static int helpfile_eval_<element>(const char *start, const char **end);
748 static const struct {
751 } helpfile_operators[] = {
752 { "&&", OP_BOOL_AND },
753 { "and", OP_BOOL_AND },
754 { "||", OP_BOOL_OR },
755 { "or", OP_BOOL_OR },
759 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
761 static int helpfile_eval_expr(const char *start, const char **end);
762 static int helpfile_eval_atomicexpr(const char *start, const char **end);
763 static int helpfile_eval_identifier(const char *start, const char **end);
766 helpfile_eval_identifier(const char *start, const char **end)
768 /* Skip leading whitespace. */
769 while (isspace(*start) && (start < *end))
772 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
776 if (start[0] == '!') {
777 int res = helpfile_eval_identifier(start+1, end);
781 } else if (start[0] == '/') {
783 char *id_str, *value;
786 strchr(identifier_chars, sep[0]) && (sep < *end);
788 memcpy(id_str = alloca(sep+1-start), start, sep-start);
789 id_str[sep-start] = '\0';
790 value = conf_get_data(id_str+1, RECDB_QSTRING);
794 return enabled_string(value) || true_string(value);
795 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
798 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
802 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
808 helpfile_eval_atomicexpr(const char *start, const char **end)
813 /* Skip leading whitespace. */
814 while (isspace(*start) && (start < *end))
817 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
821 /* If it's not parenthesized, it better be a valid identifier. */
823 return helpfile_eval_identifier(start, end);
825 /* Parse the internal expression. */
828 res = helpfile_eval_expr(start, &sep);
830 /* Check for the closing parenthesis. */
831 while (isspace(*sep) && (sep < *end))
833 if ((sep == *end) || (sep[0] != ')')) {
834 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
838 /* Report the end location and result. */
844 helpfile_eval_expr(const char *start, const char **end)
846 const char *sep, *sep2;
847 unsigned int ii, len;
851 /* Parse the first atomicexpr. */
853 res_a = helpfile_eval_atomicexpr(start, &sep);
857 /* Figure out what follows that. */
858 while (isspace(*sep) && (sep < *end))
863 for (ii = 0; helpfile_operators[ii].str; ++ii) {
864 len = strlen(helpfile_operators[ii].str);
865 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
867 op = helpfile_operators[ii].op;
870 if (op == OP_INVALID) {
871 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
875 /* Parse the next atomicexpr. */
877 res_b = helpfile_eval_atomicexpr(sep, &sep2);
881 /* Make sure there's no trailing garbage */
882 while (isspace(*sep2) && (sep2 < *end))
885 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
889 /* Record where we stopped parsing. */
892 /* Do the logic on the subexpressions. */
895 return res_a && res_b;
897 return res_a || res_b;
904 helpfile_eval_condition(const char *start, const char **end)
908 /* Skip the prefix if there is one. */
909 for (term = start; isalnum(*term) && (term < *end); ++term) ;
911 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
912 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
918 /* Evaluate the remaining string as an expression. */
919 return helpfile_eval_expr(start, end);
923 unlistify_help(const char *key, void *data, void *extra)
925 struct record_data *rd = data;
926 dict_t newdb = extra;
930 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
932 case RECDB_STRING_LIST: {
933 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
935 unsigned int totlen, len, i;
937 for (i=totlen=0; i<slist->used; i++)
938 totlen = totlen + strlen(slist->list[i]) + 1;
939 dest = alloca(totlen+1);
940 for (i=totlen=0; i<slist->used; i++) {
941 len = strlen(slist->list[i]);
942 memcpy(dest+totlen, slist->list[i], len);
943 dest[totlen+len] = '\n';
944 totlen = totlen + len + 1;
947 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
953 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
954 const char *k2, *end;
957 /* Evaluate the expression for this subentry. */
959 end = k2 + strlen(k2);
960 res = helpfile_eval_condition(k2, &end);
961 /* If the evaluation failed, bail. */
963 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
966 /* If the condition was false, try another. */
969 /* If we cannot unlistify the contents, bail. */
970 if (unlistify_help(key, iter_data(it), extra))
974 /* If none of the conditions apply, just omit the entry. */
983 open_helpfile(const char *fname, expand_func_t expand)
987 dict_t db = parse_database(fname);
988 hf = calloc(1, sizeof(*hf));
990 hf->db = alloc_database();
991 dict_set_free_keys(hf->db, free);
992 if ((slash = strrchr(fname, '/'))) {
993 hf->name = strdup(slash + 1);
995 hf->name = strdup(fname);
996 dict_insert(language_find("C")->helpfiles, hf->name, hf);
999 dict_foreach(db, unlistify_help, hf->db);
1005 void close_helpfile(struct helpfile *hf)
1009 free((char*)hf->name);
1010 free_database(hf->db);
1014 void message_register_table(const struct message_entry *table)
1018 while (table->msgid) {
1019 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1024 void helpfile_init(void)
1026 message_register_table(msgtab);
1027 language_read_list();
1030 void helpfile_finalize(void)
1032 language_read_all();
1033 reg_exit_func(language_cleanup);