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