added possibility to change default trigger (even for registered channels)
[NeonServV5.git] / src / modcmd.c
1 /* modcmd.c - NeonServ v5.3
2  * Copyright (C) 2011  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17
18 #include "modcmd.h"
19 #include "IRCEvents.h"
20 #include "IRCParser.h"
21 #include "ClientSocket.h"
22 #include "UserNode.h"
23 #include "ChanNode.h"
24 #include "ChanUser.h"
25 #include "WHOHandler.h"
26 #include "lang.h"
27 #include "mysqlConn.h"
28 #include "DBHelper.h"
29 #include "EventLogger.h"
30
31 struct trigger_callback {
32     int botid;
33     trigger_callback_t *func;
34     
35     struct trigger_callback *next;
36 };
37
38 struct cmd_bot_alias {
39     int botid;
40     char *alias;
41     
42     struct cmd_bot_alias *next;
43 };
44
45 struct command_check_user_cache {
46     struct ClientSocket *client, *textclient;
47     struct UserNode *user;
48     struct ChanNode *chan, *sent_chan;
49     char **argv;
50     int argc;
51     char *message, *args_buffer;
52     struct cmd_binding *cbind;
53 };
54
55 static struct cmd_binding **cmd_binds;
56 static struct cmd_function *cmd_functions = NULL;
57 static struct trigger_callback *trigger_callbacks = NULL;
58 static struct cmd_bot_alias *bot_aliases = NULL;
59 static struct ClientSocket *tmp_text_client;
60 static int total_triggered = 0;
61 int statistics_commands = 0;
62
63 static const struct default_language_entry msgtab[] = {
64     {"MODCMD_LESS_PARAM_COUNT", "This command requires more parameters."},
65     {"MODCMD_CHAN_REQUIRED",    "You must provide the name of a channel that exists and the bot is on."},
66     {"MODCMD_AUTH_REQUIRED",    "You need to be authenticated with AuthServ to use this command."},
67     {"MODCMD_CHAN_SUSPENDED",   "This channel is currently suspended."},
68     {"MODCMD_PRIVILEGED",       "$b%s$b is a privileged command."}, /* {ARGS: "god"} */
69     {"MODCMD_PUBCMD",           "Public commands in $b%s$b are restricted."}, /* {ARGS: "#TestChan"} */
70     {"MODCMD_ACCESS_DENIED",    "Access denied."},
71     {"MODCMD_SUBCOMMANDS",      "Subcommands of %s: %s"}, /* {ARGS: "bot", "ADD, DEL, EDIT"} */
72     {"MODCMD_CROSSCHAN",        "You must be in %s (or on its userlist) to use this command."},
73     {"MODCMD_UNKNOWN",          "$b%s$b is an unknown command."}, /* {ARGS: "bla"} */
74     {NULL, NULL}
75 };
76
77 static int get_binds_index(char first_char) {
78     if(tolower(first_char) >= 'a' && tolower(first_char) <= 'z') {
79         return tolower(first_char) - 'a';
80     }
81     return 26;
82 }
83
84 struct ClientSocket* get_botwise_prefered_bot(int botid, int clientid) {
85     struct ClientSocket *client, *lowbot = NULL;
86     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
87         if(client->botid == botid && (botid || clientid == client->clientid)) {
88             if((client->flags & SOCKET_FLAG_PREFERRED))
89                 return client;
90             else
91                 lowbot = client;
92         }
93     }
94     return lowbot;
95 }
96
97 static char* get_channel_trigger(int botid, int clientid, struct ChanNode *chan) {
98     struct trigger_cache *trigger;
99     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
100         if(trigger->botid == botid && (botid || trigger->clientid == clientid))
101             return trigger->trigger;
102     }
103     struct trigger_callback *cb;
104     for(cb = trigger_callbacks; cb; cb = cb->next) {
105         if(cb->botid == botid)
106             break;
107     }
108     char triggerStr[TRIGGERLEN];
109     if(cb)
110         cb->func(clientid, chan, triggerStr);
111     else
112         triggerStr[0] = '\0';
113     trigger = malloc(sizeof(*trigger));
114     if (!trigger) {
115         perror("malloc() failed");
116         return 0;
117     }
118     trigger->botid = botid;
119     trigger->clientid = clientid;
120     trigger->trigger = (triggerStr[0] ? strdup(triggerStr) : NULL);
121     trigger->next = chan->trigger;
122     chan->trigger = trigger;
123     return trigger->trigger;
124 }
125
126 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);
127
128 static USERAUTH_CALLBACK(command_checked_auth) {
129     struct command_check_user_cache *cache = data;
130     tmp_text_client = cache->textclient;
131     handle_command_async(cache->client, user, cache->chan, cache->sent_chan, cache->cbind, cache->argv, cache->argc);
132     free(cache->message);
133     if(cache->args_buffer)
134         free(cache->args_buffer);
135     free(cache->argv);
136     free(cache);
137 }
138
139 static CMD_BIND(modcmd_linker) {
140     //fake command for subcommands
141     //just empty
142 }
143
144 static void handle_command(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, char *message) {
145     struct ChanNode *sent_chan = chan;
146     if(message[0] == '#') {
147         char *chanName = message;
148         message = strstr(message, " ");
149         if(!message) return;
150         *message = '\0';
151         message++;
152         struct ChanNode *chan2 = getChanByName(chanName);
153         if(chan2)
154             chan = chan2;
155     }
156     message = strdup(message);
157     int bind_index = get_binds_index(message[0]);
158     char *args = strstr(message, " ");
159     char *args_buffer = NULL; //we need this to save a possible pointer to a allocation we need to free
160     if(args) {
161         *args = '\0';
162         args++;
163     }
164     struct cmd_binding *cbind;
165     int found_cmd = 0;
166     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
167         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, message) == 0) {
168             found_cmd = 1;
169             //get a text bot
170             tmp_text_client = get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0));
171             if(cbind->func->func == modcmd_linker) {
172                 //links subcommands
173                 char command[MAXLEN];
174                 struct cmd_binding *parent_bind = cbind;
175                 if(args) {
176                     char *subcmd = args;
177                     args = strstr(args, " ");
178                     if(args) {
179                         *args = '\0';
180                         args++;
181                     }
182                     sprintf(command, "%s %s", parent_bind->cmd, subcmd);
183                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
184                         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
185                             break;
186                     }
187                     if(!cbind)
188                         break;
189                 } else {
190                     //list all sub commands
191                     int commandlen = sprintf(command, "%s ", parent_bind->cmd);
192                     char subcommands[MAXLEN];
193                     int subcompos = 0;
194                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
195                         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmplen(cbind->cmd, command, commandlen) == 0) {
196                             subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
197                         }
198                     }
199                     reply(tmp_text_client, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, (subcompos ? subcommands : "\1dnone\1d"));
200                     break;
201                 }
202             }
203             if(statistics_enabled)
204                 statistics_commands++;
205             total_triggered++;
206             cbind->triggered++;
207             if((cbind->func->flags & CMDFLAG_FUNCMD)) {
208                 if(!sent_chan)
209                     break;
210                 chan = sent_chan;
211             }
212             //parse the arguments...
213             char *arga[MAXNUMPARAMS];
214             char **argv;
215             int argc = 0;
216             int escape = 0;
217             int offset = 0;
218             if(args) {
219                 while(*args) {
220                     //skip leading spaces
221                     while (*args == ' ')
222                         *args++ = 0;
223                     arga[argc++] = args;
224                     if (argc >= MAXNUMPARAMS)
225                         break;
226                     while ((escape || *args != ' ') && *args) {
227                         if((cbind->func->flags & CMDFLAG_ESCAPE_ARGS) && *args == '\\') {
228                             escape = 1;
229                             offset++;
230                         } else if(escape)
231                             escape = 0;
232                         if(!escape && offset) {
233                             args[0 - offset] = args[0];
234                         }
235                         args++;
236                         
237                     }
238                     if(offset) {
239                         args[0-offset] = '\0';
240                         offset = 0;
241                     }
242                 }
243             }
244             argv = arga;
245             if(argc != 0 && argv[0][0] == '#' && !(cbind->func->flags & CMDFLAG_CHAN_PARAM)) {
246                 struct ChanNode *chan2 = getChanByName(argv[0]);
247                 if(chan2) {
248                     argv += 1;
249                     argc -= 1;
250                     chan = chan2;
251                 }
252             }
253             if(cbind->paramcount) {
254                 //userdefined parameters...
255                 args_buffer = malloc(MAXLEN * 2 * sizeof(*args_buffer));
256                 int args_pos = 0;
257                 char *uargs[MAXNUMPARAMS];
258                 int uargc = 0;
259                 char *b, *c;
260                 int i;
261                 int allargs, argi;
262                 for(i = 0; i < cbind->paramcount; i++) {
263                     b = cbind->parameters[i];
264                     if(b[0] == '%') {
265                         b++;
266                         c = b;
267                         while(*c && *c != ' ') {
268                             if(*c == '|') break;
269                             c++;
270                         }
271                         if(!*c || *c == ' ') c = NULL;
272                         else {
273                             *c = '\0';
274                             c++;
275                         }
276                         if(b[strlen(b)-1] == '-') {
277                             allargs = strlen(b)-1;
278                             b[allargs] = '\0';
279                             argi = atoi(b);
280                             b[allargs] = '-';
281                             allargs = 1;
282                         } else if(b[strlen(b)-1] == '+') {
283                             allargs = strlen(b)-1;
284                             b[allargs] = '\0';
285                             argi = atoi(b);
286                             b[allargs] = '+';
287                             allargs = 2;
288                         } else {
289                             allargs = 0;
290                             argi = atoi(b);
291                         }
292                         if(argi > 0) {
293                             if(argi <= argc) {
294                                 uargs[uargc++] = args_buffer + args_pos;
295                                 if(allargs == 0) {
296                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
297                                 } else if(allargs == 1) {
298                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
299                                     for(argi++; argi <= argc; argi++) {
300                                         uargs[uargc++] = args_buffer + args_pos;
301                                         args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
302                                     }
303                                 } else if(allargs == 2) {
304                                     for(;argi <= argc; argi++) {
305                                         args_pos += sprintf(args_buffer + args_pos, (allargs ? "%s" : " %s"), argv[argi-1]);
306                                         allargs = 0;
307                                     }
308                                     args_pos++;
309                                 }
310                             } else if((cbind->func->flags & CMDFLAG_EMPTY_ARGS)) {
311                                 uargs[uargc++] = args_buffer + args_pos;
312                                 args_buffer[args_pos++] = '\0';
313                             } else if(c) {
314                                 uargs[uargc++] = args_buffer + args_pos;
315                                 args_pos += sprintf(args_buffer + args_pos, "%s", c) + 1;
316                             }
317                         } else if(!strcmp(b, "c")) {
318                             uargs[uargc++] = args_buffer + args_pos;
319                             args_pos += sprintf(args_buffer + args_pos, "%s", (chan ? chan->name : "")) + 1;
320                         } else if(!strcmp(b, "n")) {
321                             uargs[uargc++] = args_buffer + args_pos;
322                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
323                         }
324                         if(c) c[-1] = '|'; //reset \0 to |
325                     } else {
326                         uargs[uargc++] = args_buffer + args_pos;
327                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
328                     }
329                 }
330                 argv = uargs;
331                 argc = uargc;
332             }
333             if(argc < cbind->func->paramcount) {
334                 reply(tmp_text_client, user, "MODCMD_LESS_PARAM_COUNT");
335                 break;
336             }
337             if((cbind->func->flags & CMDFLAG_REQUIRE_CHAN) && !chan) {
338                 reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
339                 break;
340             }
341             if(((cbind->func->flags & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
342                 //check auth...
343                 struct command_check_user_cache *data = malloc(sizeof(*data));
344                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
345                 if (!data || !temp_argv) {
346                     perror("malloc() failed");
347                     break;
348                 }
349                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
350                 data->argv = temp_argv;
351                 data->argc = argc;
352                 data->client = client;
353                 data->user = user;
354                 data->chan = chan;
355                 data->sent_chan = sent_chan;
356                 data->message = message;
357                 data->args_buffer = args_buffer;
358                 data->cbind = cbind;
359                 data->textclient = tmp_text_client;
360                 get_userauth(user, command_checked_auth, data);
361                 return;
362             } else
363                 handle_command_async(client, user, chan, sent_chan, cbind, argv, argc);
364             break;
365         }
366     }
367     if(!found_cmd && !sent_chan)
368         reply(get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0)), user, "MODCMD_UNKNOWN", message);
369     free(message);
370     if(args_buffer)
371         free(args_buffer);
372 }
373
374 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) {
375     MYSQL_RES *res;
376     MYSQL_ROW row;
377     int uaccess;
378     char requested_uaccess = 0;
379     int eventflags = (cbind->func->flags & (CMDFLAG_LOG | CMDFLAG_OPLOG));
380     if((cbind->func->flags & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
381         reply(tmp_text_client, user, "MODCMD_AUTH_REQUIRED");
382         return;
383     }
384     if(chan && sent_chan != chan && !isUserOnChan(user, chan)) {
385         char user_in_chan = 0;
386         if((user->flags & USERFLAG_ISAUTHED)) {
387             //maybe there's another user authed to user->auth on the channel...
388             struct ChanUser *cchanuser;
389             for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
390                 if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
391                     user_in_chan = 1;
392                     break;
393                 }
394             }
395         }
396         if(!user_in_chan) {
397             //check if we are allowed to execute commands in this channel
398             requested_uaccess = 1;
399             uaccess = getChannelAccess(user, chan);
400             if(!uaccess) {
401                 reply(tmp_text_client, user, "MODCMD_CROSSCHAN", chan->name);
402                 return;
403             }
404         }
405     }
406     if(sent_chan && sent_chan != chan) {
407         //check pubcmd of this channel
408         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
409         res = mysql_use();
410         if ((row = mysql_fetch_row(res)) != NULL) {
411             int saccess = getChannelAccess(user, sent_chan);
412             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
413                 reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
414                 return;
415             }
416         }
417     }
418     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
419     if(global_access > 0) {
420         int user_global_access = 0;
421         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
422         res = mysql_use();
423         if ((row = mysql_fetch_row(res)) != NULL) {
424             user_global_access = atoi(row[0]);
425         }
426         if(user_global_access < global_access) {
427             if(!user_global_access)
428                 reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
429             else
430                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
431             return;
432         }
433     }
434     if((cbind->func->flags & CMDFLAG_REGISTERED_CHAN)) {
435         MYSQL_ROW defaults = NULL;
436         char access_list[256];
437         int access_pos = 0;
438         int access_count = 0;
439         int minaccess = 0;
440         char *str_a, *str_b = cbind->func->channel_access, *str_c;
441         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
442             str_b = cbind->channel_access;
443         access_list[0] = '\0';
444         if(str_b) {
445             str_c = strdup(str_b);
446             str_b = str_c;
447             while((str_a = str_b)) {
448                 str_b = strstr(str_a, ",");
449                 if(str_b) {
450                     *str_b = '\0';
451                     str_b++;
452                 }
453                 if(*str_a == '#') {
454                     str_a++;
455                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
456                     access_count++;
457                 } else {
458                     if(atoi(str_a) > minaccess)
459                         minaccess = atoi(str_a);
460                 }
461             }
462             free(str_c);
463         }
464         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
465             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
466             res = mysql_use();
467             if ((row = mysql_fetch_row(res)) != NULL) {
468                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
469                 chan->channel_id = atoi(row[0]);
470                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
471                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
472                     if(uaccess < minaccess && isGodMode(user)) {
473                         eventflags |= CMDFLAG_OPLOG;
474                     } else if(uaccess < minaccess) {
475                         //ACCESS DENIED
476                         reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
477                         return;
478                     }
479                     if(!row[1] && !defaults) {
480                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
481                         defaults = mysql_fetch_row(mysql_use());
482                     }
483                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
484                         if(isGodMode(user)) {
485                             eventflags |= CMDFLAG_OPLOG;
486                         } else {
487                             //PUBCMD
488                             reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
489                             return;
490                         }
491                     }
492                     int i;
493                     for(i = 0; i < access_count; i++) {
494                         if(!row[2+i] && !defaults) {
495                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
496                             defaults = mysql_fetch_row(mysql_use());
497                         }
498                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
499                             if(isGodMode(user)) {
500                                 eventflags |= CMDFLAG_OPLOG;
501                             } else {
502                                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
503                                 return;
504                             }
505                         }
506                     }
507                 }
508             }
509             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
510         }
511         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
512             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
513             return;
514         }
515         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);
516         res = mysql_use();
517         if ((row = mysql_fetch_row(res)) == NULL) {
518             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
519             return;
520         } else if(!strcmp(row[1], "1")) {
521             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
522             return;
523         }
524     }
525     if((cbind->func->flags & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
526         reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
527         return;
528     }
529     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
530     cbind->func->func(client, user, chan, argv, argc, event);
531 }
532
533 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
534     fd_set fds, fds2;
535     char *trigger;
536     struct ClientSocket *client;
537     FD_ZERO(&fds);
538     FD_ZERO(&fds2);
539     got_chanmsg_loop1:
540     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
541         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))))  {
542             FD_SET(client->clientid, &fds);
543             FD_SET(client->botid, &fds2);
544             trigger = get_channel_trigger(client->botid, client->clientid, chan);
545             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
546                 handle_command(client, user, chan, message + strlen(trigger));
547                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
548             }
549         }
550     }
551     got_chanmsg_loop2:
552     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
553         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
554             FD_SET(client->clientid, &fds);
555             FD_SET(client->botid, &fds2);
556             trigger = get_channel_trigger(client->botid, client->clientid, chan);
557             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
558                 handle_command(client, user, chan, message + strlen(trigger));
559                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
560             }
561         }
562     }
563 }
564
565 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
566     struct ClientSocket *client;
567     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
568         if(client->user == target) {
569             handle_command(client, user, NULL, message);
570         }
571     }
572 }
573
574 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
575     struct cmd_function *cmdfunc;
576     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
577         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
578             return 0;
579     }
580     cmdfunc = malloc(sizeof(*cmdfunc));
581     if (!cmdfunc) {
582         perror("malloc() failed");
583         return 0;
584     }
585     cmdfunc->botid = botid;
586     cmdfunc->name = strdup(name);
587     cmdfunc->func = func;
588     cmdfunc->flags = flags;
589     cmdfunc->paramcount = paramcount;
590     cmdfunc->channel_access = channel_access;
591     cmdfunc->global_access = global_access;
592     cmdfunc->next = cmd_functions;
593     cmd_functions = cmdfunc;
594     return 1;
595 }
596
597 int set_trigger_callback(int botid, trigger_callback_t *func) {
598     static struct trigger_callback *cb = NULL;
599     for(cb = trigger_callbacks; cb; cb = cb->next) {
600         if(cb->botid == botid)
601             break;
602     }
603     if(!cb) {
604         cb = malloc(sizeof(*cb));
605         if (!cb) {
606             perror("malloc() failed");
607             return 0;
608         }
609         cb->botid = botid;
610         cb->next = trigger_callbacks;
611         trigger_callbacks = cb;
612     }
613     cb->func = func;
614     return 1;
615 }
616
617 int flush_trigger_cache(int botid, int clientid) {
618     struct ChanNode *chan;
619     struct trigger_cache *trigger, *last;
620     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
621         last = NULL;
622         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
623             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
624                 if(last)
625                     last->next = trigger->next;
626                 else
627                     chan->trigger = trigger->next;
628                 free(trigger->trigger);
629                 free(trigger);
630                 break;
631             } else
632                 last = trigger;
633         }
634     }
635     return 1;
636 }
637
638 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
639     struct trigger_cache *trigger;
640     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
641         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
642             free(trigger->trigger);
643             trigger->trigger = strdup(new_trigger);
644             return 1;
645         }
646     }
647     return 0;
648 }
649
650 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
651     int bind_index = get_binds_index(cmd[0]);
652     struct cmd_binding *cbind;
653     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
654         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
655             return 0;
656     }
657     cbind = malloc(sizeof(*cbind));
658     if (!cbind) {
659         perror("malloc() failed");
660         return 0;
661     }
662     cbind->botid = botid;
663     cbind->clientid = clientid;
664     cbind->cmd = strdup(cmd);
665     cbind->func = func;
666     cbind->paramcount = 0;
667     cbind->global_access = 0;
668     cbind->channel_access = NULL;
669     cbind->flags = 0;
670     cbind->triggered = 0;
671     cbind->next = cmd_binds[bind_index];
672     cmd_binds[bind_index] = cbind;
673     return 1;
674 }
675
676 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
677     struct cmd_function *cmdfunc;
678     int fbotid = botid;
679     char *c;
680     if((c = strstr(func, "."))) {
681         *c = '\0';
682         struct cmd_bot_alias *botalias;
683         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
684             if(!stricmp(botalias->alias, func)) {
685                 fbotid = botalias->botid;
686                 break;
687             }
688         }
689         *c = '.';
690         func = c+1;
691     }
692     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
693         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
694             break;
695     }
696     if(!cmdfunc) return 0;
697     int bind_index = get_binds_index(cmd[0]);
698     struct cmd_binding *cbind;
699     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
700         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
701             return 0;
702     }
703     cbind = malloc(sizeof(*cbind));
704     if (!cbind) {
705         perror("malloc() failed");
706         return 0;
707     }
708     cbind->botid = botid;
709     cbind->clientid = clientid;
710     cbind->cmd = strdup(cmd);
711     cbind->func = cmdfunc;
712     cbind->next = cmd_binds[bind_index];
713     cbind->paramcount = 0;
714     cbind->global_access = 0;
715     cbind->channel_access = NULL;
716     cbind->flags = 0;
717     cbind->triggered = 0;
718     cmd_binds[bind_index] = cbind;
719     return 1;
720 }
721
722 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
723     int bind_index = get_binds_index(cmd[0]);
724     struct cmd_binding *cbind, *last = NULL;
725     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
726         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
727             if(last)
728                 last->next = cbind->next;
729             else
730                 cmd_binds[bind_index] = cbind->next;
731             free(cbind->cmd);
732             if(cbind->paramcount) {
733                 int i;
734                 for(i = 0; i < cbind->paramcount; i++)
735                     free(cbind->parameters[i]);
736             }
737             if(cbind->channel_access)
738                 free(cbind->channel_access);
739             free(cbind);
740             return 1;
741         } else
742             last = cbind;
743     }
744     return 0;
745 }
746
747 int unbind_botwise_allcmd(int clientid) {
748     int i;
749     for(i = 0; i < 27; i++) {
750         struct cmd_binding *cbind, *next, *last = NULL;
751         for(cbind = cmd_binds[i]; cbind; cbind = next) {
752             next = cbind->next;
753             if(clientid == cbind->clientid) {
754                 if(last)
755                     last->next = cbind->next;
756                 else
757                     cmd_binds[i] = cbind->next;
758                 free(cbind->cmd);
759                 if(cbind->paramcount) {
760                     int j;
761                     for(j = 0; j < cbind->paramcount; j++)
762                         free(cbind->parameters[j]);
763                 }
764                 if(cbind->channel_access)
765                     free(cbind->channel_access);
766                 free(cbind);
767             } else
768                 last = cbind;
769         }
770     }
771     return 1;
772 }
773
774 struct cmd_function *find_cmd_function(int botid, char *name) {
775     struct cmd_function *cmdfunc;
776     char *c;
777     if((c = strstr(name, "."))) {
778         *c = '\0';
779         struct cmd_bot_alias *botalias;
780         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
781             if(!stricmp(botalias->alias, name)) {
782                 botid = botalias->botid;
783                 break;
784             }
785         }
786         *c = '.';
787         name = c+1;
788     }
789     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
790         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
791             break;
792     }
793     return cmdfunc;
794 }
795
796 struct ClientSocket *getTextBot() {
797     return tmp_text_client;
798 }
799
800 void init_modcmd() {
801     cmd_binds = calloc(27, sizeof(*cmd_binds));
802     bind_chanmsg(got_chanmsg);
803     bind_privmsg(got_privmsg);
804     register_default_language_table(msgtab);
805     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
806 }
807
808 void free_modcmd() {
809     int i;
810     for(i = 0; i < 27; i++) {
811         struct cmd_binding *cbind, *next;
812         for(cbind = cmd_binds[i]; cbind; cbind = next) {
813             next = cbind->next;
814             free(cbind->cmd);
815             if(cbind->paramcount) {
816                 int j;
817                 for(j = 0; j < cbind->paramcount; j++)
818                     free(cbind->parameters[j]);
819             }
820             if(cbind->channel_access)
821                 free(cbind->channel_access);
822             free(cbind);
823         }
824     }
825     free(cmd_binds);
826     struct cmd_function *cmdfunct, *next;
827     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
828         next = cmdfunct->next;
829         free(cmdfunct->name);
830         free(cmdfunct);
831     }
832     struct trigger_callback *cb, *next_cb;
833     for(cb = trigger_callbacks; cb; cb = next_cb) {
834         next_cb = cb->next;
835         free(next_cb);
836     }
837     struct cmd_bot_alias *botalias, *next_botalias;
838     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
839         next_botalias = botalias->next;
840         free(botalias->alias);
841         free(botalias);
842     }
843     cmd_functions = NULL;
844     trigger_callbacks = NULL;
845     bot_aliases = NULL;
846 }
847
848 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
849     int bind_index = get_binds_index(cmd[0]);
850     struct cmd_binding *cbind;
851     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
852         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
853             if(cbind->paramcount) {
854                 int i;
855                 for(i = 0; i < cbind->paramcount; i++)
856                     free(cbind->parameters[i]);
857                 cbind->paramcount = 0;
858             }
859             char *a, *b = parameters;
860             do {
861                 a = strstr(b, " ");
862                 if(a) *a = '\0';
863                 cbind->parameters[cbind->paramcount++] = strdup(b);
864                 if(a) b = a+1;
865             } while(a);
866             return;
867         }
868     }
869 }
870
871 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
872     int bind_index = get_binds_index(cmd[0]);
873     struct cmd_binding *cbind;
874     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
875         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
876             if(gaccess > -1) {
877                 cbind->global_access = gaccess;
878                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
879             } else {
880                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
881             }
882             return;
883         }
884     }
885 }
886
887 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
888     int bind_index = get_binds_index(cmd[0]);
889     struct cmd_binding *cbind;
890     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
891         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
892             if(cbind->channel_access)
893                 free(cbind->channel_access);
894             if(chanaccess) {
895                 cbind->channel_access = strdup(chanaccess);
896                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
897             } else {
898                 cbind->channel_access = NULL;
899                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
900             }
901             return;
902         }
903     }
904 }
905
906 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
907     int bind_index = get_binds_index(cmd[0]);
908     struct cmd_binding *cbind;
909     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
910         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
911             return cbind;
912         }
913     }
914     return NULL;
915 }
916
917 void bind_botwise_unbound_required_functions(int botid, int clientid) {
918     struct cmd_function *cmdfunc;
919     int i, found;
920     struct cmd_binding *cbind;
921     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
922         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
923             found = 0;
924             for(i = 0; i < 27; i++) {
925                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
926                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
927                         found = 1;
928                         break;
929                     }
930                 }
931                 if(found)
932                     break;
933             }
934             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
935                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
936                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
937             }
938         }
939     }
940 }
941
942 void register_command_alias(int botid, char *alias) {
943     struct cmd_bot_alias *botalias;
944     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
945         if(!stricmp(botalias->alias, alias))
946             return;
947     }
948     botalias = malloc(sizeof(*botalias));
949     if (!botalias) {
950         perror("malloc() failed");
951         return;
952     }
953     botalias->botid = botid;
954     botalias->alias = strdup(alias);
955     botalias->next = bot_aliases;
956     bot_aliases = botalias;
957 }
958
959 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
960     int bind_index;
961     if(last) {
962         if(last->next)
963             return last->next;
964         bind_index = get_binds_index(last->cmd[0]) + 1;
965         if(bind_index > 26)
966             return NULL;
967     } else
968         bind_index = 0;
969     do {
970         if(cmd_binds[bind_index])
971             return cmd_binds[bind_index];
972         bind_index++;
973     } while(bind_index < 27);
974     return NULL;
975 }