Another year is about to end... So we have to update these damn copyright information :P
[NeonServV5.git] / src / modcmd.c
1 /* modcmd.c - NeonServ v5.3
2  * Copyright (C) 2011-2012  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."}, /* {ARGS: "#TestChan"} */
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((BIND_FLAGS(cbind) & 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((BIND_FLAGS(cbind) & 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] == '#' && !(BIND_FLAGS(cbind) & 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((BIND_FLAGS(cbind) & 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((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_CHAN) && !chan) {
338                 reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
339                 break;
340             }
341             if(((BIND_FLAGS(cbind) & 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 = (BIND_FLAGS(cbind) & (CMDFLAG_LOG | CMDFLAG_OPLOG));
380     if((BIND_FLAGS(cbind) & 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                 if(isGodMode(user)) {
402                     eventflags |= CMDFLAG_OPLOG;
403                 } else {
404                     reply(tmp_text_client, user, "MODCMD_CROSSCHAN", chan->name);
405                     return;
406                 }
407             }
408         }
409     }
410     if(sent_chan && sent_chan != chan) {
411         //check pubcmd of this channel
412         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
413         res = mysql_use();
414         if ((row = mysql_fetch_row(res)) != NULL) {
415             int saccess = getChannelAccess(user, sent_chan);
416             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
417                 reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
418                 return;
419             }
420         }
421     }
422     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
423     if(global_access > 0) {
424         int user_global_access = 0;
425         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
426         res = mysql_use();
427         if ((row = mysql_fetch_row(res)) != NULL) {
428             user_global_access = atoi(row[0]);
429         }
430         if(user_global_access < global_access) {
431             if(!user_global_access)
432                 reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
433             else
434                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
435             return;
436         }
437     }
438     if((BIND_FLAGS(cbind) & CMDFLAG_REGISTERED_CHAN)) {
439         MYSQL_ROW defaults = NULL;
440         char access_list[256];
441         int access_pos = 0;
442         int access_count = 0;
443         int minaccess = 0;
444         char *str_a, *str_b = cbind->func->channel_access, *str_c;
445         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
446             str_b = cbind->channel_access;
447         access_list[0] = '\0';
448         if(str_b) {
449             str_c = strdup(str_b);
450             str_b = str_c;
451             while((str_a = str_b)) {
452                 str_b = strstr(str_a, ",");
453                 if(str_b) {
454                     *str_b = '\0';
455                     str_b++;
456                 }
457                 if(*str_a == '#') {
458                     str_a++;
459                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
460                     access_count++;
461                 } else {
462                     if(atoi(str_a) > minaccess)
463                         minaccess = atoi(str_a);
464                 }
465             }
466             free(str_c);
467         }
468         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
469             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
470             res = mysql_use();
471             if ((row = mysql_fetch_row(res)) != NULL) {
472                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
473                 chan->channel_id = atoi(row[0]);
474                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
475                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
476                     if(uaccess < minaccess && isGodMode(user)) {
477                         eventflags |= CMDFLAG_OPLOG;
478                     } else if(uaccess < minaccess) {
479                         //ACCESS DENIED
480                         reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
481                         return;
482                     }
483                     if(!row[1] && !defaults) {
484                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
485                         defaults = mysql_fetch_row(mysql_use());
486                     }
487                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
488                         if(isGodMode(user)) {
489                             eventflags |= CMDFLAG_OPLOG;
490                         } else {
491                             //PUBCMD
492                             reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
493                             return;
494                         }
495                     }
496                     int i;
497                     for(i = 0; i < access_count; i++) {
498                         if(!row[2+i] && !defaults) {
499                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
500                             defaults = mysql_fetch_row(mysql_use());
501                         }
502                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
503                             if(isGodMode(user)) {
504                                 eventflags |= CMDFLAG_OPLOG;
505                             } else {
506                                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
507                                 return;
508                             }
509                         }
510                     }
511                 }
512             }
513             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
514         }
515         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
516             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
517             return;
518         }
519         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);
520         res = mysql_use();
521         if ((row = mysql_fetch_row(res)) == NULL) {
522             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
523             return;
524         } else if(!strcmp(row[1], "1")) {
525             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
526             return;
527         }
528     }
529     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
530         reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
531         return;
532     }
533     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
534     cbind->func->func(client, user, chan, argv, argc, event);
535 }
536
537 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
538     fd_set fds, fds2;
539     char *trigger;
540     struct ClientSocket *client;
541     FD_ZERO(&fds);
542     FD_ZERO(&fds2);
543     got_chanmsg_loop1:
544     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
545         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))))  {
546             FD_SET(client->clientid, &fds);
547             FD_SET(client->botid, &fds2);
548             trigger = get_channel_trigger(client->botid, client->clientid, chan);
549             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
550                 handle_command(client, user, chan, message + strlen(trigger));
551                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
552             }
553         }
554     }
555     got_chanmsg_loop2:
556     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
557         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
558             FD_SET(client->clientid, &fds);
559             FD_SET(client->botid, &fds2);
560             trigger = get_channel_trigger(client->botid, client->clientid, chan);
561             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
562                 handle_command(client, user, chan, message + strlen(trigger));
563                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
564             }
565         }
566     }
567 }
568
569 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
570     struct ClientSocket *client;
571     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
572         if(client->user == target) {
573             handle_command(client, user, NULL, message);
574         }
575     }
576 }
577
578 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
579     struct cmd_function *cmdfunc;
580     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
581         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
582             return 0;
583     }
584     cmdfunc = malloc(sizeof(*cmdfunc));
585     if (!cmdfunc) {
586         perror("malloc() failed");
587         return 0;
588     }
589     cmdfunc->botid = botid;
590     cmdfunc->name = strdup(name);
591     cmdfunc->func = func;
592     cmdfunc->flags = flags;
593     cmdfunc->paramcount = paramcount;
594     cmdfunc->channel_access = channel_access;
595     cmdfunc->global_access = global_access;
596     cmdfunc->next = cmd_functions;
597     cmd_functions = cmdfunc;
598     return 1;
599 }
600
601 int set_trigger_callback(int botid, trigger_callback_t *func) {
602     static struct trigger_callback *cb = NULL;
603     for(cb = trigger_callbacks; cb; cb = cb->next) {
604         if(cb->botid == botid)
605             break;
606     }
607     if(!cb) {
608         cb = malloc(sizeof(*cb));
609         if (!cb) {
610             perror("malloc() failed");
611             return 0;
612         }
613         cb->botid = botid;
614         cb->next = trigger_callbacks;
615         trigger_callbacks = cb;
616     }
617     cb->func = func;
618     return 1;
619 }
620
621 int flush_trigger_cache(int botid, int clientid) {
622     struct ChanNode *chan;
623     struct trigger_cache *trigger, *last;
624     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
625         last = NULL;
626         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
627             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
628                 if(last)
629                     last->next = trigger->next;
630                 else
631                     chan->trigger = trigger->next;
632                 free(trigger->trigger);
633                 free(trigger);
634                 break;
635             } else
636                 last = trigger;
637         }
638     }
639     return 1;
640 }
641
642 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
643     struct trigger_cache *trigger;
644     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
645         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
646             free(trigger->trigger);
647             trigger->trigger = strdup(new_trigger);
648             return 1;
649         }
650     }
651     return 0;
652 }
653
654 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
655     int bind_index = get_binds_index(cmd[0]);
656     struct cmd_binding *cbind;
657     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
658         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
659             return 0;
660     }
661     cbind = malloc(sizeof(*cbind));
662     if (!cbind) {
663         perror("malloc() failed");
664         return 0;
665     }
666     cbind->botid = botid;
667     cbind->clientid = clientid;
668     cbind->cmd = strdup(cmd);
669     cbind->func = func;
670     cbind->paramcount = 0;
671     cbind->global_access = 0;
672     cbind->channel_access = NULL;
673     cbind->flags = 0;
674     cbind->triggered = 0;
675     cbind->next = cmd_binds[bind_index];
676     cmd_binds[bind_index] = cbind;
677     return 1;
678 }
679
680 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
681     struct cmd_function *cmdfunc;
682     int fbotid = botid;
683     char *c;
684     if((c = strstr(func, "."))) {
685         *c = '\0';
686         struct cmd_bot_alias *botalias;
687         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
688             if(!stricmp(botalias->alias, func)) {
689                 fbotid = botalias->botid;
690                 break;
691             }
692         }
693         *c = '.';
694         func = c+1;
695     }
696     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
697         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
698             break;
699     }
700     if(!cmdfunc) return 0;
701     int bind_index = get_binds_index(cmd[0]);
702     struct cmd_binding *cbind;
703     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
704         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
705             return 0;
706     }
707     cbind = malloc(sizeof(*cbind));
708     if (!cbind) {
709         perror("malloc() failed");
710         return 0;
711     }
712     cbind->botid = botid;
713     cbind->clientid = clientid;
714     cbind->cmd = strdup(cmd);
715     cbind->func = cmdfunc;
716     cbind->next = cmd_binds[bind_index];
717     cbind->paramcount = 0;
718     cbind->global_access = 0;
719     cbind->channel_access = NULL;
720     cbind->flags = 0;
721     cbind->triggered = 0;
722     cmd_binds[bind_index] = cbind;
723     return 1;
724 }
725
726 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
727     int bind_index = get_binds_index(cmd[0]);
728     struct cmd_binding *cbind, *last = NULL;
729     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
730         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
731             if(last)
732                 last->next = cbind->next;
733             else
734                 cmd_binds[bind_index] = cbind->next;
735             free(cbind->cmd);
736             if(cbind->paramcount) {
737                 int i;
738                 for(i = 0; i < cbind->paramcount; i++)
739                     free(cbind->parameters[i]);
740             }
741             if(cbind->channel_access)
742                 free(cbind->channel_access);
743             free(cbind);
744             return 1;
745         } else
746             last = cbind;
747     }
748     return 0;
749 }
750
751 int unbind_botwise_allcmd(int clientid) {
752     int i;
753     for(i = 0; i < 27; i++) {
754         struct cmd_binding *cbind, *next, *last = NULL;
755         for(cbind = cmd_binds[i]; cbind; cbind = next) {
756             next = cbind->next;
757             if(clientid == cbind->clientid) {
758                 if(last)
759                     last->next = cbind->next;
760                 else
761                     cmd_binds[i] = cbind->next;
762                 free(cbind->cmd);
763                 if(cbind->paramcount) {
764                     int j;
765                     for(j = 0; j < cbind->paramcount; j++)
766                         free(cbind->parameters[j]);
767                 }
768                 if(cbind->channel_access)
769                     free(cbind->channel_access);
770                 free(cbind);
771             } else
772                 last = cbind;
773         }
774     }
775     return 1;
776 }
777
778 struct cmd_function *find_cmd_function(int botid, char *name) {
779     struct cmd_function *cmdfunc;
780     char *c;
781     if((c = strstr(name, "."))) {
782         *c = '\0';
783         struct cmd_bot_alias *botalias;
784         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
785             if(!stricmp(botalias->alias, name)) {
786                 botid = botalias->botid;
787                 break;
788             }
789         }
790         *c = '.';
791         name = c+1;
792     }
793     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
794         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
795             break;
796     }
797     return cmdfunc;
798 }
799
800 struct ClientSocket *getTextBot() {
801     return tmp_text_client;
802 }
803
804 void init_modcmd() {
805     cmd_binds = calloc(27, sizeof(*cmd_binds));
806     bind_chanmsg(got_chanmsg);
807     bind_privmsg(got_privmsg);
808     register_default_language_table(msgtab);
809     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
810 }
811
812 void free_modcmd() {
813     int i;
814     for(i = 0; i < 27; i++) {
815         struct cmd_binding *cbind, *next;
816         for(cbind = cmd_binds[i]; cbind; cbind = next) {
817             next = cbind->next;
818             free(cbind->cmd);
819             if(cbind->paramcount) {
820                 int j;
821                 for(j = 0; j < cbind->paramcount; j++)
822                     free(cbind->parameters[j]);
823             }
824             if(cbind->channel_access)
825                 free(cbind->channel_access);
826             free(cbind);
827         }
828     }
829     free(cmd_binds);
830     struct cmd_function *cmdfunct, *next;
831     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
832         next = cmdfunct->next;
833         free(cmdfunct->name);
834         free(cmdfunct);
835     }
836     struct trigger_callback *cb, *next_cb;
837     for(cb = trigger_callbacks; cb; cb = next_cb) {
838         next_cb = cb->next;
839         free(next_cb);
840     }
841     struct cmd_bot_alias *botalias, *next_botalias;
842     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
843         next_botalias = botalias->next;
844         free(botalias->alias);
845         free(botalias);
846     }
847     cmd_functions = NULL;
848     trigger_callbacks = NULL;
849     bot_aliases = NULL;
850 }
851
852 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
853     int bind_index = get_binds_index(cmd[0]);
854     struct cmd_binding *cbind;
855     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
856         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
857             if(cbind->paramcount) {
858                 int i;
859                 for(i = 0; i < cbind->paramcount; i++)
860                     free(cbind->parameters[i]);
861                 cbind->paramcount = 0;
862             }
863             if(parameters) {
864                 char *a, *b = parameters;
865                 do {
866                     a = strstr(b, " ");
867                     if(a) *a = '\0';
868                     cbind->parameters[cbind->paramcount++] = strdup(b);
869                     if(a) b = a+1;
870                 } while(a);
871             }
872             return;
873         }
874     }
875 }
876
877 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
878     int bind_index = get_binds_index(cmd[0]);
879     struct cmd_binding *cbind;
880     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
881         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
882             if(gaccess > -1) {
883                 cbind->global_access = gaccess;
884                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
885             } else {
886                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
887             }
888             return;
889         }
890     }
891 }
892
893 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
894     int bind_index = get_binds_index(cmd[0]);
895     struct cmd_binding *cbind;
896     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
897         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
898             if(cbind->channel_access)
899                 free(cbind->channel_access);
900             if(chanaccess) {
901                 cbind->channel_access = strdup(chanaccess);
902                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
903             } else {
904                 cbind->channel_access = NULL;
905                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
906             }
907             return;
908         }
909     }
910 }
911
912 void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
913     int bind_index = get_binds_index(cmd[0]);
914     struct cmd_binding *cbind;
915     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
916         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
917             cbind->flags |= flags;
918             return;
919         }
920     }
921 }
922
923 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
924     int bind_index = get_binds_index(cmd[0]);
925     struct cmd_binding *cbind;
926     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
927         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
928             return cbind;
929         }
930     }
931     return NULL;
932 }
933
934 void bind_botwise_unbound_required_functions(int botid, int clientid) {
935     struct cmd_function *cmdfunc;
936     int i, found;
937     struct cmd_binding *cbind;
938     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
939         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
940             found = 0;
941             for(i = 0; i < 27; i++) {
942                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
943                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
944                         found = 1;
945                         break;
946                     }
947                 }
948                 if(found)
949                     break;
950             }
951             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
952                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
953                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
954             }
955         }
956     }
957 }
958
959 void register_command_alias(int botid, char *alias) {
960     struct cmd_bot_alias *botalias;
961     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
962         if(!stricmp(botalias->alias, alias))
963             return;
964     }
965     botalias = malloc(sizeof(*botalias));
966     if (!botalias) {
967         perror("malloc() failed");
968         return;
969     }
970     botalias->botid = botid;
971     botalias->alias = strdup(alias);
972     botalias->next = bot_aliases;
973     bot_aliases = botalias;
974 }
975
976 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
977     int bind_index;
978     if(last) {
979         if(last->next)
980             return last->next;
981         bind_index = get_binds_index(last->cmd[0]) + 1;
982         if(bind_index > 26)
983             return NULL;
984     } else
985         bind_index = 0;
986     do {
987         if(cmd_binds[bind_index])
988             return cmd_binds[bind_index];
989         bind_index++;
990     } while(bind_index < 27);
991     return NULL;
992 }