Merge branch 'development'
[NeonServV5.git] / src / modcmd.c
index 8b9c72c4573ab60000075d2e6a14e20df36861f9..8ec2517ef9c640bcbeb3f909a306980c02800d94 100644 (file)
@@ -1,5 +1,5 @@
-/* modcmd.c - NeonServ v5.2
- * Copyright (C) 2011  Philipp Kreil (pk910)
+/* modcmd.c - NeonServ v5.6
+ * Copyright (C) 2011-2012  Philipp Kreil (pk910)
  * 
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include "mysqlConn.h"
 #include "DBHelper.h"
 #include "EventLogger.h"
+#include "tools.h"
+#include "log.h"
 
 struct trigger_callback {
     int botid;
+    int module_id;
     trigger_callback_t *func;
     
     struct trigger_callback *next;
@@ -56,7 +59,8 @@ static struct cmd_binding **cmd_binds;
 static struct cmd_function *cmd_functions = NULL;
 static struct trigger_callback *trigger_callbacks = NULL;
 static struct cmd_bot_alias *bot_aliases = NULL;
-static struct ClientSocket *tmp_text_client;
+static int total_triggered = 0;
+int statistics_commands = 0;
 
 static const struct default_language_entry msgtab[] = {
     {"MODCMD_LESS_PARAM_COUNT", "This command requires more parameters."},
@@ -66,6 +70,9 @@ static const struct default_language_entry msgtab[] = {
     {"MODCMD_PRIVILEGED",       "$b%s$b is a privileged command."}, /* {ARGS: "god"} */
     {"MODCMD_PUBCMD",           "Public commands in $b%s$b are restricted."}, /* {ARGS: "#TestChan"} */
     {"MODCMD_ACCESS_DENIED",    "Access denied."},
+    {"MODCMD_SUBCOMMANDS",      "Subcommands of %s: %s"}, /* {ARGS: "bot", "ADD, DEL, EDIT"} */
+    {"MODCMD_CROSSCHAN",        "You must be in %s (or on its userlist) to use this command."}, /* {ARGS: "#TestChan"} */
+    {"MODCMD_UNKNOWN",          "$b%s$b is an unknown command."}, /* {ARGS: "bla"} */
     {NULL, NULL}
 };
 
@@ -76,10 +83,10 @@ static int get_binds_index(char first_char) {
     return 26;
 }
 
-struct ClientSocket* get_prefered_bot(int botid) {
+struct ClientSocket* get_botwise_prefered_bot(int botid, int clientid) {
     struct ClientSocket *client, *lowbot = NULL;
     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
-        if(client->botid == botid) {
+        if(client->botid == botid && (botid || clientid == client->clientid)) {
             if((client->flags & SOCKET_FLAG_PREFERRED))
                 return client;
             else
@@ -89,10 +96,10 @@ struct ClientSocket* get_prefered_bot(int botid) {
     return lowbot;
 }
 
-static char* get_channel_trigger(int botid, struct ChanNode *chan) {
+static char* get_channel_trigger(int botid, int clientid, struct ChanNode *chan) {
     struct trigger_cache *trigger;
     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
-        if(trigger->botid == botid)
+        if(trigger->botid == botid && (botid || trigger->clientid == clientid))
             return trigger->trigger;
     }
     struct trigger_callback *cb;
@@ -102,27 +109,28 @@ static char* get_channel_trigger(int botid, struct ChanNode *chan) {
     }
     char triggerStr[TRIGGERLEN];
     if(cb)
-        cb->func(chan, triggerStr);
+        cb->func(clientid, chan, triggerStr);
     else
-        strcpy(triggerStr, "+");
+        triggerStr[0] = '\0';
     trigger = malloc(sizeof(*trigger));
     if (!trigger) {
-        perror("malloc() failed");
+        printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
         return 0;
     }
     trigger->botid = botid;
+    trigger->clientid = clientid;
     trigger->trigger = (triggerStr[0] ? strdup(triggerStr) : NULL);
     trigger->next = chan->trigger;
     chan->trigger = trigger;
     return trigger->trigger;
 }
 
-static void handle_command_async(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc);
+static void handle_command_async(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc);
 
 static USERAUTH_CALLBACK(command_checked_auth) {
     struct command_check_user_cache *cache = data;
-    tmp_text_client = cache->textclient;
-    handle_command_async(cache->client, user, cache->chan, cache->sent_chan, cache->cbind, cache->argv, cache->argc);
+    if(user)
+        handle_command_async(cache->client, cache->textclient, user, cache->chan, cache->sent_chan, cache->cbind, cache->argv, cache->argc);
     free(cache->message);
     if(cache->args_buffer)
         free(cache->args_buffer);
@@ -130,6 +138,79 @@ static USERAUTH_CALLBACK(command_checked_auth) {
     free(cache);
 }
 
+static CMD_BIND(modcmd_linker) {
+    //fake command for subcommands
+    //just empty
+}
+
+static struct cmd_binding *modcmd_linker_command(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct cmd_binding *cbind, int bind_index, char **args_ptr) {
+    //links subcommands
+    char command[MAXLEN];
+    struct cmd_binding *parent_bind = cbind;
+    char *args = *args_ptr;
+    if(args) {
+        char *subcmd = args;
+        args = strstr(args, " ");
+        if(args) {
+            *args = '\0';
+            args++;
+        }
+        sprintf(command, "%s %s", parent_bind->cmd, subcmd);
+        for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
+            if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
+                break;
+        }
+        *args_ptr = args;
+        if(cbind && cbind->func->func == modcmd_linker) {
+            return modcmd_linker_command(client, textclient, user, cbind, bind_index, args_ptr);
+        }
+        return cbind;
+    } else {
+        //list all sub commands
+        int commandlen = sprintf(command, "%s ", parent_bind->cmd);
+        char subcommands[MAXLEN];
+        int subcompos = 0;
+        for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
+            if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmplen(cbind->cmd, command, commandlen) == 0) {
+                if(strstr(cbind->cmd + commandlen, " ")) continue; //ignore if there is another space in the command (sub-sub-command :D)
+                subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
+            }
+        }
+        reply(textclient, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, (subcompos ? subcommands : "\1dnone\1d"));
+        return NULL;
+    }
+}
+
+static struct cmd_binding *modcmd_sub_linker_command(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct cmd_binding *cbind, int bind_index, char **args_ptr) {
+    //links subcommands
+    char command[MAXLEN];
+    struct cmd_binding *parent_bind = cbind;
+    char *args = *args_ptr;
+    if(args) {
+        char *subcmd = args;
+        args = strchr(args, ' ');
+        if(args) {
+            *args = '\0';
+            args++;
+        }
+        sprintf(command, "%s %s", parent_bind->cmd, subcmd);
+        if(args)
+            args[-1] = ' ';
+        for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
+            if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
+                break;
+        }
+        if(cbind) {
+            *args_ptr = args;
+            if(cbind->func->func == modcmd_linker)
+                parent_bind = modcmd_linker_command(client, textclient, user, cbind, bind_index, args_ptr);
+            else
+                parent_bind = cbind;
+        }
+    }
+    return parent_bind;
+}
+
 static void handle_command(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, char *message) {
     struct ChanNode *sent_chan = chan;
     if(message[0] == '#') {
@@ -144,26 +225,38 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
     }
     message = strdup(message);
     int bind_index = get_binds_index(message[0]);
-    char *args = strstr(message, " ");
+    char *args = strchr(message, ' ');
     char *args_buffer = NULL; //we need this to save a possible pointer to a allocation we need to free
     if(args) {
         *args = '\0';
         args++;
     }
     struct cmd_binding *cbind;
+    int found_cmd = 0;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == client->botid && stricmp(cbind->cmd, message) == 0) {
-            if((cbind->flags & CMDFLAG_FUNCMD)) {
+        if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, message) == 0) {
+            found_cmd = 1;
+            //get a text bot
+            struct ClientSocket *textclient = get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0));
+            if(cbind->func->func == modcmd_linker) {
+                cbind = modcmd_linker_command(client, textclient, user, cbind, bind_index, &args);
+                if(cbind == NULL) break;
+            } else if(cbind->flags & CMDFLAG_SUB_LINKER)
+                cbind = modcmd_sub_linker_command(client, textclient, user, cbind, bind_index, &args);
+            statistics_commands++;
+            total_triggered++;
+            cbind->triggered++;
+            if((BIND_FLAGS(cbind) & CMDFLAG_FUNCMD)) {
                 if(!sent_chan)
                     break;
                 chan = sent_chan;
             }
-            //get a text bot
-            tmp_text_client = get_prefered_bot(client->botid);
             //parse the arguments...
             char *arga[MAXNUMPARAMS];
             char **argv;
             int argc = 0;
+            int escape = 0;
+            int offset = 0;
             if(args) {
                 while(*args) {
                     //skip leading spaces
@@ -172,32 +265,48 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
                     arga[argc++] = args;
                     if (argc >= MAXNUMPARAMS)
                         break;
-                    while (*args != ' ' && *args)
+                    while ((escape || *args != ' ') && *args) {
+                        if((BIND_FLAGS(cbind) & CMDFLAG_ESCAPE_ARGS) && *args == '\\') {
+                            escape = 1;
+                            offset++;
+                        } else if(escape)
+                            escape = 0;
+                        if(!escape && offset) {
+                            args[0 - offset] = args[0];
+                        }
                         args++;
+                        
+                    }
+                    if(offset) {
+                        args[0-offset] = '\0';
+                        offset = 0;
+                    }
                 }
             }
             argv = arga;
-            if(argc != 0 && argv[0][0] == '#' && !(cbind->func->flags & CMDFLAG_CHAN_PARAM)) {
-                struct ChanNode *chan2 = getChanByName(argv[0]);
-                if(chan2) {
-                    argv += 1;
-                    argc -= 1;
-                    chan = chan2;
-                }
-            }
             if(cbind->paramcount) {
                 //userdefined parameters...
                 args_buffer = malloc(MAXLEN * 2 * sizeof(*args_buffer));
                 int args_pos = 0;
                 char *uargs[MAXNUMPARAMS];
                 int uargc = 0;
-                char *b;
+                char *b, *c;
                 int i;
                 int allargs, argi;
                 for(i = 0; i < cbind->paramcount; i++) {
                     b = cbind->parameters[i];
                     if(b[0] == '%') {
                         b++;
+                        c = b;
+                        while(*c && *c != ' ') {
+                            if(*c == '|') break;
+                            c++;
+                        }
+                        if(!*c || *c == ' ') c = NULL;
+                        else {
+                            *c = '\0';
+                            c++;
+                        }
                         if(b[strlen(b)-1] == '-') {
                             allargs = strlen(b)-1;
                             b[allargs] = '\0';
@@ -232,9 +341,12 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
                                     }
                                     args_pos++;
                                 }
-                            } else if((cbind->func->flags & CMDFLAG_EMPTY_ARGS)) {
+                            } else if((BIND_FLAGS(cbind) & CMDFLAG_EMPTY_ARGS)) {
                                 uargs[uargc++] = args_buffer + args_pos;
                                 args_buffer[args_pos++] = '\0';
+                            } else if(c) {
+                                uargs[uargc++] = args_buffer + args_pos;
+                                args_pos += sprintf(args_buffer + args_pos, "%s", c) + 1;
                             }
                         } else if(!strcmp(b, "c")) {
                             uargs[uargc++] = args_buffer + args_pos;
@@ -243,6 +355,7 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
                             uargs[uargc++] = args_buffer + args_pos;
                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
                         }
+                        if(c) c[-1] = '|'; //reset \0 to |
                     } else {
                         uargs[uargc++] = args_buffer + args_pos;
                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
@@ -251,20 +364,28 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
                 argv = uargs;
                 argc = uargc;
             }
+            if(argc != 0 && argv[0][0] == '#' && !(BIND_FLAGS(cbind) & CMDFLAG_CHAN_PARAM)) {
+                struct ChanNode *chan2 = getChanByName(argv[0]);
+                if(chan2) {
+                    argv += 1;
+                    argc -= 1;
+                    chan = chan2;
+                }
+            }
             if(argc < cbind->func->paramcount) {
-                reply(tmp_text_client, user, "MODCMD_LESS_PARAM_COUNT");
+                reply(textclient, user, "MODCMD_LESS_PARAM_COUNT");
                 break;
             }
-            if((cbind->func->flags & CMDFLAG_REQUIRE_CHAN) && !chan) {
-                reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
+            if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_CHAN) && !chan) {
+                reply(textclient, user, "MODCMD_CHAN_REQUIRED");
                 break;
             }
-            if((cbind->func->flags & CMDFLAG_CHECK_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
+            if(((BIND_FLAGS(cbind) & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
                 //check auth...
                 struct command_check_user_cache *data = malloc(sizeof(*data));
                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
                 if (!data || !temp_argv) {
-                    perror("malloc() failed");
+                    printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
                     break;
                 }
                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
@@ -277,36 +398,65 @@ static void handle_command(struct ClientSocket *client, struct UserNode *user, s
                 data->message = message;
                 data->args_buffer = args_buffer;
                 data->cbind = cbind;
-                data->textclient = tmp_text_client;
-                get_userauth(user, command_checked_auth, data);
+                data->textclient = textclient;
+                get_userauth(user, 0, command_checked_auth, data);
                 return;
             } else
-                handle_command_async(client, user, chan, sent_chan, cbind, argv, argc);
+                handle_command_async(client, textclient, user, chan, sent_chan, cbind, argv, argc);
             break;
         }
     }
+    if(!found_cmd && !sent_chan && !(client->flags & SOCKET_FLAG_SILENT))
+        reply(get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0)), user, "MODCMD_UNKNOWN", message);
     free(message);
     if(args_buffer)
         free(args_buffer);
 }
 
-static void handle_command_async(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc) {
+static void handle_command_async(struct ClientSocket *client, struct ClientSocket *textclient, struct UserNode *user, struct ChanNode *chan, struct ChanNode *sent_chan, struct cmd_binding *cbind, char **argv, int argc) {
     MYSQL_RES *res;
     MYSQL_ROW row;
     int uaccess;
-    int eventflags = (cbind->func->flags & (CMDFLAG_LOG | CMDFLAG_OPLOG));
-    if((cbind->func->flags & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
-        reply(tmp_text_client, user, "MODCMD_AUTH_REQUIRED");
+    char requested_uaccess = 0;
+    int eventflags = (BIND_FLAGS(cbind) & (CMDFLAG_LOG | CMDFLAG_OPLOG));
+    if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
+        reply(textclient, user, "MODCMD_AUTH_REQUIRED");
         return;
     }
+    if(chan && sent_chan != chan && (BIND_FLAGS(cbind) & CMDFLAG_NO_CROSSCHAN) && !isUserOnChan(user, chan)) {
+        char user_in_chan = 0;
+        if((user->flags & USERFLAG_ISAUTHED)) {
+            //maybe there's another user authed to user->auth on the channel...
+            struct ChanUser *cchanuser;
+            for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
+                if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
+                    user_in_chan = 1;
+                    break;
+                }
+            }
+        }
+        if(!user_in_chan) {
+            //check if we are allowed to execute commands in this channel
+            requested_uaccess = 1;
+            uaccess = getChannelAccess(user, chan);
+            if(!uaccess) {
+                if(isGodMode(user)) {
+                    eventflags |= CMDFLAG_OPLOG;
+                } else {
+                    reply(textclient, user, "MODCMD_CROSSCHAN", chan->name);
+                    return;
+                }
+            }
+        }
+    }
     if(sent_chan && sent_chan != chan) {
         //check pubcmd of this channel
         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
         res = mysql_use();
         if ((row = mysql_fetch_row(res)) != NULL) {
-            uaccess = getChannelAccess(user, sent_chan);
-            if(row[0] && uaccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
-                reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
+            int saccess = getChannelAccess(user, sent_chan);
+            if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
+                reply(textclient, user, "MODCMD_PUBCMD", sent_chan->name);
                 return;
             }
         }
@@ -321,13 +471,13 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
         }
         if(user_global_access < global_access) {
             if(!user_global_access)
-                reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
+                reply(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
             else
-                reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
+                reply(textclient, user, "MODCMD_ACCESS_DENIED");
             return;
         }
     }
-    if((cbind->func->flags & CMDFLAG_REGISTERED_CHAN)) {
+    if((BIND_FLAGS(cbind) & CMDFLAG_REGISTERED_CHAN)) {
         MYSQL_ROW defaults = NULL;
         char access_list[256];
         int access_pos = 0;
@@ -338,6 +488,7 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
             str_b = cbind->channel_access;
         access_list[0] = '\0';
         if(str_b) {
+            struct ChanUser *chanuser = getChanUser(user, chan);
             str_c = strdup(str_b);
             str_b = str_c;
             while((str_a = str_b)) {
@@ -346,6 +497,15 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
                     *str_b = '\0';
                     str_b++;
                 }
+                if(*str_a == '@' || *str_a == '+') {
+                    //privs can override this access requirement
+                    int priv = 0;
+                    if(*str_a == '@') priv = CHANUSERFLAG_OPPED;
+                    else if(*str_a == '%') priv = CHANUSERFLAG_HALFOPPED;
+                    else if(*str_a == '+') priv = CHANUSERFLAG_VOICED;
+                    if(chanuser && (chanuser->flags & priv)) continue;
+                    str_a++;
+                }
                 if(*str_a == '#') {
                     str_a++;
                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
@@ -364,12 +524,12 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
                 chan->channel_id = atoi(row[0]);
                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
-                    uaccess = getChannelAccess(user, chan);
+                    if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
                     if(uaccess < minaccess && isGodMode(user)) {
                         eventflags |= CMDFLAG_OPLOG;
                     } else if(uaccess < minaccess) {
                         //ACCESS DENIED
-                        reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
+                        reply(textclient, user, "MODCMD_ACCESS_DENIED");
                         return;
                     }
                     if(!row[1] && !defaults) {
@@ -381,7 +541,7 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
                             eventflags |= CMDFLAG_OPLOG;
                         } else {
                             //PUBCMD
-                            reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
+                            reply(textclient, user, "MODCMD_PUBCMD", chan->name);
                             return;
                         }
                     }
@@ -395,7 +555,7 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
                             if(isGodMode(user)) {
                                 eventflags |= CMDFLAG_OPLOG;
                             } else {
-                                reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
+                                reply(textclient, user, "MODCMD_ACCESS_DENIED");
                                 return;
                             }
                         }
@@ -405,47 +565,54 @@ static void handle_command_async(struct ClientSocket *client, struct UserNode *u
             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
         }
         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
-            reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
+            reply(textclient, user, "MODCMD_CHAN_REQUIRED");
             return;
         }
         printf_mysql_query("SELECT `botid`, `suspended` FROM `bot_channels` LEFT JOIN `bots` ON `bot_channels`.`botid` = `bots`.`id` WHERE `chanid` = '%d' AND `botclass` = '%d'", chan->channel_id, client->botid);
         res = mysql_use();
         if ((row = mysql_fetch_row(res)) == NULL) {
-            reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
+            reply(textclient, user, "MODCMD_CHAN_REQUIRED");
             return;
         } else if(!strcmp(row[1], "1")) {
-            reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
+            reply(textclient, user, "MODCMD_CHAN_SUSPENDED");
             return;
         }
     }
-    if((cbind->func->flags & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
-        reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
+    if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
+        reply(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
         return;
     }
-    struct Event *event = createEvent(client, user, chan, cbind->func->name, argv, argc, eventflags);
-    cbind->func->func(client, user, chan, argv, argc, event);
+    struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
+    cbind->func->func(client, textclient, user, chan, argv, argc, event);
 }
 
 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
-    fd_set fds;
+    fd_set fds, fds2;
     char *trigger;
     struct ClientSocket *client;
     FD_ZERO(&fds);
+    FD_ZERO(&fds2);
+    got_chanmsg_loop1:
     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
-        if(isUserOnChan(client->user, chan) && (client->flags & SOCKET_FLAG_PREFERRED) && !FD_ISSET(client->botid, &fds)) {
-            FD_SET(client->botid, &fds);
-            trigger = get_channel_trigger(client->botid, chan);
+        if(isUserOnChan(client->user, chan) && (client->flags & SOCKET_FLAG_PREFERRED) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2))))  {
+            FD_SET(client->clientid, &fds);
+            FD_SET(client->botid, &fds2);
+            trigger = get_channel_trigger(client->botid, client->clientid, chan);
             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
                 handle_command(client, user, chan, message + strlen(trigger));
+                goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
             }
         }
     }
+    got_chanmsg_loop2:
     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
-        if(isUserOnChan(client->user, chan) && !FD_ISSET(client->botid, &fds)) {
-            FD_SET(client->botid, &fds);
-            trigger = get_channel_trigger(client->botid, chan);
+        if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
+            FD_SET(client->clientid, &fds);
+            FD_SET(client->botid, &fds2);
+            trigger = get_channel_trigger(client->botid, client->clientid, chan);
             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
                 handle_command(client, user, chan, message + strlen(trigger));
+                goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
             }
         }
     }
@@ -460,19 +627,20 @@ static void got_privmsg(struct UserNode *user, struct UserNode *target, char *me
     }
 }
 
-int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
+int register_command(int botid, char *name, int module_id, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
     struct cmd_function *cmdfunc;
     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
-        if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
+        if((cmdfunc->botid == botid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, name))
             return 0;
     }
     cmdfunc = malloc(sizeof(*cmdfunc));
     if (!cmdfunc) {
-        perror("malloc() failed");
+        printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
         return 0;
     }
     cmdfunc->botid = botid;
     cmdfunc->name = strdup(name);
+    cmdfunc->module_id = module_id;
     cmdfunc->func = func;
     cmdfunc->flags = flags;
     cmdfunc->paramcount = paramcount;
@@ -483,7 +651,7 @@ int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, ch
     return 1;
 }
 
-int set_trigger_callback(int botid, trigger_callback_t *func) {
+int set_trigger_callback(int botid, int module_id, trigger_callback_t *func) {
     static struct trigger_callback *cb = NULL;
     for(cb = trigger_callbacks; cb; cb = cb->next) {
         if(cb->botid == botid)
@@ -492,21 +660,43 @@ int set_trigger_callback(int botid, trigger_callback_t *func) {
     if(!cb) {
         cb = malloc(sizeof(*cb));
         if (!cb) {
-            perror("malloc() failed");
+            printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
             return 0;
         }
         cb->botid = botid;
         cb->next = trigger_callbacks;
         trigger_callbacks = cb;
     }
+    cb->module_id = module_id;
     cb->func = func;
     return 1;
 }
 
-int changeChannelTrigger(int botid, struct ChanNode *chan, char *new_trigger) {
+int flush_trigger_cache(int botid, int clientid) {
+    struct ChanNode *chan;
+    struct trigger_cache *trigger, *last;
+    for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
+        last = NULL;
+        for(trigger = chan->trigger; trigger; trigger = trigger->next) {
+            if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
+                if(last)
+                    last->next = trigger->next;
+                else
+                    chan->trigger = trigger->next;
+                free(trigger->trigger);
+                free(trigger);
+                break;
+            } else
+                last = trigger;
+        }
+    }
+    return 1;
+}
+
+int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
     struct trigger_cache *trigger;
     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
-        if(trigger->botid == botid) {
+        if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
             free(trigger->trigger);
             trigger->trigger = strdup(new_trigger);
             return 1;
@@ -515,31 +705,33 @@ int changeChannelTrigger(int botid, struct ChanNode *chan, char *new_trigger) {
     return 0;
 }
 
-int bind_cmd_to_function(int botid, char *cmd, struct cmd_function *func) {
+int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0)
+        if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
             return 0;
     }
     cbind = malloc(sizeof(*cbind));
     if (!cbind) {
-        perror("malloc() failed");
+        printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
         return 0;
     }
     cbind->botid = botid;
+    cbind->clientid = clientid;
     cbind->cmd = strdup(cmd);
     cbind->func = func;
     cbind->paramcount = 0;
     cbind->global_access = 0;
     cbind->channel_access = NULL;
     cbind->flags = 0;
+    cbind->triggered = 0;
     cbind->next = cmd_binds[bind_index];
     cmd_binds[bind_index] = cbind;
     return 1;
 }
 
-int bind_cmd_to_command(int botid, char *cmd, char *func) {
+int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
     struct cmd_function *cmdfunc;
     int fbotid = botid;
     char *c;
@@ -556,22 +748,23 @@ int bind_cmd_to_command(int botid, char *cmd, char *func) {
         func = c+1;
     }
     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
-        if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
+        if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, func))
             break;
     }
     if(!cmdfunc) return 0;
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0)
+        if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
             return 0;
     }
     cbind = malloc(sizeof(*cbind));
     if (!cbind) {
-        perror("malloc() failed");
+        printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
         return 0;
     }
     cbind->botid = botid;
+    cbind->clientid = clientid;
     cbind->cmd = strdup(cmd);
     cbind->func = cmdfunc;
     cbind->next = cmd_binds[bind_index];
@@ -579,15 +772,16 @@ int bind_cmd_to_command(int botid, char *cmd, char *func) {
     cbind->global_access = 0;
     cbind->channel_access = NULL;
     cbind->flags = 0;
+    cbind->triggered = 0;
     cmd_binds[bind_index] = cbind;
     return 1;
 }
 
-int unbind_cmd(int botid, char *cmd) {
+int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind, *last = NULL;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
             if(last)
                 last->next = cbind->next;
             else
@@ -598,6 +792,8 @@ int unbind_cmd(int botid, char *cmd) {
                 for(i = 0; i < cbind->paramcount; i++)
                     free(cbind->parameters[i]);
             }
+            if(cbind->channel_access)
+                free(cbind->channel_access);
             free(cbind);
             return 1;
         } else
@@ -606,6 +802,33 @@ int unbind_cmd(int botid, char *cmd) {
     return 0;
 }
 
+int unbind_botwise_allcmd(int botid, int clientid) {
+    int i;
+    for(i = 0; i < 27; i++) {
+        struct cmd_binding *cbind, *next, *last = NULL;
+        for(cbind = cmd_binds[i]; cbind; cbind = next) {
+            next = cbind->next;
+            if((botid == 0 && clientid == cbind->clientid) || (botid && botid == cbind->botid)) {
+                if(last)
+                    last->next = cbind->next;
+                else
+                    cmd_binds[i] = cbind->next;
+                free(cbind->cmd);
+                if(cbind->paramcount) {
+                    int j;
+                    for(j = 0; j < cbind->paramcount; j++)
+                        free(cbind->parameters[j]);
+                }
+                if(cbind->channel_access)
+                    free(cbind->channel_access);
+                free(cbind);
+            } else
+                last = cbind;
+        }
+    }
+    return 1;
+}
+
 struct cmd_function *find_cmd_function(int botid, char *name) {
     struct cmd_function *cmdfunc;
     char *c;
@@ -628,15 +851,12 @@ struct cmd_function *find_cmd_function(int botid, char *name) {
     return cmdfunc;
 }
 
-struct ClientSocket *getTextBot() {
-    return tmp_text_client;
-}
-
 void init_modcmd() {
     cmd_binds = calloc(27, sizeof(*cmd_binds));
-    bind_chanmsg(got_chanmsg);
-    bind_privmsg(got_privmsg);
+    bind_chanmsg(got_chanmsg, 0);
+    bind_privmsg(got_privmsg, 0);
     register_default_language_table(msgtab);
+    register_command(0, "linker", 0, modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
 }
 
 void free_modcmd() {
@@ -679,34 +899,36 @@ void free_modcmd() {
     bot_aliases = NULL;
 }
 
-void bind_set_parameters(int botid, char *cmd, char *parameters) {
+void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
             if(cbind->paramcount) {
                 int i;
                 for(i = 0; i < cbind->paramcount; i++)
                     free(cbind->parameters[i]);
                 cbind->paramcount = 0;
             }
-            char *a, *b = parameters;
-            do {
-                a = strstr(b, " ");
-                if(a) *a = '\0';
-                cbind->parameters[cbind->paramcount++] = strdup(b);
-                if(a) b = a+1;
-            } while(a);
+            if(parameters) {
+                char *a, *b = parameters;
+                do {
+                    a = strstr(b, " ");
+                    if(a) *a = '\0';
+                    cbind->parameters[cbind->paramcount++] = strdup(b);
+                    if(a) b = a+1;
+                } while(a);
+            }
             return;
         }
     }
 }
 
-void bind_set_global_access(int botid, char *cmd, int gaccess) {
+void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
             if(gaccess > -1) {
                 cbind->global_access = gaccess;
                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
@@ -718,11 +940,11 @@ void bind_set_global_access(int botid, char *cmd, int gaccess) {
     }
 }
 
-void bind_set_channel_access(int botid, char *cmd, char *chanaccess) {
+void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
             if(cbind->channel_access)
                 free(cbind->channel_access);
             if(chanaccess) {
@@ -737,18 +959,29 @@ void bind_set_channel_access(int botid, char *cmd, char *chanaccess) {
     }
 }
 
-struct cmd_binding *find_cmd_binding(int botid, char *cmd) {
+void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
+    int bind_index = get_binds_index(cmd[0]);
+    struct cmd_binding *cbind;
+    for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
+            cbind->flags |= flags;
+            return;
+        }
+    }
+}
+
+struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
     int bind_index = get_binds_index(cmd[0]);
     struct cmd_binding *cbind;
     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
-        if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
+        if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
             return cbind;
         }
     }
     return NULL;
 }
 
-void bind_unbound_required_functions(int botid) {
+void bind_botwise_unbound_required_functions(int botid, int clientid) {
     struct cmd_function *cmdfunc;
     int i, found;
     struct cmd_binding *cbind;
@@ -757,7 +990,7 @@ void bind_unbound_required_functions(int botid) {
             found = 0;
             for(i = 0; i < 27; i++) {
                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
-                    if(cbind->botid == botid && cbind->func == cmdfunc) {
+                    if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
                         found = 1;
                         break;
                     }
@@ -765,8 +998,8 @@ void bind_unbound_required_functions(int botid) {
                 if(found)
                     break;
             }
-            if(!found && bind_cmd_to_function(botid, cmdfunc->name, cmdfunc)) {
-                cbind = find_cmd_binding(botid, cmdfunc->name);
+            if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
+                cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
             }
         }
@@ -781,7 +1014,7 @@ void register_command_alias(int botid, char *alias) {
     }
     botalias = malloc(sizeof(*botalias));
     if (!botalias) {
-        perror("malloc() failed");
+        printf_log("main", LOG_ERROR, "%s:%d malloc() failed", __FILE__, __LINE__);
         return;
     }
     botalias->botid = botid;
@@ -807,3 +1040,54 @@ struct cmd_binding *getAllBinds(struct cmd_binding *last) {
     } while(bind_index < 27);
     return NULL;
 }
+
+void unregister_module_commands(int module_id) {
+    struct cmd_function *cmdfunct, *nextfunct, *prevfunct = NULL;
+    int i;
+    for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = nextfunct) {
+        nextfunct = cmdfunct->next;
+        if(cmdfunct->module_id == module_id) {
+            for(i = 0; i < 27; i++) {
+                struct cmd_binding *cbind, *next, *last = NULL;
+                for(cbind = cmd_binds[i]; cbind; cbind = next) {
+                    next = cbind->next;
+                    if(cmdfunct == cbind->func) {
+                        if(last)
+                            last->next = cbind->next;
+                        else
+                            cmd_binds[i] = cbind->next;
+                        free(cbind->cmd);
+                        if(cbind->paramcount) {
+                            int j;
+                            for(j = 0; j < cbind->paramcount; j++)
+                                free(cbind->parameters[j]);
+                        }
+                        if(cbind->channel_access)
+                            free(cbind->channel_access);
+                        free(cbind);
+                    } else
+                        last = cbind;
+                }
+            }
+            if(prevfunct) 
+                prevfunct->next = nextfunct;
+            else
+                cmd_functions = nextfunct;
+            free(cmdfunct->name);
+            free(cmdfunct);
+        } else
+            prevfunct = cmdfunct;
+    }
+    struct trigger_callback *cb, *prevcb = NULL, *nextcb;
+    for(cb = trigger_callbacks; cb; cb = nextcb) {
+        nextcb = cb->next;
+        if(cb->module_id == module_id) {
+            if(prevcb)
+                prevcb->next = nextcb;
+            else
+                trigger_callbacks = nextcb;
+            free(cb);
+        } else
+            prevcb = cb;
+    }
+}