don't show sub-sub-commands in linker overview
[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 struct cmd_binding *modcmd_linker_command(struct ClientSocket *client, struct UserNode *user, struct cmd_binding *cbind, int bind_index, char **args_ptr) {
145     //links subcommands
146     char command[MAXLEN];
147     struct cmd_binding *parent_bind = cbind;
148     char *args = *args_ptr;
149     if(args) {
150         char *subcmd = args;
151         args = strstr(args, " ");
152         if(args) {
153             *args = '\0';
154             args++;
155         }
156         sprintf(command, "%s %s", parent_bind->cmd, subcmd);
157         for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
158             if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
159                 break;
160         }
161         *args_ptr = args;
162         if(cbind->func->func == modcmd_linker) {
163             return modcmd_linker_command(client, user, cbind, bind_index, args_ptr);
164         }
165         return cbind;
166     } else {
167         //list all sub commands
168         int commandlen = sprintf(command, "%s ", parent_bind->cmd);
169         char subcommands[MAXLEN];
170         int subcompos = 0;
171         for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
172             if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmplen(cbind->cmd, command, commandlen) == 0) {
173                 if(strstr(cbind->cmd + commandlen, " ")) continue; //ignore if there is another space in the command (sub-sub-command :D)
174                 subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
175             }
176         }
177         reply(tmp_text_client, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, (subcompos ? subcommands : "\1dnone\1d"));
178         return NULL;
179     }
180 }
181
182 static void handle_command(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, char *message) {
183     struct ChanNode *sent_chan = chan;
184     if(message[0] == '#') {
185         char *chanName = message;
186         message = strstr(message, " ");
187         if(!message) return;
188         *message = '\0';
189         message++;
190         struct ChanNode *chan2 = getChanByName(chanName);
191         if(chan2)
192             chan = chan2;
193     }
194     message = strdup(message);
195     int bind_index = get_binds_index(message[0]);
196     char *args = strstr(message, " ");
197     char *args_buffer = NULL; //we need this to save a possible pointer to a allocation we need to free
198     if(args) {
199         *args = '\0';
200         args++;
201     }
202     struct cmd_binding *cbind;
203     int found_cmd = 0;
204     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
205         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, message) == 0) {
206             found_cmd = 1;
207             //get a text bot
208             tmp_text_client = get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0));
209             if(cbind->func->func == modcmd_linker) {
210                 cbind = modcmd_linker_command(client, user, cbind, bind_index, &args);
211                 if(cbind == NULL) break;
212             }
213             if(statistics_enabled)
214                 statistics_commands++;
215             total_triggered++;
216             cbind->triggered++;
217             if((BIND_FLAGS(cbind) & CMDFLAG_FUNCMD)) {
218                 if(!sent_chan)
219                     break;
220                 chan = sent_chan;
221             }
222             //parse the arguments...
223             char *arga[MAXNUMPARAMS];
224             char **argv;
225             int argc = 0;
226             int escape = 0;
227             int offset = 0;
228             if(args) {
229                 while(*args) {
230                     //skip leading spaces
231                     while (*args == ' ')
232                         *args++ = 0;
233                     arga[argc++] = args;
234                     if (argc >= MAXNUMPARAMS)
235                         break;
236                     while ((escape || *args != ' ') && *args) {
237                         if((BIND_FLAGS(cbind) & CMDFLAG_ESCAPE_ARGS) && *args == '\\') {
238                             escape = 1;
239                             offset++;
240                         } else if(escape)
241                             escape = 0;
242                         if(!escape && offset) {
243                             args[0 - offset] = args[0];
244                         }
245                         args++;
246                         
247                     }
248                     if(offset) {
249                         args[0-offset] = '\0';
250                         offset = 0;
251                     }
252                 }
253             }
254             argv = arga;
255             if(cbind->paramcount) {
256                 //userdefined parameters...
257                 args_buffer = malloc(MAXLEN * 2 * sizeof(*args_buffer));
258                 int args_pos = 0;
259                 char *uargs[MAXNUMPARAMS];
260                 int uargc = 0;
261                 char *b, *c;
262                 int i;
263                 int allargs, argi;
264                 for(i = 0; i < cbind->paramcount; i++) {
265                     b = cbind->parameters[i];
266                     if(b[0] == '%') {
267                         b++;
268                         c = b;
269                         while(*c && *c != ' ') {
270                             if(*c == '|') break;
271                             c++;
272                         }
273                         if(!*c || *c == ' ') c = NULL;
274                         else {
275                             *c = '\0';
276                             c++;
277                         }
278                         if(b[strlen(b)-1] == '-') {
279                             allargs = strlen(b)-1;
280                             b[allargs] = '\0';
281                             argi = atoi(b);
282                             b[allargs] = '-';
283                             allargs = 1;
284                         } else if(b[strlen(b)-1] == '+') {
285                             allargs = strlen(b)-1;
286                             b[allargs] = '\0';
287                             argi = atoi(b);
288                             b[allargs] = '+';
289                             allargs = 2;
290                         } else {
291                             allargs = 0;
292                             argi = atoi(b);
293                         }
294                         if(argi > 0) {
295                             if(argi <= argc) {
296                                 uargs[uargc++] = args_buffer + args_pos;
297                                 if(allargs == 0) {
298                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
299                                 } else if(allargs == 1) {
300                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
301                                     for(argi++; argi <= argc; argi++) {
302                                         uargs[uargc++] = args_buffer + args_pos;
303                                         args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
304                                     }
305                                 } else if(allargs == 2) {
306                                     for(;argi <= argc; argi++) {
307                                         args_pos += sprintf(args_buffer + args_pos, (allargs ? "%s" : " %s"), argv[argi-1]);
308                                         allargs = 0;
309                                     }
310                                     args_pos++;
311                                 }
312                             } else if((BIND_FLAGS(cbind) & CMDFLAG_EMPTY_ARGS)) {
313                                 uargs[uargc++] = args_buffer + args_pos;
314                                 args_buffer[args_pos++] = '\0';
315                             } else if(c) {
316                                 uargs[uargc++] = args_buffer + args_pos;
317                                 args_pos += sprintf(args_buffer + args_pos, "%s", c) + 1;
318                             }
319                         } else if(!strcmp(b, "c")) {
320                             uargs[uargc++] = args_buffer + args_pos;
321                             args_pos += sprintf(args_buffer + args_pos, "%s", (chan ? chan->name : "")) + 1;
322                         } else if(!strcmp(b, "n")) {
323                             uargs[uargc++] = args_buffer + args_pos;
324                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
325                         }
326                         if(c) c[-1] = '|'; //reset \0 to |
327                     } else {
328                         uargs[uargc++] = args_buffer + args_pos;
329                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
330                     }
331                 }
332                 argv = uargs;
333                 argc = uargc;
334             }
335             if(argc != 0 && argv[0][0] == '#' && !(BIND_FLAGS(cbind) & CMDFLAG_CHAN_PARAM)) {
336                 struct ChanNode *chan2 = getChanByName(argv[0]);
337                 if(chan2) {
338                     argv += 1;
339                     argc -= 1;
340                     chan = chan2;
341                 }
342             }
343             if(argc < cbind->func->paramcount) {
344                 reply(tmp_text_client, user, "MODCMD_LESS_PARAM_COUNT");
345                 break;
346             }
347             if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_CHAN) && !chan) {
348                 reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
349                 break;
350             }
351             if(((BIND_FLAGS(cbind) & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
352                 //check auth...
353                 struct command_check_user_cache *data = malloc(sizeof(*data));
354                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
355                 if (!data || !temp_argv) {
356                     perror("malloc() failed");
357                     break;
358                 }
359                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
360                 data->argv = temp_argv;
361                 data->argc = argc;
362                 data->client = client;
363                 data->user = user;
364                 data->chan = chan;
365                 data->sent_chan = sent_chan;
366                 data->message = message;
367                 data->args_buffer = args_buffer;
368                 data->cbind = cbind;
369                 data->textclient = tmp_text_client;
370                 get_userauth(user, command_checked_auth, data);
371                 return;
372             } else
373                 handle_command_async(client, user, chan, sent_chan, cbind, argv, argc);
374             break;
375         }
376     }
377     if(!found_cmd && !sent_chan && !(client->flags & SOCKET_FLAG_SILENT))
378         reply(get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0)), user, "MODCMD_UNKNOWN", message);
379     free(message);
380     if(args_buffer)
381         free(args_buffer);
382 }
383
384 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) {
385     MYSQL_RES *res;
386     MYSQL_ROW row;
387     int uaccess;
388     char requested_uaccess = 0;
389     int eventflags = (BIND_FLAGS(cbind) & (CMDFLAG_LOG | CMDFLAG_OPLOG));
390     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
391         reply(tmp_text_client, user, "MODCMD_AUTH_REQUIRED");
392         return;
393     }
394     if(chan && sent_chan != chan && !isUserOnChan(user, chan)) {
395         char user_in_chan = 0;
396         if((user->flags & USERFLAG_ISAUTHED)) {
397             //maybe there's another user authed to user->auth on the channel...
398             struct ChanUser *cchanuser;
399             for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
400                 if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
401                     user_in_chan = 1;
402                     break;
403                 }
404             }
405         }
406         if(!user_in_chan) {
407             //check if we are allowed to execute commands in this channel
408             requested_uaccess = 1;
409             uaccess = getChannelAccess(user, chan);
410             if(!uaccess) {
411                 if(isGodMode(user)) {
412                     eventflags |= CMDFLAG_OPLOG;
413                 } else {
414                     reply(tmp_text_client, user, "MODCMD_CROSSCHAN", chan->name);
415                     return;
416                 }
417             }
418         }
419     }
420     if(sent_chan && sent_chan != chan) {
421         //check pubcmd of this channel
422         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
423         res = mysql_use();
424         if ((row = mysql_fetch_row(res)) != NULL) {
425             int saccess = getChannelAccess(user, sent_chan);
426             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
427                 reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
428                 return;
429             }
430         }
431     }
432     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
433     if(global_access > 0) {
434         int user_global_access = 0;
435         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
436         res = mysql_use();
437         if ((row = mysql_fetch_row(res)) != NULL) {
438             user_global_access = atoi(row[0]);
439         }
440         if(user_global_access < global_access) {
441             if(!user_global_access)
442                 reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
443             else
444                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
445             return;
446         }
447     }
448     if((BIND_FLAGS(cbind) & CMDFLAG_REGISTERED_CHAN)) {
449         MYSQL_ROW defaults = NULL;
450         char access_list[256];
451         int access_pos = 0;
452         int access_count = 0;
453         int minaccess = 0;
454         char *str_a, *str_b = cbind->func->channel_access, *str_c;
455         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
456             str_b = cbind->channel_access;
457         access_list[0] = '\0';
458         if(str_b) {
459             str_c = strdup(str_b);
460             str_b = str_c;
461             while((str_a = str_b)) {
462                 str_b = strstr(str_a, ",");
463                 if(str_b) {
464                     *str_b = '\0';
465                     str_b++;
466                 }
467                 if(*str_a == '#') {
468                     str_a++;
469                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
470                     access_count++;
471                 } else {
472                     if(atoi(str_a) > minaccess)
473                         minaccess = atoi(str_a);
474                 }
475             }
476             free(str_c);
477         }
478         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
479             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
480             res = mysql_use();
481             if ((row = mysql_fetch_row(res)) != NULL) {
482                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
483                 chan->channel_id = atoi(row[0]);
484                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
485                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
486                     if(uaccess < minaccess && isGodMode(user)) {
487                         eventflags |= CMDFLAG_OPLOG;
488                     } else if(uaccess < minaccess) {
489                         //ACCESS DENIED
490                         reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
491                         return;
492                     }
493                     if(!row[1] && !defaults) {
494                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
495                         defaults = mysql_fetch_row(mysql_use());
496                     }
497                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
498                         if(isGodMode(user)) {
499                             eventflags |= CMDFLAG_OPLOG;
500                         } else {
501                             //PUBCMD
502                             reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
503                             return;
504                         }
505                     }
506                     int i;
507                     for(i = 0; i < access_count; i++) {
508                         if(!row[2+i] && !defaults) {
509                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
510                             defaults = mysql_fetch_row(mysql_use());
511                         }
512                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
513                             if(isGodMode(user)) {
514                                 eventflags |= CMDFLAG_OPLOG;
515                             } else {
516                                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
517                                 return;
518                             }
519                         }
520                     }
521                 }
522             }
523             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
524         }
525         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
526             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
527             return;
528         }
529         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);
530         res = mysql_use();
531         if ((row = mysql_fetch_row(res)) == NULL) {
532             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
533             return;
534         } else if(!strcmp(row[1], "1")) {
535             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
536             return;
537         }
538     }
539     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
540         reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
541         return;
542     }
543     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
544     cbind->func->func(client, user, chan, argv, argc, event);
545 }
546
547 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
548     fd_set fds, fds2;
549     char *trigger;
550     struct ClientSocket *client;
551     FD_ZERO(&fds);
552     FD_ZERO(&fds2);
553     got_chanmsg_loop1:
554     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
555         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))))  {
556             FD_SET(client->clientid, &fds);
557             FD_SET(client->botid, &fds2);
558             trigger = get_channel_trigger(client->botid, client->clientid, chan);
559             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
560                 handle_command(client, user, chan, message + strlen(trigger));
561                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
562             }
563         }
564     }
565     got_chanmsg_loop2:
566     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
567         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
568             FD_SET(client->clientid, &fds);
569             FD_SET(client->botid, &fds2);
570             trigger = get_channel_trigger(client->botid, client->clientid, chan);
571             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
572                 handle_command(client, user, chan, message + strlen(trigger));
573                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
574             }
575         }
576     }
577 }
578
579 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
580     struct ClientSocket *client;
581     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
582         if(client->user == target) {
583             handle_command(client, user, NULL, message);
584         }
585     }
586 }
587
588 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
589     struct cmd_function *cmdfunc;
590     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
591         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
592             return 0;
593     }
594     cmdfunc = malloc(sizeof(*cmdfunc));
595     if (!cmdfunc) {
596         perror("malloc() failed");
597         return 0;
598     }
599     cmdfunc->botid = botid;
600     cmdfunc->name = strdup(name);
601     cmdfunc->func = func;
602     cmdfunc->flags = flags;
603     cmdfunc->paramcount = paramcount;
604     cmdfunc->channel_access = channel_access;
605     cmdfunc->global_access = global_access;
606     cmdfunc->next = cmd_functions;
607     cmd_functions = cmdfunc;
608     return 1;
609 }
610
611 int set_trigger_callback(int botid, trigger_callback_t *func) {
612     static struct trigger_callback *cb = NULL;
613     for(cb = trigger_callbacks; cb; cb = cb->next) {
614         if(cb->botid == botid)
615             break;
616     }
617     if(!cb) {
618         cb = malloc(sizeof(*cb));
619         if (!cb) {
620             perror("malloc() failed");
621             return 0;
622         }
623         cb->botid = botid;
624         cb->next = trigger_callbacks;
625         trigger_callbacks = cb;
626     }
627     cb->func = func;
628     return 1;
629 }
630
631 int flush_trigger_cache(int botid, int clientid) {
632     struct ChanNode *chan;
633     struct trigger_cache *trigger, *last;
634     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
635         last = NULL;
636         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
637             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
638                 if(last)
639                     last->next = trigger->next;
640                 else
641                     chan->trigger = trigger->next;
642                 free(trigger->trigger);
643                 free(trigger);
644                 break;
645             } else
646                 last = trigger;
647         }
648     }
649     return 1;
650 }
651
652 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
653     struct trigger_cache *trigger;
654     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
655         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
656             free(trigger->trigger);
657             trigger->trigger = strdup(new_trigger);
658             return 1;
659         }
660     }
661     return 0;
662 }
663
664 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
665     int bind_index = get_binds_index(cmd[0]);
666     struct cmd_binding *cbind;
667     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
668         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
669             return 0;
670     }
671     cbind = malloc(sizeof(*cbind));
672     if (!cbind) {
673         perror("malloc() failed");
674         return 0;
675     }
676     cbind->botid = botid;
677     cbind->clientid = clientid;
678     cbind->cmd = strdup(cmd);
679     cbind->func = func;
680     cbind->paramcount = 0;
681     cbind->global_access = 0;
682     cbind->channel_access = NULL;
683     cbind->flags = 0;
684     cbind->triggered = 0;
685     cbind->next = cmd_binds[bind_index];
686     cmd_binds[bind_index] = cbind;
687     return 1;
688 }
689
690 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
691     struct cmd_function *cmdfunc;
692     int fbotid = botid;
693     char *c;
694     if((c = strstr(func, "."))) {
695         *c = '\0';
696         struct cmd_bot_alias *botalias;
697         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
698             if(!stricmp(botalias->alias, func)) {
699                 fbotid = botalias->botid;
700                 break;
701             }
702         }
703         *c = '.';
704         func = c+1;
705     }
706     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
707         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
708             break;
709     }
710     if(!cmdfunc) return 0;
711     int bind_index = get_binds_index(cmd[0]);
712     struct cmd_binding *cbind;
713     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
714         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
715             return 0;
716     }
717     cbind = malloc(sizeof(*cbind));
718     if (!cbind) {
719         perror("malloc() failed");
720         return 0;
721     }
722     cbind->botid = botid;
723     cbind->clientid = clientid;
724     cbind->cmd = strdup(cmd);
725     cbind->func = cmdfunc;
726     cbind->next = cmd_binds[bind_index];
727     cbind->paramcount = 0;
728     cbind->global_access = 0;
729     cbind->channel_access = NULL;
730     cbind->flags = 0;
731     cbind->triggered = 0;
732     cmd_binds[bind_index] = cbind;
733     return 1;
734 }
735
736 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
737     int bind_index = get_binds_index(cmd[0]);
738     struct cmd_binding *cbind, *last = NULL;
739     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
740         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
741             if(last)
742                 last->next = cbind->next;
743             else
744                 cmd_binds[bind_index] = cbind->next;
745             free(cbind->cmd);
746             if(cbind->paramcount) {
747                 int i;
748                 for(i = 0; i < cbind->paramcount; i++)
749                     free(cbind->parameters[i]);
750             }
751             if(cbind->channel_access)
752                 free(cbind->channel_access);
753             free(cbind);
754             return 1;
755         } else
756             last = cbind;
757     }
758     return 0;
759 }
760
761 int unbind_botwise_allcmd(int clientid) {
762     int i;
763     for(i = 0; i < 27; i++) {
764         struct cmd_binding *cbind, *next, *last = NULL;
765         for(cbind = cmd_binds[i]; cbind; cbind = next) {
766             next = cbind->next;
767             if(clientid == cbind->clientid) {
768                 if(last)
769                     last->next = cbind->next;
770                 else
771                     cmd_binds[i] = cbind->next;
772                 free(cbind->cmd);
773                 if(cbind->paramcount) {
774                     int j;
775                     for(j = 0; j < cbind->paramcount; j++)
776                         free(cbind->parameters[j]);
777                 }
778                 if(cbind->channel_access)
779                     free(cbind->channel_access);
780                 free(cbind);
781             } else
782                 last = cbind;
783         }
784     }
785     return 1;
786 }
787
788 struct cmd_function *find_cmd_function(int botid, char *name) {
789     struct cmd_function *cmdfunc;
790     char *c;
791     if((c = strstr(name, "."))) {
792         *c = '\0';
793         struct cmd_bot_alias *botalias;
794         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
795             if(!stricmp(botalias->alias, name)) {
796                 botid = botalias->botid;
797                 break;
798             }
799         }
800         *c = '.';
801         name = c+1;
802     }
803     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
804         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
805             break;
806     }
807     return cmdfunc;
808 }
809
810 struct ClientSocket *getTextBot() {
811     return tmp_text_client;
812 }
813
814 void init_modcmd() {
815     cmd_binds = calloc(27, sizeof(*cmd_binds));
816     bind_chanmsg(got_chanmsg);
817     bind_privmsg(got_privmsg);
818     register_default_language_table(msgtab);
819     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
820 }
821
822 void free_modcmd() {
823     int i;
824     for(i = 0; i < 27; i++) {
825         struct cmd_binding *cbind, *next;
826         for(cbind = cmd_binds[i]; cbind; cbind = next) {
827             next = cbind->next;
828             free(cbind->cmd);
829             if(cbind->paramcount) {
830                 int j;
831                 for(j = 0; j < cbind->paramcount; j++)
832                     free(cbind->parameters[j]);
833             }
834             if(cbind->channel_access)
835                 free(cbind->channel_access);
836             free(cbind);
837         }
838     }
839     free(cmd_binds);
840     struct cmd_function *cmdfunct, *next;
841     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
842         next = cmdfunct->next;
843         free(cmdfunct->name);
844         free(cmdfunct);
845     }
846     struct trigger_callback *cb, *next_cb;
847     for(cb = trigger_callbacks; cb; cb = next_cb) {
848         next_cb = cb->next;
849         free(next_cb);
850     }
851     struct cmd_bot_alias *botalias, *next_botalias;
852     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
853         next_botalias = botalias->next;
854         free(botalias->alias);
855         free(botalias);
856     }
857     cmd_functions = NULL;
858     trigger_callbacks = NULL;
859     bot_aliases = NULL;
860 }
861
862 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
863     int bind_index = get_binds_index(cmd[0]);
864     struct cmd_binding *cbind;
865     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
866         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
867             if(cbind->paramcount) {
868                 int i;
869                 for(i = 0; i < cbind->paramcount; i++)
870                     free(cbind->parameters[i]);
871                 cbind->paramcount = 0;
872             }
873             if(parameters) {
874                 char *a, *b = parameters;
875                 do {
876                     a = strstr(b, " ");
877                     if(a) *a = '\0';
878                     cbind->parameters[cbind->paramcount++] = strdup(b);
879                     if(a) b = a+1;
880                 } while(a);
881             }
882             return;
883         }
884     }
885 }
886
887 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
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(gaccess > -1) {
893                 cbind->global_access = gaccess;
894                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
895             } else {
896                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
897             }
898             return;
899         }
900     }
901 }
902
903 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
904     int bind_index = get_binds_index(cmd[0]);
905     struct cmd_binding *cbind;
906     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
907         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
908             if(cbind->channel_access)
909                 free(cbind->channel_access);
910             if(chanaccess) {
911                 cbind->channel_access = strdup(chanaccess);
912                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
913             } else {
914                 cbind->channel_access = NULL;
915                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
916             }
917             return;
918         }
919     }
920 }
921
922 void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
923     int bind_index = get_binds_index(cmd[0]);
924     struct cmd_binding *cbind;
925     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
926         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
927             cbind->flags |= flags;
928             return;
929         }
930     }
931 }
932
933 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
934     int bind_index = get_binds_index(cmd[0]);
935     struct cmd_binding *cbind;
936     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
937         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
938             return cbind;
939         }
940     }
941     return NULL;
942 }
943
944 void bind_botwise_unbound_required_functions(int botid, int clientid) {
945     struct cmd_function *cmdfunc;
946     int i, found;
947     struct cmd_binding *cbind;
948     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
949         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
950             found = 0;
951             for(i = 0; i < 27; i++) {
952                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
953                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
954                         found = 1;
955                         break;
956                     }
957                 }
958                 if(found)
959                     break;
960             }
961             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
962                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
963                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
964             }
965         }
966     }
967 }
968
969 void register_command_alias(int botid, char *alias) {
970     struct cmd_bot_alias *botalias;
971     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
972         if(!stricmp(botalias->alias, alias))
973             return;
974     }
975     botalias = malloc(sizeof(*botalias));
976     if (!botalias) {
977         perror("malloc() failed");
978         return;
979     }
980     botalias->botid = botid;
981     botalias->alias = strdup(alias);
982     botalias->next = bot_aliases;
983     bot_aliases = botalias;
984 }
985
986 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
987     int bind_index;
988     if(last) {
989         if(last->next)
990             return last->next;
991         bind_index = get_binds_index(last->cmd[0]) + 1;
992         if(bind_index > 26)
993             return NULL;
994     } else
995         bind_index = 0;
996     do {
997         if(cmd_binds[bind_index])
998             return cmd_binds[bind_index];
999         bind_index++;
1000     } while(bind_index < 27);
1001     return NULL;
1002 }