fixed path of mysql/errmsg.h (OSX compilation fix)
[NeonServV5.git] / src / modcmd.c
1 /* modcmd.c - NeonServ v5.6
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     int module_id;
34     trigger_callback_t *func;
35     
36     struct trigger_callback *next;
37 };
38
39 struct cmd_bot_alias {
40     int botid;
41     char *alias;
42     
43     struct cmd_bot_alias *next;
44 };
45
46 struct command_check_user_cache {
47     struct ClientSocket *client, *textclient;
48     struct UserNode *user;
49     struct ChanNode *chan, *sent_chan;
50     char **argv;
51     int argc;
52     char *message, *args_buffer;
53     struct cmd_binding *cbind;
54 };
55
56 static struct cmd_binding **cmd_binds;
57 static struct cmd_function *cmd_functions = NULL;
58 static struct trigger_callback *trigger_callbacks = NULL;
59 static struct cmd_bot_alias *bot_aliases = NULL;
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 ClientSocket *textclient, 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     if(user)
131         handle_command_async(cache->client, cache->textclient, 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 ClientSocket *textclient, 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 && cbind->func->func == modcmd_linker) {
163             return modcmd_linker_command(client, textclient, 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(textclient, 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             struct ClientSocket *textclient = 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, textclient, 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(textclient, user, "MODCMD_LESS_PARAM_COUNT");
345                 break;
346             }
347             if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_CHAN) && !chan) {
348                 reply(textclient, 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 = textclient;
370                 get_userauth(user, 0, command_checked_auth, data);
371                 return;
372             } else
373                 handle_command_async(client, textclient, 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 ClientSocket *textclient, 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(textclient, user, "MODCMD_AUTH_REQUIRED");
392         return;
393     }
394     if(chan && sent_chan != chan && (BIND_FLAGS(cbind) & CMDFLAG_NO_CROSSCHAN) && !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(textclient, 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(textclient, 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(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
443             else
444                 reply(textclient, 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             struct ChanUser *chanuser = getChanUser(user, chan);
460             str_c = strdup(str_b);
461             str_b = str_c;
462             while((str_a = str_b)) {
463                 str_b = strstr(str_a, ",");
464                 if(str_b) {
465                     *str_b = '\0';
466                     str_b++;
467                 }
468                 if(*str_a == '@' || *str_a == '+') {
469                     //privs can override this access requirement
470                     int priv = 0;
471                     if(*str_a == '@') priv = CHANUSERFLAG_OPPED;
472                     else if(*str_a == '%') priv = CHANUSERFLAG_HALFOPPED;
473                     else if(*str_a == '+') priv = CHANUSERFLAG_VOICED;
474                     if(chanuser && (chanuser->flags & priv)) continue;
475                     str_a++;
476                 }
477                 if(*str_a == '#') {
478                     str_a++;
479                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
480                     access_count++;
481                 } else {
482                     if(atoi(str_a) > minaccess)
483                         minaccess = atoi(str_a);
484                 }
485             }
486             free(str_c);
487         }
488         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
489             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
490             res = mysql_use();
491             if ((row = mysql_fetch_row(res)) != NULL) {
492                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
493                 chan->channel_id = atoi(row[0]);
494                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
495                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
496                     if(uaccess < minaccess && isGodMode(user)) {
497                         eventflags |= CMDFLAG_OPLOG;
498                     } else if(uaccess < minaccess) {
499                         //ACCESS DENIED
500                         reply(textclient, user, "MODCMD_ACCESS_DENIED");
501                         return;
502                     }
503                     if(!row[1] && !defaults) {
504                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
505                         defaults = mysql_fetch_row(mysql_use());
506                     }
507                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
508                         if(isGodMode(user)) {
509                             eventflags |= CMDFLAG_OPLOG;
510                         } else {
511                             //PUBCMD
512                             reply(textclient, user, "MODCMD_PUBCMD", chan->name);
513                             return;
514                         }
515                     }
516                     int i;
517                     for(i = 0; i < access_count; i++) {
518                         if(!row[2+i] && !defaults) {
519                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
520                             defaults = mysql_fetch_row(mysql_use());
521                         }
522                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
523                             if(isGodMode(user)) {
524                                 eventflags |= CMDFLAG_OPLOG;
525                             } else {
526                                 reply(textclient, user, "MODCMD_ACCESS_DENIED");
527                                 return;
528                             }
529                         }
530                     }
531                 }
532             }
533             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
534         }
535         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
536             reply(textclient, user, "MODCMD_CHAN_REQUIRED");
537             return;
538         }
539         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);
540         res = mysql_use();
541         if ((row = mysql_fetch_row(res)) == NULL) {
542             reply(textclient, user, "MODCMD_CHAN_REQUIRED");
543             return;
544         } else if(!strcmp(row[1], "1")) {
545             reply(textclient, user, "MODCMD_CHAN_SUSPENDED");
546             return;
547         }
548     }
549     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
550         reply(textclient, user, "MODCMD_PRIVILEGED", cbind->cmd);
551         return;
552     }
553     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
554     cbind->func->func(client, textclient, user, chan, argv, argc, event);
555 }
556
557 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
558     fd_set fds, fds2;
559     char *trigger;
560     struct ClientSocket *client;
561     FD_ZERO(&fds);
562     FD_ZERO(&fds2);
563     got_chanmsg_loop1:
564     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
565         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))))  {
566             FD_SET(client->clientid, &fds);
567             FD_SET(client->botid, &fds2);
568             trigger = get_channel_trigger(client->botid, client->clientid, chan);
569             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
570                 handle_command(client, user, chan, message + strlen(trigger));
571                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
572             }
573         }
574     }
575     got_chanmsg_loop2:
576     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
577         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
578             FD_SET(client->clientid, &fds);
579             FD_SET(client->botid, &fds2);
580             trigger = get_channel_trigger(client->botid, client->clientid, chan);
581             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
582                 handle_command(client, user, chan, message + strlen(trigger));
583                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
584             }
585         }
586     }
587 }
588
589 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
590     struct ClientSocket *client;
591     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
592         if(client->user == target) {
593             handle_command(client, user, NULL, message);
594         }
595     }
596 }
597
598 int register_command(int botid, char *name, int module_id, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
599     struct cmd_function *cmdfunc;
600     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
601         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, name))
602             return 0;
603     }
604     cmdfunc = malloc(sizeof(*cmdfunc));
605     if (!cmdfunc) {
606         perror("malloc() failed");
607         return 0;
608     }
609     cmdfunc->botid = botid;
610     cmdfunc->name = strdup(name);
611     cmdfunc->module_id = module_id;
612     cmdfunc->func = func;
613     cmdfunc->flags = flags;
614     cmdfunc->paramcount = paramcount;
615     cmdfunc->channel_access = channel_access;
616     cmdfunc->global_access = global_access;
617     cmdfunc->next = cmd_functions;
618     cmd_functions = cmdfunc;
619     return 1;
620 }
621
622 int set_trigger_callback(int botid, int module_id, trigger_callback_t *func) {
623     static struct trigger_callback *cb = NULL;
624     for(cb = trigger_callbacks; cb; cb = cb->next) {
625         if(cb->botid == botid)
626             break;
627     }
628     if(!cb) {
629         cb = malloc(sizeof(*cb));
630         if (!cb) {
631             perror("malloc() failed");
632             return 0;
633         }
634         cb->botid = botid;
635         cb->next = trigger_callbacks;
636         trigger_callbacks = cb;
637     }
638     cb->module_id = module_id;
639     cb->func = func;
640     return 1;
641 }
642
643 int flush_trigger_cache(int botid, int clientid) {
644     struct ChanNode *chan;
645     struct trigger_cache *trigger, *last;
646     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
647         last = NULL;
648         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
649             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
650                 if(last)
651                     last->next = trigger->next;
652                 else
653                     chan->trigger = trigger->next;
654                 free(trigger->trigger);
655                 free(trigger);
656                 break;
657             } else
658                 last = trigger;
659         }
660     }
661     return 1;
662 }
663
664 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
665     struct trigger_cache *trigger;
666     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
667         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
668             free(trigger->trigger);
669             trigger->trigger = strdup(new_trigger);
670             return 1;
671         }
672     }
673     return 0;
674 }
675
676 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
677     int bind_index = get_binds_index(cmd[0]);
678     struct cmd_binding *cbind;
679     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
680         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
681             return 0;
682     }
683     cbind = malloc(sizeof(*cbind));
684     if (!cbind) {
685         perror("malloc() failed");
686         return 0;
687     }
688     cbind->botid = botid;
689     cbind->clientid = clientid;
690     cbind->cmd = strdup(cmd);
691     cbind->func = func;
692     cbind->paramcount = 0;
693     cbind->global_access = 0;
694     cbind->channel_access = NULL;
695     cbind->flags = 0;
696     cbind->triggered = 0;
697     cbind->next = cmd_binds[bind_index];
698     cmd_binds[bind_index] = cbind;
699     return 1;
700 }
701
702 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
703     struct cmd_function *cmdfunc;
704     int fbotid = botid;
705     char *c;
706     if((c = strstr(func, "."))) {
707         *c = '\0';
708         struct cmd_bot_alias *botalias;
709         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
710             if(!stricmp(botalias->alias, func)) {
711                 fbotid = botalias->botid;
712                 break;
713             }
714         }
715         *c = '.';
716         func = c+1;
717     }
718     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
719         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && !stricmp(cmdfunc->name, func))
720             break;
721     }
722     if(!cmdfunc) return 0;
723     int bind_index = get_binds_index(cmd[0]);
724     struct cmd_binding *cbind;
725     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
726         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && !stricmp(cbind->cmd, cmd))
727             return 0;
728     }
729     cbind = malloc(sizeof(*cbind));
730     if (!cbind) {
731         perror("malloc() failed");
732         return 0;
733     }
734     cbind->botid = botid;
735     cbind->clientid = clientid;
736     cbind->cmd = strdup(cmd);
737     cbind->func = cmdfunc;
738     cbind->next = cmd_binds[bind_index];
739     cbind->paramcount = 0;
740     cbind->global_access = 0;
741     cbind->channel_access = NULL;
742     cbind->flags = 0;
743     cbind->triggered = 0;
744     cmd_binds[bind_index] = cbind;
745     return 1;
746 }
747
748 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
749     int bind_index = get_binds_index(cmd[0]);
750     struct cmd_binding *cbind, *last = NULL;
751     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
752         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
753             if(last)
754                 last->next = cbind->next;
755             else
756                 cmd_binds[bind_index] = cbind->next;
757             free(cbind->cmd);
758             if(cbind->paramcount) {
759                 int i;
760                 for(i = 0; i < cbind->paramcount; i++)
761                     free(cbind->parameters[i]);
762             }
763             if(cbind->channel_access)
764                 free(cbind->channel_access);
765             free(cbind);
766             return 1;
767         } else
768             last = cbind;
769     }
770     return 0;
771 }
772
773 int unbind_botwise_allcmd(int botid, int clientid) {
774     int i;
775     for(i = 0; i < 27; i++) {
776         struct cmd_binding *cbind, *next, *last = NULL;
777         for(cbind = cmd_binds[i]; cbind; cbind = next) {
778             next = cbind->next;
779             if((botid == 0 && clientid == cbind->clientid) || (botid && botid == cbind->botid)) {
780                 if(last)
781                     last->next = cbind->next;
782                 else
783                     cmd_binds[i] = cbind->next;
784                 free(cbind->cmd);
785                 if(cbind->paramcount) {
786                     int j;
787                     for(j = 0; j < cbind->paramcount; j++)
788                         free(cbind->parameters[j]);
789                 }
790                 if(cbind->channel_access)
791                     free(cbind->channel_access);
792                 free(cbind);
793             } else
794                 last = cbind;
795         }
796     }
797     return 1;
798 }
799
800 struct cmd_function *find_cmd_function(int botid, char *name) {
801     struct cmd_function *cmdfunc;
802     char *c;
803     if((c = strstr(name, "."))) {
804         *c = '\0';
805         struct cmd_bot_alias *botalias;
806         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
807             if(!stricmp(botalias->alias, name)) {
808                 botid = botalias->botid;
809                 break;
810             }
811         }
812         *c = '.';
813         name = c+1;
814     }
815     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
816         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
817             break;
818     }
819     return cmdfunc;
820 }
821
822 void init_modcmd() {
823     cmd_binds = calloc(27, sizeof(*cmd_binds));
824     bind_chanmsg(got_chanmsg, 0);
825     bind_privmsg(got_privmsg, 0);
826     register_default_language_table(msgtab);
827     register_command(0, "linker", 0, modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
828 }
829
830 void free_modcmd() {
831     int i;
832     for(i = 0; i < 27; i++) {
833         struct cmd_binding *cbind, *next;
834         for(cbind = cmd_binds[i]; cbind; cbind = next) {
835             next = cbind->next;
836             free(cbind->cmd);
837             if(cbind->paramcount) {
838                 int j;
839                 for(j = 0; j < cbind->paramcount; j++)
840                     free(cbind->parameters[j]);
841             }
842             if(cbind->channel_access)
843                 free(cbind->channel_access);
844             free(cbind);
845         }
846     }
847     free(cmd_binds);
848     struct cmd_function *cmdfunct, *next;
849     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
850         next = cmdfunct->next;
851         free(cmdfunct->name);
852         free(cmdfunct);
853     }
854     struct trigger_callback *cb, *next_cb;
855     for(cb = trigger_callbacks; cb; cb = next_cb) {
856         next_cb = cb->next;
857         free(next_cb);
858     }
859     struct cmd_bot_alias *botalias, *next_botalias;
860     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
861         next_botalias = botalias->next;
862         free(botalias->alias);
863         free(botalias);
864     }
865     cmd_functions = NULL;
866     trigger_callbacks = NULL;
867     bot_aliases = NULL;
868 }
869
870 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
871     int bind_index = get_binds_index(cmd[0]);
872     struct cmd_binding *cbind;
873     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
874         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
875             if(cbind->paramcount) {
876                 int i;
877                 for(i = 0; i < cbind->paramcount; i++)
878                     free(cbind->parameters[i]);
879                 cbind->paramcount = 0;
880             }
881             if(parameters) {
882                 char *a, *b = parameters;
883                 do {
884                     a = strstr(b, " ");
885                     if(a) *a = '\0';
886                     cbind->parameters[cbind->paramcount++] = strdup(b);
887                     if(a) b = a+1;
888                 } while(a);
889             }
890             return;
891         }
892     }
893 }
894
895 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
896     int bind_index = get_binds_index(cmd[0]);
897     struct cmd_binding *cbind;
898     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
899         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
900             if(gaccess > -1) {
901                 cbind->global_access = gaccess;
902                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
903             } else {
904                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
905             }
906             return;
907         }
908     }
909 }
910
911 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
912     int bind_index = get_binds_index(cmd[0]);
913     struct cmd_binding *cbind;
914     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
915         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
916             if(cbind->channel_access)
917                 free(cbind->channel_access);
918             if(chanaccess) {
919                 cbind->channel_access = strdup(chanaccess);
920                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
921             } else {
922                 cbind->channel_access = NULL;
923                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
924             }
925             return;
926         }
927     }
928 }
929
930 void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
931     int bind_index = get_binds_index(cmd[0]);
932     struct cmd_binding *cbind;
933     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
934         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
935             cbind->flags |= flags;
936             return;
937         }
938     }
939 }
940
941 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
942     int bind_index = get_binds_index(cmd[0]);
943     struct cmd_binding *cbind;
944     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
945         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && !stricmp(cbind->cmd, cmd)) {
946             return cbind;
947         }
948     }
949     return NULL;
950 }
951
952 void bind_botwise_unbound_required_functions(int botid, int clientid) {
953     struct cmd_function *cmdfunc;
954     int i, found;
955     struct cmd_binding *cbind;
956     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
957         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
958             found = 0;
959             for(i = 0; i < 27; i++) {
960                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
961                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
962                         found = 1;
963                         break;
964                     }
965                 }
966                 if(found)
967                     break;
968             }
969             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
970                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
971                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
972             }
973         }
974     }
975 }
976
977 void register_command_alias(int botid, char *alias) {
978     struct cmd_bot_alias *botalias;
979     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
980         if(!stricmp(botalias->alias, alias))
981             return;
982     }
983     botalias = malloc(sizeof(*botalias));
984     if (!botalias) {
985         perror("malloc() failed");
986         return;
987     }
988     botalias->botid = botid;
989     botalias->alias = strdup(alias);
990     botalias->next = bot_aliases;
991     bot_aliases = botalias;
992 }
993
994 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
995     int bind_index;
996     if(last) {
997         if(last->next)
998             return last->next;
999         bind_index = get_binds_index(last->cmd[0]) + 1;
1000         if(bind_index > 26)
1001             return NULL;
1002     } else
1003         bind_index = 0;
1004     do {
1005         if(cmd_binds[bind_index])
1006             return cmd_binds[bind_index];
1007         bind_index++;
1008     } while(bind_index < 27);
1009     return NULL;
1010 }
1011
1012 void unregister_module_commands(int module_id) {
1013     struct cmd_function *cmdfunct, *nextfunct, *prevfunct = NULL;
1014     int i;
1015     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = nextfunct) {
1016         nextfunct = cmdfunct->next;
1017         if(cmdfunct->module_id == module_id) {
1018             for(i = 0; i < 27; i++) {
1019                 struct cmd_binding *cbind, *next, *last = NULL;
1020                 for(cbind = cmd_binds[i]; cbind; cbind = next) {
1021                     next = cbind->next;
1022                     if(cmdfunct == cbind->func) {
1023                         if(last)
1024                             last->next = cbind->next;
1025                         else
1026                             cmd_binds[i] = cbind->next;
1027                         free(cbind->cmd);
1028                         if(cbind->paramcount) {
1029                             int j;
1030                             for(j = 0; j < cbind->paramcount; j++)
1031                                 free(cbind->parameters[j]);
1032                         }
1033                         if(cbind->channel_access)
1034                             free(cbind->channel_access);
1035                         free(cbind);
1036                     } else
1037                         last = cbind;
1038                 }
1039             }
1040             if(prevfunct) 
1041                 prevfunct->next = nextfunct;
1042             else
1043                 cmd_functions = nextfunct;
1044             free(cmdfunct->name);
1045             free(cmdfunct);
1046         } else
1047             prevfunct = cmdfunct;
1048     }
1049     struct trigger_callback *cb, *prevcb = NULL, *nextcb;
1050     for(cb = trigger_callbacks; cb; cb = nextcb) {
1051         nextcb = cb->next;
1052         if(cb->module_id == module_id) {
1053             if(prevcb)
1054                 prevcb->next = nextcb;
1055             else
1056                 trigger_callbacks = nextcb;
1057             free(cb);
1058         } else
1059             prevcb = cb;
1060     }
1061 }