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