Assorted bug fixes
[srvx.git] / src / helpfile.c
index 71dcd91c8ef6710153241d6e973f3d6584eb71f2..d214fe345e95b45d1514d991ae2d134239d65fad 100644 (file)
@@ -1,11 +1,12 @@
 /* helpfile.c - Help file loading and display
  * Copyright 2000-2004 srvx Development Team
  *
- * This program is free software; you can redistribute it and/or modify
+ * This file is part of srvx.
+ *
+ * srvx is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.  Important limitations are
- * listed in the COPYING file that accompanies this software.
+ * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, email srvx-maintainers@srvx.net.
+ * along with srvx; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
  */
 
+#include "conf.h"
 #include "helpfile.h"
 #include "log.h"
+#include "modcmd.h"
 #include "nickserv.h"
-#include "recdb.h"
 
+#if defined(HAVE_DIRENT_H)
 #include <dirent.h>
+#endif
+
+#if defined(HAVE_SYS_STAT_H)
+#include <sys/stat.h>
+#endif
 
 static const struct message_entry msgtab[] = {
     { "HFMSG_MISSING_HELPFILE", "The help file could not be found.  Sorry!" },
@@ -62,6 +71,7 @@ static struct language *language_alloc(const char *name)
 {
     struct language *lang = calloc(1, sizeof(*lang));
     lang->name = strdup(name);
+    lang->parent = lang_C;
     if (!languages) {
         languages = dict_new();
         dict_set_free_data(languages, language_free);
@@ -106,19 +116,13 @@ static void language_set_messages(struct language *lang, dict_t dict)
 {
     dict_iterator_t it, it2;
     struct record_data *rd;
-    const char *msgid;
     char *msg;
-    int diff, extra, missing;
+    int extra, missing;
 
     extra = missing = 0;
-    for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it || it2; ) {
-        msgid = iter_key(it);
-        if (it && it2)
-            diff = irccasecmp(msgid, iter_key(it2));
-        else if (it)
-            diff = -1;
-        else
-            diff = 1;
+    for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it; ) {
+        const char *msgid = iter_key(it);
+        int diff = it2 ? irccasecmp(msgid, iter_key(it2)) : -1;
         if (diff < 0) {
             extra++;
             it = iter_next(it);
@@ -128,7 +132,6 @@ static void language_set_messages(struct language *lang, dict_t dict)
             it2 = iter_next(it2);
             continue;
         }
-        msgid = iter_key(it);
         rd = iter_data(it);
         switch (rd->type) {
         case RECDB_QSTRING:
@@ -140,11 +143,16 @@ static void language_set_messages(struct language *lang, dict_t dict)
             log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
             continue;
         }
-        dict_insert(lang->messages, iter_key(it2), msg);
+        dict_insert(lang->messages, strdup(msgid), msg);
         it = iter_next(it);
         it2 = iter_next(it2);
     }
-    log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages", lang->name, extra, missing);
+    while (it2) {
+        missing++;
+        it2 = iter_next(it2);
+    }
+    if (extra || missing)
+        log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages.", lang->name, extra, missing);
 }
 
 static struct language *language_read(const char *name)
@@ -163,10 +171,8 @@ static struct language *language_read(const char *name)
 
     /* Open the directory stream; if we can't, fail. */
     snprintf(filename, sizeof(filename), "languages/%s", name);
-    if (!(dir = opendir(filename))) {
-        
+    if (!(dir = opendir(filename)))
         return NULL;
-    }
     if (!(lang = dict_find(languages, name, NULL)))
         lang = language_alloc(name);
 
@@ -189,6 +195,7 @@ static struct language *language_read(const char *name)
     /* (Re-)initialize the language's dicts. */
     dict_delete(lang->messages);
     lang->messages = dict_new();
+    dict_set_free_keys(lang->messages, free);
     dict_set_free_data(lang->messages, free);
     lang->helpfiles = dict_new();
     dict_set_free_data(lang->helpfiles, language_free_helpfile);
@@ -213,29 +220,33 @@ static struct language *language_read(const char *name)
     return lang;
 }
 
-static void language_read_all(void)
+static void language_read_list(void)
 {
-    struct string_list *slist;
     struct dirent *dirent;
     DIR *dir;
-    unsigned int ii;
 
-    /* Read into an in-memory list and sort so we are likely to load
-     * parent languages before their children (de_DE sorts after de).
-     */
-    slist = alloc_string_list(4);
     if (!(dir = opendir("languages")))
         return;
-    while ((dirent = readdir(dir)))
-        string_list_append(slist, strdup(dirent->d_name));
-    closedir(dir);
-    string_list_sort(slist);
-    for (ii = 0; ii < slist->used; ++ii) {
-        if (!strcmp(slist->list[ii], ".") || !strcmp(slist->list[ii], ".."))
+    while ((dirent = readdir(dir))) {
+        if (dirent->d_name[0] == '.')
+            continue;
+#ifdef HAVE_DIRENT_D_TYPE
+        if (dirent->d_type != DT_DIR)
             continue;
-        language_read(slist->list[ii]);
+#else
+        {
+            char namebuf[MAXLEN];
+            struct stat sbuf;
+            snprintf(namebuf, sizeof(namebuf), "languages/%s", dirent->d_name);
+            if (stat(namebuf, &sbuf) < 0)
+                continue;
+            if (!S_ISDIR(sbuf.st_mode))
+                continue;
+        }
+#endif
+        language_alloc(dirent->d_name);
     }
-    free_string_list(slist);
+    closedir(dir);
 }
 
 const char *language_find_message(struct language *lang, const char *msgid) {
@@ -396,7 +407,8 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
 #endif
     }
     message_source = src;
-    if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
+    if (!(msg_type & MSG_TYPE_NOXLATE)
+        && !(format = handle_find_message(handle, format)))
         return 0;
     /* fill in a buffer with the string */
     input.used = 0;
@@ -413,7 +425,7 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
         size = sizeof(line);
         use_color = 1;
     }
-    if (!size)
+    if (!size || !(msg_type & MSG_TYPE_MULTILINE))
         size = DEFAULT_LINE_SIZE;
     switch (msg_type & 3) {
         case 0:
@@ -520,46 +532,72 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
        case 'H':
            value = handle ? handle->handle : "Account";
            break;
-#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)
+#define SEND_LINE(TRUNCED) do { \
+    line[pos] = 0; \
+    if (pos > 0) { \
+        if (!(msg_type & MSG_TYPE_MULTILINE) && (pos > 1) && TRUNCED) \
+            line[pos-2] = line[pos-1] = '.'; \
+        irc_send(src, dest, line); \
+    } \
+    chars_sent += pos; \
+    pos = 0; \
+    newline_ipos = ipos; \
+    if (!(msg_type & MSG_TYPE_MULTILINE)) return chars_sent; \
+} while (0)
        /* Custom expansion handled by helpfile-specific function. */
        case '{':
-       case '(':
-           if (expand_f) {
-               char *name_end = input.list + ipos + 1;
-
-               while (*name_end != '}' && *name_end != ')' && *name_end) name_end++;
-               if (*name_end) {
-                    struct helpfile_expansion exp;
-                   *name_end = 0;
-                   exp = expand_f(input.list + ipos + 1);
-                    switch (exp.type) {
-                    case HF_STRING:
-                        free_value = value = exp.value.str;
-                        if (!value) value = "";
-                        break;
-                    case HF_TABLE:
-                        /* Must send current line, then emit table. */
-                        SEND_LINE();
-                        table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
-                        value = "";
-                        break;
-                    default:
-                        value = "";
-                        log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
-                        break;
-                    }
-                   ipos = name_end - input.list;
-                   break;
-               }
-           }
-
-       /* Let it fall through when there's no expansion function or
-       terminating ')'. */
+       case '(': {
+            struct helpfile_expansion exp;
+            char *name_end = input.list + ipos + 1, *colon = NULL;
+
+            while (*name_end != '}' && *name_end != ')' && *name_end) {
+                if (*name_end == ':') {
+                    colon = name_end;
+                    *colon = '\0';
+                }
+                name_end++;
+            }
+            if (!*name_end)
+                goto fallthrough;
+            *name_end = '\0';
+            if (colon) {
+                struct module *module = module_find(input.list + ipos + 1);
+                if (module && module->expand_help)
+                    exp = module->expand_help(colon + 1);
+                else {
+                    *colon = ':';
+                    goto fallthrough;
+                }
+            } else if (expand_f)
+                exp = expand_f(input.list + ipos + 1);
+            else
+                goto fallthrough;
+            switch (exp.type) {
+            case HF_STRING:
+                free_value = value = exp.value.str;
+                if (!value)
+                    value = "";
+                break;
+            case HF_TABLE:
+                /* Must send current line, then emit table. */
+                SEND_LINE(0);
+                table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
+                value = "";
+                break;
+            default:
+                value = "";
+                log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
+                break;
+            }
+            ipos = name_end - input.list;
+            break;
+        }
        default:
-               value = alloca(3);
-               value[0] = '$';
-               value[1] = input.list[ipos];
-               value[2] = 0;
+        fallthrough:
+            value = alloca(3);
+            value[0] = '$';
+            value[1] = input.list[ipos];
+            value[2] = 0;
        }
        ipos++;
         while ((pos + strlen(value) > size) || strchr(value, '\n')) {
@@ -580,7 +618,7 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
                 /* word to send is too big to send now.. what to do? */
                 if (pos > 0) {
                     /* try to put it on a separate line */
-                    SEND_LINE();
+                    SEND_LINE(1);
                 } else {
                     /* already at start of line; only send part of it */
                     strncpy(line, value, avail);
@@ -593,7 +631,7 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
             }
             /* if we're looking at a newline, send the accumulated text */
             if (*value == '\n') {
-                SEND_LINE();
+                SEND_LINE(0);
                 value++;
             }
         }
@@ -610,7 +648,7 @@ vsend_message(const char *dest, struct userNode *src, struct handle_info *handle
       send_line:
         expand_pos = pos;
         expand_ipos = ipos;
-        SEND_LINE();
+        SEND_LINE(0);
 #undef SEND_LINE
     }
     return chars_sent;
@@ -660,7 +698,7 @@ _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, co
 
     va_list ap;
     va_start(ap, format);
-    res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
+    res = vsend_message(dest->nick, src, dest->handle_info, 12, expand, format, ap);
     va_end(ap);
     return res;
 }
@@ -696,22 +734,215 @@ send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, cons
     return _send_help(dest, src, hf->expand, rec->d.qstring);
 }
 
-int
+/* Grammar supported by this parser:
+ * condition = expr | prefix expr
+ * expr = atomicexpr | atomicexpr op atomicexpr
+ * op = '&&' | '||' | 'and' | 'or'
+ * atomicexpr = '(' expr ')' | identifier
+ * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
+ *
+ * Whitespace is ignored. The parser is implemented as a recursive
+ * descent parser by functions like:
+ *   static int helpfile_eval_<element>(const char *start, const char **end);
+ */
+
+enum helpfile_op {
+    OP_INVALID,
+    OP_BOOL_AND,
+    OP_BOOL_OR
+};
+
+static const struct {
+    const char *str;
+    enum helpfile_op op;
+} helpfile_operators[] = {
+    { "&&", OP_BOOL_AND },
+    { "and", OP_BOOL_AND },
+    { "||", OP_BOOL_OR },
+    { "or", OP_BOOL_OR },
+    { NULL, OP_INVALID }
+};
+
+static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
+
+static int helpfile_eval_expr(const char *start, const char **end);
+static int helpfile_eval_atomicexpr(const char *start, const char **end);
+static int helpfile_eval_identifier(const char *start, const char **end);
+
+static int
+helpfile_eval_identifier(const char *start, const char **end)
+{
+    /* Skip leading whitespace. */
+    while (isspace(*start) && (start < *end))
+        start++;
+    if (start == *end) {
+        log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
+        return -1;
+    }
+
+    if (start[0] == '!') {
+        int res = helpfile_eval_identifier(start+1, end);
+        if (res < 0)
+            return res;
+        return !res;
+    } else if (start[0] == '/') {
+        const char *sep;
+        char *id_str, *value;
+
+        for (sep = start;
+             strchr(identifier_chars, sep[0]) && (sep < *end);
+             ++sep) ;
+        memcpy(id_str = alloca(sep+1-start), start, sep-start);
+        id_str[sep-start] = '\0';
+        value = conf_get_data(id_str+1, RECDB_QSTRING);
+        *end = sep;
+        if (!value)
+            return 0;
+        return enabled_string(value) || true_string(value);
+    } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
+        *end = start + 4;
+        return 1;
+    } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
+        *end = start + 5;
+        return 0;
+    } else {
+        log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
+        return -1;
+    }
+}
+
+static int
+helpfile_eval_atomicexpr(const char *start, const char **end)
+{
+    const char *sep;
+    int res;
+
+    /* Skip leading whitespace. */
+    while (isspace(*start) && (start < *end))
+        start++;
+    if (start == *end) {
+        log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
+        return -1;
+    }
+
+    /* If it's not parenthesized, it better be a valid identifier. */
+    if (*start != '(')
+        return helpfile_eval_identifier(start, end);
+
+    /* Parse the internal expression. */
+    start++;
+    sep = *end;
+    res = helpfile_eval_expr(start, &sep);
+
+    /* Check for the closing parenthesis. */
+    while (isspace(*sep) && (sep < *end))
+        sep++;
+    if ((sep == *end) || (sep[0] != ')')) {
+        log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
+        return -1;
+    }
+
+    /* Report the end location and result. */
+    *end = sep + 1;
+    return res;
+}
+
+static int
+helpfile_eval_expr(const char *start, const char **end)
+{
+    const char *sep, *sep2;
+    unsigned int ii, len;
+    int res_a, res_b;
+    enum helpfile_op op;
+
+    /* Parse the first atomicexpr. */
+    sep = *end;
+    res_a = helpfile_eval_atomicexpr(start, &sep);
+    if (res_a < 0)
+        return res_a;
+
+    /* Figure out what follows that. */
+    while (isspace(*sep) && (sep < *end))
+        sep++;
+    if (sep == *end)
+        return res_a;
+    op = OP_INVALID;
+    for (ii = 0; helpfile_operators[ii].str; ++ii) {
+        len = strlen(helpfile_operators[ii].str);
+        if (ircncasecmp(sep, helpfile_operators[ii].str, len))
+            continue;
+        op = helpfile_operators[ii].op;
+        sep += len;
+    }
+    if (op == OP_INVALID) {
+        log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
+        return -1;
+    }
+
+    /* Parse the next atomicexpr. */
+    sep2 = *end;
+    res_b = helpfile_eval_atomicexpr(sep, &sep2);
+    if (res_b < 0)
+        return res_b;
+
+    /* Make sure there's no trailing garbage */
+    while (isspace(*sep2) && (sep2 < *end))
+        sep2++;
+    if (sep2 != *end) {
+        log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
+        return -1;
+    }
+
+    /* Record where we stopped parsing. */
+    *end = sep2;
+
+    /* Do the logic on the subexpressions. */
+    switch (op) {
+    case OP_BOOL_AND:
+        return res_a && res_b;
+    case OP_BOOL_OR:
+        return res_a || res_b;
+    default:
+        return -1;
+    }
+}
+
+static int
+helpfile_eval_condition(const char *start, const char **end)
+{
+    const char *term;
+
+    /* Skip the prefix if there is one. */
+    for (term = start; isalnum(*term) && (term < *end); ++term) ;
+    if (term != start) {
+        if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
+            log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
+            return -1;
+        }
+        start = term + 2;
+    }
+
+    /* Evaluate the remaining string as an expression. */
+    return helpfile_eval_expr(start, end);
+}
+
+static int
 unlistify_help(const char *key, void *data, void *extra)
 {
     struct record_data *rd = data;
     dict_t newdb = extra;
-    key = strdup(key);
-    if (rd->type == RECDB_QSTRING) {
-       dict_insert(newdb, key, alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
+
+    switch (rd->type) {
+    case RECDB_QSTRING:
+       dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
        return 0;
-    } else if (rd->type == RECDB_STRING_LIST) {
+    case RECDB_STRING_LIST: {
        struct string_list *slist = GET_RECORD_STRING_LIST(rd);
        char *dest;
        unsigned int totlen, len, i;
-       for (i=totlen=0; i<slist->used; i++) {
+
+       for (i=totlen=0; i<slist->used; i++)
            totlen = totlen + strlen(slist->list[i]) + 1;
-       }
        dest = alloca(totlen+1);
        for (i=totlen=0; i<slist->used; i++) {
            len = strlen(slist->list[i]);
@@ -720,9 +951,37 @@ unlistify_help(const char *key, void *data, void *extra)
            totlen = totlen + len + 1;
        }
        dest[totlen] = 0;
-       dict_insert(newdb, key, alloc_record_data_qstring(dest));
+       dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
        return 0;
-    } else {
+    }
+    case RECDB_OBJECT: {
+        dict_iterator_t it;
+
+        for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
+            const char *k2, *end;
+            int res;
+
+            /* Evaluate the expression for this subentry. */
+            k2 = iter_key(it);
+            end = k2 + strlen(k2);
+            res = helpfile_eval_condition(k2, &end);
+            /* If the evaluation failed, bail. */
+            if (res < 0) {
+                log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
+                return 1;
+            }
+            /* If the condition was false, try another. */
+            if (!res)
+                continue;
+            /* If we cannot unlistify the contents, bail. */
+            if (unlistify_help(key, iter_data(it), extra))
+                return 1;
+            return 0;
+        }
+        /* If none of the conditions apply, just omit the entry. */
+        return 0;
+    }
+    default:
        return 1;
     }
 }
@@ -752,7 +1011,8 @@ open_helpfile(const char *fname, expand_func_t expand)
 
 void close_helpfile(struct helpfile *hf)
 {
-    if (!hf) return;
+    if (!hf)
+        return;
     free((char*)hf->name);
     free_database(hf->db);
     free(hf);
@@ -768,9 +1028,16 @@ void message_register_table(const struct message_entry *table)
     }
 }
 
-void helpfile_finalize(void)
+void helpfile_init(void)
 {
     message_register_table(msgtab);
-    language_read_all();
+    language_read_list();
+}
+
+void helpfile_finalize(void)
+{
+    dict_iterator_t it;
+    for (it = dict_first(languages); it; it = iter_next(it))
+        language_read(iter_key(it));
     reg_exit_func(language_cleanup);
 }