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