made commands op, deop, opall, deopall, voice, devoice, voiceall, devoiceall a little...
[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             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(tmp_text_client, 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(tmp_text_client, 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(tmp_text_client, 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(tmp_text_client, 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(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
543             return;
544         } else if(!strcmp(row[1], "1")) {
545             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
546             return;
547         }
548     }
549     if((BIND_FLAGS(cbind) & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
550         reply(tmp_text_client, 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, 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, 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) && strcmp(cmdfunc->name, name) == 0)
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->func = func;
612     cmdfunc->flags = flags;
613     cmdfunc->paramcount = paramcount;
614     cmdfunc->channel_access = channel_access;
615     cmdfunc->global_access = global_access;
616     cmdfunc->next = cmd_functions;
617     cmd_functions = cmdfunc;
618     return 1;
619 }
620
621 int set_trigger_callback(int botid, trigger_callback_t *func) {
622     static struct trigger_callback *cb = NULL;
623     for(cb = trigger_callbacks; cb; cb = cb->next) {
624         if(cb->botid == botid)
625             break;
626     }
627     if(!cb) {
628         cb = malloc(sizeof(*cb));
629         if (!cb) {
630             perror("malloc() failed");
631             return 0;
632         }
633         cb->botid = botid;
634         cb->next = trigger_callbacks;
635         trigger_callbacks = cb;
636     }
637     cb->func = func;
638     return 1;
639 }
640
641 int flush_trigger_cache(int botid, int clientid) {
642     struct ChanNode *chan;
643     struct trigger_cache *trigger, *last;
644     for(chan = getAllChans(NULL); chan; chan = getAllChans(chan)) {
645         last = NULL;
646         for(trigger = chan->trigger; trigger; trigger = trigger->next) {
647             if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
648                 if(last)
649                     last->next = trigger->next;
650                 else
651                     chan->trigger = trigger->next;
652                 free(trigger->trigger);
653                 free(trigger);
654                 break;
655             } else
656                 last = trigger;
657         }
658     }
659     return 1;
660 }
661
662 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
663     struct trigger_cache *trigger;
664     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
665         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
666             free(trigger->trigger);
667             trigger->trigger = strdup(new_trigger);
668             return 1;
669         }
670     }
671     return 0;
672 }
673
674 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
675     int bind_index = get_binds_index(cmd[0]);
676     struct cmd_binding *cbind;
677     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
678         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
679             return 0;
680     }
681     cbind = malloc(sizeof(*cbind));
682     if (!cbind) {
683         perror("malloc() failed");
684         return 0;
685     }
686     cbind->botid = botid;
687     cbind->clientid = clientid;
688     cbind->cmd = strdup(cmd);
689     cbind->func = func;
690     cbind->paramcount = 0;
691     cbind->global_access = 0;
692     cbind->channel_access = NULL;
693     cbind->flags = 0;
694     cbind->triggered = 0;
695     cbind->next = cmd_binds[bind_index];
696     cmd_binds[bind_index] = cbind;
697     return 1;
698 }
699
700 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
701     struct cmd_function *cmdfunc;
702     int fbotid = botid;
703     char *c;
704     if((c = strstr(func, "."))) {
705         *c = '\0';
706         struct cmd_bot_alias *botalias;
707         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
708             if(!stricmp(botalias->alias, func)) {
709                 fbotid = botalias->botid;
710                 break;
711             }
712         }
713         *c = '.';
714         func = c+1;
715     }
716     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
717         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
718             break;
719     }
720     if(!cmdfunc) return 0;
721     int bind_index = get_binds_index(cmd[0]);
722     struct cmd_binding *cbind;
723     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
724         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
725             return 0;
726     }
727     cbind = malloc(sizeof(*cbind));
728     if (!cbind) {
729         perror("malloc() failed");
730         return 0;
731     }
732     cbind->botid = botid;
733     cbind->clientid = clientid;
734     cbind->cmd = strdup(cmd);
735     cbind->func = cmdfunc;
736     cbind->next = cmd_binds[bind_index];
737     cbind->paramcount = 0;
738     cbind->global_access = 0;
739     cbind->channel_access = NULL;
740     cbind->flags = 0;
741     cbind->triggered = 0;
742     cmd_binds[bind_index] = cbind;
743     return 1;
744 }
745
746 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
747     int bind_index = get_binds_index(cmd[0]);
748     struct cmd_binding *cbind, *last = NULL;
749     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
750         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
751             if(last)
752                 last->next = cbind->next;
753             else
754                 cmd_binds[bind_index] = cbind->next;
755             free(cbind->cmd);
756             if(cbind->paramcount) {
757                 int i;
758                 for(i = 0; i < cbind->paramcount; i++)
759                     free(cbind->parameters[i]);
760             }
761             if(cbind->channel_access)
762                 free(cbind->channel_access);
763             free(cbind);
764             return 1;
765         } else
766             last = cbind;
767     }
768     return 0;
769 }
770
771 int unbind_botwise_allcmd(int clientid) {
772     int i;
773     for(i = 0; i < 27; i++) {
774         struct cmd_binding *cbind, *next, *last = NULL;
775         for(cbind = cmd_binds[i]; cbind; cbind = next) {
776             next = cbind->next;
777             if(clientid == cbind->clientid) {
778                 if(last)
779                     last->next = cbind->next;
780                 else
781                     cmd_binds[i] = cbind->next;
782                 free(cbind->cmd);
783                 if(cbind->paramcount) {
784                     int j;
785                     for(j = 0; j < cbind->paramcount; j++)
786                         free(cbind->parameters[j]);
787                 }
788                 if(cbind->channel_access)
789                     free(cbind->channel_access);
790                 free(cbind);
791             } else
792                 last = cbind;
793         }
794     }
795     return 1;
796 }
797
798 struct cmd_function *find_cmd_function(int botid, char *name) {
799     struct cmd_function *cmdfunc;
800     char *c;
801     if((c = strstr(name, "."))) {
802         *c = '\0';
803         struct cmd_bot_alias *botalias;
804         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
805             if(!stricmp(botalias->alias, name)) {
806                 botid = botalias->botid;
807                 break;
808             }
809         }
810         *c = '.';
811         name = c+1;
812     }
813     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
814         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
815             break;
816     }
817     return cmdfunc;
818 }
819
820 struct ClientSocket *getTextBot() {
821     return tmp_text_client;
822 }
823
824 void init_modcmd() {
825     cmd_binds = calloc(27, sizeof(*cmd_binds));
826     bind_chanmsg(got_chanmsg);
827     bind_privmsg(got_privmsg);
828     register_default_language_table(msgtab);
829     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
830 }
831
832 void free_modcmd() {
833     int i;
834     for(i = 0; i < 27; i++) {
835         struct cmd_binding *cbind, *next;
836         for(cbind = cmd_binds[i]; cbind; cbind = next) {
837             next = cbind->next;
838             free(cbind->cmd);
839             if(cbind->paramcount) {
840                 int j;
841                 for(j = 0; j < cbind->paramcount; j++)
842                     free(cbind->parameters[j]);
843             }
844             if(cbind->channel_access)
845                 free(cbind->channel_access);
846             free(cbind);
847         }
848     }
849     free(cmd_binds);
850     struct cmd_function *cmdfunct, *next;
851     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
852         next = cmdfunct->next;
853         free(cmdfunct->name);
854         free(cmdfunct);
855     }
856     struct trigger_callback *cb, *next_cb;
857     for(cb = trigger_callbacks; cb; cb = next_cb) {
858         next_cb = cb->next;
859         free(next_cb);
860     }
861     struct cmd_bot_alias *botalias, *next_botalias;
862     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
863         next_botalias = botalias->next;
864         free(botalias->alias);
865         free(botalias);
866     }
867     cmd_functions = NULL;
868     trigger_callbacks = NULL;
869     bot_aliases = NULL;
870 }
871
872 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
873     int bind_index = get_binds_index(cmd[0]);
874     struct cmd_binding *cbind;
875     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
876         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
877             if(cbind->paramcount) {
878                 int i;
879                 for(i = 0; i < cbind->paramcount; i++)
880                     free(cbind->parameters[i]);
881                 cbind->paramcount = 0;
882             }
883             if(parameters) {
884                 char *a, *b = parameters;
885                 do {
886                     a = strstr(b, " ");
887                     if(a) *a = '\0';
888                     cbind->parameters[cbind->paramcount++] = strdup(b);
889                     if(a) b = a+1;
890                 } while(a);
891             }
892             return;
893         }
894     }
895 }
896
897 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
898     int bind_index = get_binds_index(cmd[0]);
899     struct cmd_binding *cbind;
900     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
901         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
902             if(gaccess > -1) {
903                 cbind->global_access = gaccess;
904                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
905             } else {
906                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
907             }
908             return;
909         }
910     }
911 }
912
913 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
914     int bind_index = get_binds_index(cmd[0]);
915     struct cmd_binding *cbind;
916     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
917         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
918             if(cbind->channel_access)
919                 free(cbind->channel_access);
920             if(chanaccess) {
921                 cbind->channel_access = strdup(chanaccess);
922                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
923             } else {
924                 cbind->channel_access = NULL;
925                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
926             }
927             return;
928         }
929     }
930 }
931
932 void bind_botwise_set_bind_flags(int botid, int clientid, char *cmd, unsigned int flags) {
933     int bind_index = get_binds_index(cmd[0]);
934     struct cmd_binding *cbind;
935     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
936         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
937             cbind->flags |= flags;
938             return;
939         }
940     }
941 }
942
943 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
944     int bind_index = get_binds_index(cmd[0]);
945     struct cmd_binding *cbind;
946     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
947         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
948             return cbind;
949         }
950     }
951     return NULL;
952 }
953
954 void bind_botwise_unbound_required_functions(int botid, int clientid) {
955     struct cmd_function *cmdfunc;
956     int i, found;
957     struct cmd_binding *cbind;
958     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
959         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
960             found = 0;
961             for(i = 0; i < 27; i++) {
962                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
963                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
964                         found = 1;
965                         break;
966                     }
967                 }
968                 if(found)
969                     break;
970             }
971             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
972                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
973                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
974             }
975         }
976     }
977 }
978
979 void register_command_alias(int botid, char *alias) {
980     struct cmd_bot_alias *botalias;
981     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
982         if(!stricmp(botalias->alias, alias))
983             return;
984     }
985     botalias = malloc(sizeof(*botalias));
986     if (!botalias) {
987         perror("malloc() failed");
988         return;
989     }
990     botalias->botid = botid;
991     botalias->alias = strdup(alias);
992     botalias->next = bot_aliases;
993     bot_aliases = botalias;
994 }
995
996 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
997     int bind_index;
998     if(last) {
999         if(last->next)
1000             return last->next;
1001         bind_index = get_binds_index(last->cmd[0]) + 1;
1002         if(bind_index > 26)
1003             return NULL;
1004     } else
1005         bind_index = 0;
1006     do {
1007         if(cmd_binds[bind_index])
1008             return cmd_binds[bind_index];
1009         bind_index++;
1010     } while(bind_index < 27);
1011     return NULL;
1012 }