prevent users from executing CrossChannel commands (without being in the target chann...
[NeonServV5.git] / src / modcmd.c
1 /* modcmd.c - NeonServ v5.2
2  * Copyright (C) 2011  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."},
73     {NULL, NULL}
74 };
75
76 static int get_binds_index(char first_char) {
77     if(tolower(first_char) >= 'a' && tolower(first_char) <= 'z') {
78         return tolower(first_char) - 'a';
79     }
80     return 26;
81 }
82
83 struct ClientSocket* get_prefered_bot(int botid) {
84     struct ClientSocket *client, *lowbot = NULL;
85     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
86         if(client->botid == botid) {
87             if((client->flags & SOCKET_FLAG_PREFERRED))
88                 return client;
89             else
90                 lowbot = client;
91         }
92     }
93     return lowbot;
94 }
95
96 static char* get_channel_trigger(int botid, struct ChanNode *chan) {
97     struct trigger_cache *trigger;
98     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
99         if(trigger->botid == botid)
100             return trigger->trigger;
101     }
102     struct trigger_callback *cb;
103     for(cb = trigger_callbacks; cb; cb = cb->next) {
104         if(cb->botid == botid)
105             break;
106     }
107     char triggerStr[TRIGGERLEN];
108     if(cb)
109         cb->func(chan, triggerStr);
110     else
111         strcpy(triggerStr, "+");
112     trigger = malloc(sizeof(*trigger));
113     if (!trigger) {
114         perror("malloc() failed");
115         return 0;
116     }
117     trigger->botid = botid;
118     trigger->trigger = (triggerStr[0] ? strdup(triggerStr) : NULL);
119     trigger->next = chan->trigger;
120     chan->trigger = trigger;
121     return trigger->trigger;
122 }
123
124 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);
125
126 static USERAUTH_CALLBACK(command_checked_auth) {
127     struct command_check_user_cache *cache = data;
128     tmp_text_client = cache->textclient;
129     handle_command_async(cache->client, user, cache->chan, cache->sent_chan, cache->cbind, cache->argv, cache->argc);
130     free(cache->message);
131     if(cache->args_buffer)
132         free(cache->args_buffer);
133     free(cache->argv);
134     free(cache);
135 }
136
137 static CMD_BIND(modcmd_linker) {
138     //fake command for subcommands
139     //just empty
140 }
141
142 static void handle_command(struct ClientSocket *client, struct UserNode *user, struct ChanNode *chan, char *message) {
143     struct ChanNode *sent_chan = chan;
144     if(message[0] == '#') {
145         char *chanName = message;
146         message = strstr(message, " ");
147         if(!message) return;
148         *message = '\0';
149         message++;
150         struct ChanNode *chan2 = getChanByName(chanName);
151         if(chan2)
152             chan = chan2;
153     }
154     message = strdup(message);
155     int bind_index = get_binds_index(message[0]);
156     char *args = strstr(message, " ");
157     char *args_buffer = NULL; //we need this to save a possible pointer to a allocation we need to free
158     if(args) {
159         *args = '\0';
160         args++;
161     }
162     struct cmd_binding *cbind;
163     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
164         if(cbind->botid == client->botid && stricmp(cbind->cmd, message) == 0) {
165             if(cbind->func->func == modcmd_linker) {
166                 //links subcommands
167                 char command[MAXLEN];
168                 struct cmd_binding *parent_bind = cbind;
169                 if(args) {
170                     char *subcmd = args;
171                     args = strstr(args, " ");
172                     if(args) {
173                         *args = '\0';
174                         args++;
175                     }
176                     sprintf(command, "%s %s", parent_bind->cmd, subcmd);
177                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
178                         if(cbind->botid == client->botid && stricmp(cbind->cmd, command) == 0)
179                             break;
180                     }
181                     if(!cbind)
182                         break;
183                 } else {
184                     //list all sub commands
185                     int commandlen = sprintf(command, "%s ", parent_bind->cmd);
186                     char subcommands[MAXLEN];
187                     int subcompos = 0;
188                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
189                         if(cbind->botid == client->botid && stricmplen(cbind->cmd, command, commandlen) == 0) {
190                             subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
191                         }
192                     }
193                     reply(tmp_text_client, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, subcommands);
194                     break;
195                 }
196             }
197             if(statistics_enabled)
198                 statistics_commands++;
199             total_triggered++;
200             cbind->triggered++;
201             if((cbind->func->flags & CMDFLAG_FUNCMD)) {
202                 if(!sent_chan)
203                     break;
204                 chan = sent_chan;
205             }
206             //get a text bot
207             tmp_text_client = get_prefered_bot(client->botid);
208             //parse the arguments...
209             char *arga[MAXNUMPARAMS];
210             char **argv;
211             int argc = 0;
212             int escape = 0;
213             int offset = 0;
214             if(args) {
215                 while(*args) {
216                     //skip leading spaces
217                     while (*args == ' ')
218                         *args++ = 0;
219                     arga[argc++] = args;
220                     if (argc >= MAXNUMPARAMS)
221                         break;
222                     while ((escape || *args != ' ') && *args) {
223                         if((cbind->func->flags & CMDFLAG_ESCAPE_ARGS) && *args == '\\') {
224                             escape = 1;
225                             offset++;
226                         } else if(escape)
227                             escape = 0;
228                         if(!escape && offset) {
229                             args[0 - offset] = args[0];
230                         }
231                         args++;
232                         
233                     }
234                     if(offset) {
235                         args[0-offset] = '\0';
236                         offset = 0;
237                     }
238                 }
239             }
240             argv = arga;
241             if(argc != 0 && argv[0][0] == '#' && !(cbind->func->flags & CMDFLAG_CHAN_PARAM)) {
242                 struct ChanNode *chan2 = getChanByName(argv[0]);
243                 if(chan2) {
244                     argv += 1;
245                     argc -= 1;
246                     chan = chan2;
247                 }
248             }
249             if(cbind->paramcount) {
250                 //userdefined parameters...
251                 args_buffer = malloc(MAXLEN * 2 * sizeof(*args_buffer));
252                 int args_pos = 0;
253                 char *uargs[MAXNUMPARAMS];
254                 int uargc = 0;
255                 char *b;
256                 int i;
257                 int allargs, argi;
258                 for(i = 0; i < cbind->paramcount; i++) {
259                     b = cbind->parameters[i];
260                     if(b[0] == '%') {
261                         b++;
262                         if(b[strlen(b)-1] == '-') {
263                             allargs = strlen(b)-1;
264                             b[allargs] = '\0';
265                             argi = atoi(b);
266                             b[allargs] = '-';
267                             allargs = 1;
268                         } else if(b[strlen(b)-1] == '+') {
269                             allargs = strlen(b)-1;
270                             b[allargs] = '\0';
271                             argi = atoi(b);
272                             b[allargs] = '+';
273                             allargs = 2;
274                         } else {
275                             allargs = 0;
276                             argi = atoi(b);
277                         }
278                         if(argi > 0) {
279                             if(argi <= argc) {
280                                 uargs[uargc++] = args_buffer + args_pos;
281                                 if(allargs == 0) {
282                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
283                                 } else if(allargs == 1) {
284                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
285                                     for(argi++; argi <= argc; argi++) {
286                                         uargs[uargc++] = args_buffer + args_pos;
287                                         args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
288                                     }
289                                 } else if(allargs == 2) {
290                                     for(;argi <= argc; argi++) {
291                                         args_pos += sprintf(args_buffer + args_pos, (allargs ? "%s" : " %s"), argv[argi-1]);
292                                         allargs = 0;
293                                     }
294                                     args_pos++;
295                                 }
296                             } else if((cbind->func->flags & CMDFLAG_EMPTY_ARGS)) {
297                                 uargs[uargc++] = args_buffer + args_pos;
298                                 args_buffer[args_pos++] = '\0';
299                             }
300                         } else if(!strcmp(b, "c")) {
301                             uargs[uargc++] = args_buffer + args_pos;
302                             args_pos += sprintf(args_buffer + args_pos, "%s", (chan ? chan->name : "")) + 1;
303                         } else if(!strcmp(b, "n")) {
304                             uargs[uargc++] = args_buffer + args_pos;
305                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
306                         }
307                     } else {
308                         uargs[uargc++] = args_buffer + args_pos;
309                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
310                     }
311                 }
312                 argv = uargs;
313                 argc = uargc;
314             }
315             if(argc < cbind->func->paramcount) {
316                 reply(tmp_text_client, user, "MODCMD_LESS_PARAM_COUNT");
317                 break;
318             }
319             if((cbind->func->flags & CMDFLAG_REQUIRE_CHAN) && !chan) {
320                 reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
321                 break;
322             }
323             if(((cbind->func->flags & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
324                 //check auth...
325                 struct command_check_user_cache *data = malloc(sizeof(*data));
326                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
327                 if (!data || !temp_argv) {
328                     perror("malloc() failed");
329                     break;
330                 }
331                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
332                 data->argv = temp_argv;
333                 data->argc = argc;
334                 data->client = client;
335                 data->user = user;
336                 data->chan = chan;
337                 data->sent_chan = sent_chan;
338                 data->message = message;
339                 data->args_buffer = args_buffer;
340                 data->cbind = cbind;
341                 data->textclient = tmp_text_client;
342                 get_userauth(user, command_checked_auth, data);
343                 return;
344             } else
345                 handle_command_async(client, user, chan, sent_chan, cbind, argv, argc);
346             break;
347         }
348     }
349     free(message);
350     if(args_buffer)
351         free(args_buffer);
352 }
353
354 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) {
355     MYSQL_RES *res;
356     MYSQL_ROW row;
357     int uaccess;
358     char requested_uaccess = 0;
359     int eventflags = (cbind->func->flags & (CMDFLAG_LOG | CMDFLAG_OPLOG));
360     if((cbind->func->flags & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
361         reply(tmp_text_client, user, "MODCMD_AUTH_REQUIRED");
362         return;
363     }
364     if(chan && sent_chan != chan && !isUserOnChan(user, chan)) {
365         char user_in_chan = 0;
366         if((user->flags & USERFLAG_ISAUTHED)) {
367             //maybe there's another user authed to user->auth on the channel...
368             struct ChanUser *cchanuser;
369             for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
370                 if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
371                     user_in_chan = 1;
372                     break;
373                 }
374             }
375         }
376         if(!user_in_chan) {
377             //check if we are allowed to execute commands in this channel
378             requested_uaccess = 1;
379             uaccess = getChannelAccess(user, chan);
380             if(!uaccess) {
381                 reply(tmp_text_client, user, "MODCMD_CROSSCHAN", chan->name);
382                 return;
383             }
384         }
385     }
386     if(sent_chan && sent_chan != chan) {
387         //check pubcmd of this channel
388         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
389         res = mysql_use();
390         if ((row = mysql_fetch_row(res)) != NULL) {
391             int saccess = getChannelAccess(user, sent_chan);
392             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
393                 reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
394                 return;
395             }
396         }
397     }
398     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
399     if(global_access > 0) {
400         int user_global_access = 0;
401         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
402         res = mysql_use();
403         if ((row = mysql_fetch_row(res)) != NULL) {
404             user_global_access = atoi(row[0]);
405         }
406         if(user_global_access < global_access) {
407             if(!user_global_access)
408                 reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
409             else
410                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
411             return;
412         }
413     }
414     if((cbind->func->flags & CMDFLAG_REGISTERED_CHAN)) {
415         MYSQL_ROW defaults = NULL;
416         char access_list[256];
417         int access_pos = 0;
418         int access_count = 0;
419         int minaccess = 0;
420         char *str_a, *str_b = cbind->func->channel_access, *str_c;
421         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
422             str_b = cbind->channel_access;
423         access_list[0] = '\0';
424         if(str_b) {
425             str_c = strdup(str_b);
426             str_b = str_c;
427             while((str_a = str_b)) {
428                 str_b = strstr(str_a, ",");
429                 if(str_b) {
430                     *str_b = '\0';
431                     str_b++;
432                 }
433                 if(*str_a == '#') {
434                     str_a++;
435                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
436                     access_count++;
437                 } else {
438                     if(atoi(str_a) > minaccess)
439                         minaccess = atoi(str_a);
440                 }
441             }
442             free(str_c);
443         }
444         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
445             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
446             res = mysql_use();
447             if ((row = mysql_fetch_row(res)) != NULL) {
448                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
449                 chan->channel_id = atoi(row[0]);
450                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
451                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
452                     if(uaccess < minaccess && isGodMode(user)) {
453                         eventflags |= CMDFLAG_OPLOG;
454                     } else if(uaccess < minaccess) {
455                         //ACCESS DENIED
456                         reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
457                         return;
458                     }
459                     if(!row[1] && !defaults) {
460                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
461                         defaults = mysql_fetch_row(mysql_use());
462                     }
463                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
464                         if(isGodMode(user)) {
465                             eventflags |= CMDFLAG_OPLOG;
466                         } else {
467                             //PUBCMD
468                             reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
469                             return;
470                         }
471                     }
472                     int i;
473                     for(i = 0; i < access_count; i++) {
474                         if(!row[2+i] && !defaults) {
475                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
476                             defaults = mysql_fetch_row(mysql_use());
477                         }
478                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
479                             if(isGodMode(user)) {
480                                 eventflags |= CMDFLAG_OPLOG;
481                             } else {
482                                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
483                                 return;
484                             }
485                         }
486                     }
487                 }
488             }
489             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
490         }
491         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
492             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
493             return;
494         }
495         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);
496         res = mysql_use();
497         if ((row = mysql_fetch_row(res)) == NULL) {
498             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
499             return;
500         } else if(!strcmp(row[1], "1")) {
501             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
502             return;
503         }
504     }
505     if((cbind->func->flags & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
506         reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
507         return;
508     }
509     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
510     cbind->func->func(client, user, chan, argv, argc, event);
511 }
512
513 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
514     fd_set fds;
515     char *trigger;
516     struct ClientSocket *client;
517     FD_ZERO(&fds);
518     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
519         if(isUserOnChan(client->user, chan) && (client->flags & SOCKET_FLAG_PREFERRED) && !FD_ISSET(client->botid, &fds)) {
520             FD_SET(client->botid, &fds);
521             trigger = get_channel_trigger(client->botid, chan);
522             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
523                 handle_command(client, user, chan, message + strlen(trigger));
524             }
525         }
526     }
527     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
528         if(isUserOnChan(client->user, chan) && !FD_ISSET(client->botid, &fds)) {
529             FD_SET(client->botid, &fds);
530             trigger = get_channel_trigger(client->botid, chan);
531             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
532                 handle_command(client, user, chan, message + strlen(trigger));
533             }
534         }
535     }
536 }
537
538 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
539     struct ClientSocket *client;
540     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
541         if(client->user == target) {
542             handle_command(client, user, NULL, message);
543         }
544     }
545 }
546
547 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
548     struct cmd_function *cmdfunc;
549     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
550         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
551             return 0;
552     }
553     cmdfunc = malloc(sizeof(*cmdfunc));
554     if (!cmdfunc) {
555         perror("malloc() failed");
556         return 0;
557     }
558     cmdfunc->botid = botid;
559     cmdfunc->name = strdup(name);
560     cmdfunc->func = func;
561     cmdfunc->flags = flags;
562     cmdfunc->paramcount = paramcount;
563     cmdfunc->channel_access = channel_access;
564     cmdfunc->global_access = global_access;
565     cmdfunc->next = cmd_functions;
566     cmd_functions = cmdfunc;
567     return 1;
568 }
569
570 int set_trigger_callback(int botid, trigger_callback_t *func) {
571     static struct trigger_callback *cb = NULL;
572     for(cb = trigger_callbacks; cb; cb = cb->next) {
573         if(cb->botid == botid)
574             break;
575     }
576     if(!cb) {
577         cb = malloc(sizeof(*cb));
578         if (!cb) {
579             perror("malloc() failed");
580             return 0;
581         }
582         cb->botid = botid;
583         cb->next = trigger_callbacks;
584         trigger_callbacks = cb;
585     }
586     cb->func = func;
587     return 1;
588 }
589
590 int changeChannelTrigger(int botid, struct ChanNode *chan, char *new_trigger) {
591     struct trigger_cache *trigger;
592     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
593         if(trigger->botid == botid) {
594             free(trigger->trigger);
595             trigger->trigger = strdup(new_trigger);
596             return 1;
597         }
598     }
599     return 0;
600 }
601
602 int bind_cmd_to_function(int botid, char *cmd, struct cmd_function *func) {
603     int bind_index = get_binds_index(cmd[0]);
604     struct cmd_binding *cbind;
605     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
606         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0)
607             return 0;
608     }
609     cbind = malloc(sizeof(*cbind));
610     if (!cbind) {
611         perror("malloc() failed");
612         return 0;
613     }
614     cbind->botid = botid;
615     cbind->cmd = strdup(cmd);
616     cbind->func = func;
617     cbind->paramcount = 0;
618     cbind->global_access = 0;
619     cbind->channel_access = NULL;
620     cbind->flags = 0;
621     cbind->triggered = 0;
622     cbind->next = cmd_binds[bind_index];
623     cmd_binds[bind_index] = cbind;
624     return 1;
625 }
626
627 int bind_cmd_to_command(int botid, char *cmd, char *func) {
628     struct cmd_function *cmdfunc;
629     int fbotid = botid;
630     char *c;
631     if((c = strstr(func, "."))) {
632         *c = '\0';
633         struct cmd_bot_alias *botalias;
634         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
635             if(!stricmp(botalias->alias, func)) {
636                 fbotid = botalias->botid;
637                 break;
638             }
639         }
640         *c = '.';
641         func = c+1;
642     }
643     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
644         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
645             break;
646     }
647     if(!cmdfunc) return 0;
648     int bind_index = get_binds_index(cmd[0]);
649     struct cmd_binding *cbind;
650     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
651         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0)
652             return 0;
653     }
654     cbind = malloc(sizeof(*cbind));
655     if (!cbind) {
656         perror("malloc() failed");
657         return 0;
658     }
659     cbind->botid = botid;
660     cbind->cmd = strdup(cmd);
661     cbind->func = cmdfunc;
662     cbind->next = cmd_binds[bind_index];
663     cbind->paramcount = 0;
664     cbind->global_access = 0;
665     cbind->channel_access = NULL;
666     cbind->flags = 0;
667     cbind->triggered = 0;
668     cmd_binds[bind_index] = cbind;
669     return 1;
670 }
671
672 int unbind_cmd(int botid, char *cmd) {
673     int bind_index = get_binds_index(cmd[0]);
674     struct cmd_binding *cbind, *last = NULL;
675     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
676         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
677             if(last)
678                 last->next = cbind->next;
679             else
680                 cmd_binds[bind_index] = cbind->next;
681             free(cbind->cmd);
682             if(cbind->paramcount) {
683                 int i;
684                 for(i = 0; i < cbind->paramcount; i++)
685                     free(cbind->parameters[i]);
686             }
687             free(cbind);
688             return 1;
689         } else
690             last = cbind;
691     }
692     return 0;
693 }
694
695 struct cmd_function *find_cmd_function(int botid, char *name) {
696     struct cmd_function *cmdfunc;
697     char *c;
698     if((c = strstr(name, "."))) {
699         *c = '\0';
700         struct cmd_bot_alias *botalias;
701         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
702             if(!stricmp(botalias->alias, name)) {
703                 botid = botalias->botid;
704                 break;
705             }
706         }
707         *c = '.';
708         name = c+1;
709     }
710     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
711         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
712             break;
713     }
714     return cmdfunc;
715 }
716
717 struct ClientSocket *getTextBot() {
718     return tmp_text_client;
719 }
720
721 void init_modcmd() {
722     cmd_binds = calloc(27, sizeof(*cmd_binds));
723     bind_chanmsg(got_chanmsg);
724     bind_privmsg(got_privmsg);
725     register_default_language_table(msgtab);
726     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
727 }
728
729 void free_modcmd() {
730     int i;
731     for(i = 0; i < 27; i++) {
732         struct cmd_binding *cbind, *next;
733         for(cbind = cmd_binds[i]; cbind; cbind = next) {
734             next = cbind->next;
735             free(cbind->cmd);
736             if(cbind->paramcount) {
737                 int j;
738                 for(j = 0; j < cbind->paramcount; j++)
739                     free(cbind->parameters[j]);
740             }
741             if(cbind->channel_access)
742                 free(cbind->channel_access);
743             free(cbind);
744         }
745     }
746     free(cmd_binds);
747     struct cmd_function *cmdfunct, *next;
748     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
749         next = cmdfunct->next;
750         free(cmdfunct->name);
751         free(cmdfunct);
752     }
753     struct trigger_callback *cb, *next_cb;
754     for(cb = trigger_callbacks; cb; cb = next_cb) {
755         next_cb = cb->next;
756         free(next_cb);
757     }
758     struct cmd_bot_alias *botalias, *next_botalias;
759     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
760         next_botalias = botalias->next;
761         free(botalias->alias);
762         free(botalias);
763     }
764     cmd_functions = NULL;
765     trigger_callbacks = NULL;
766     bot_aliases = NULL;
767 }
768
769 void bind_set_parameters(int botid, char *cmd, char *parameters) {
770     int bind_index = get_binds_index(cmd[0]);
771     struct cmd_binding *cbind;
772     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
773         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
774             if(cbind->paramcount) {
775                 int i;
776                 for(i = 0; i < cbind->paramcount; i++)
777                     free(cbind->parameters[i]);
778                 cbind->paramcount = 0;
779             }
780             char *a, *b = parameters;
781             do {
782                 a = strstr(b, " ");
783                 if(a) *a = '\0';
784                 cbind->parameters[cbind->paramcount++] = strdup(b);
785                 if(a) b = a+1;
786             } while(a);
787             return;
788         }
789     }
790 }
791
792 void bind_set_global_access(int botid, char *cmd, int gaccess) {
793     int bind_index = get_binds_index(cmd[0]);
794     struct cmd_binding *cbind;
795     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
796         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
797             if(gaccess > -1) {
798                 cbind->global_access = gaccess;
799                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
800             } else {
801                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
802             }
803             return;
804         }
805     }
806 }
807
808 void bind_set_channel_access(int botid, char *cmd, char *chanaccess) {
809     int bind_index = get_binds_index(cmd[0]);
810     struct cmd_binding *cbind;
811     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
812         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
813             if(cbind->channel_access)
814                 free(cbind->channel_access);
815             if(chanaccess) {
816                 cbind->channel_access = strdup(chanaccess);
817                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
818             } else {
819                 cbind->channel_access = NULL;
820                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
821             }
822             return;
823         }
824     }
825 }
826
827 struct cmd_binding *find_cmd_binding(int botid, char *cmd) {
828     int bind_index = get_binds_index(cmd[0]);
829     struct cmd_binding *cbind;
830     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
831         if(cbind->botid == botid && strcmp(cbind->cmd, cmd) == 0) {
832             return cbind;
833         }
834     }
835     return NULL;
836 }
837
838 void bind_unbound_required_functions(int botid) {
839     struct cmd_function *cmdfunc;
840     int i, found;
841     struct cmd_binding *cbind;
842     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
843         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
844             found = 0;
845             for(i = 0; i < 27; i++) {
846                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
847                     if(cbind->botid == botid && cbind->func == cmdfunc) {
848                         found = 1;
849                         break;
850                     }
851                 }
852                 if(found)
853                     break;
854             }
855             if(!found && bind_cmd_to_function(botid, cmdfunc->name, cmdfunc)) {
856                 cbind = find_cmd_binding(botid, cmdfunc->name);
857                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
858             }
859         }
860     }
861 }
862
863 void register_command_alias(int botid, char *alias) {
864     struct cmd_bot_alias *botalias;
865     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
866         if(!stricmp(botalias->alias, alias))
867             return;
868     }
869     botalias = malloc(sizeof(*botalias));
870     if (!botalias) {
871         perror("malloc() failed");
872         return;
873     }
874     botalias->botid = botid;
875     botalias->alias = strdup(alias);
876     botalias->next = bot_aliases;
877     bot_aliases = botalias;
878 }
879
880 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
881     int bind_index;
882     if(last) {
883         if(last->next)
884             return last->next;
885         bind_index = get_binds_index(last->cmd[0]) + 1;
886         if(bind_index > 26)
887             return NULL;
888     } else
889         bind_index = 0;
890     do {
891         if(cmd_binds[bind_index])
892             return cmd_binds[bind_index];
893         bind_index++;
894     } while(bind_index < 27);
895     return NULL;
896 }