added support for independent "zero-bots" (bots without an own source file)
[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;
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                         if(b[strlen(b)-1] == '-') {
264                             allargs = strlen(b)-1;
265                             b[allargs] = '\0';
266                             argi = atoi(b);
267                             b[allargs] = '-';
268                             allargs = 1;
269                         } else if(b[strlen(b)-1] == '+') {
270                             allargs = strlen(b)-1;
271                             b[allargs] = '\0';
272                             argi = atoi(b);
273                             b[allargs] = '+';
274                             allargs = 2;
275                         } else {
276                             allargs = 0;
277                             argi = atoi(b);
278                         }
279                         if(argi > 0) {
280                             if(argi <= argc) {
281                                 uargs[uargc++] = args_buffer + args_pos;
282                                 if(allargs == 0) {
283                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
284                                 } else if(allargs == 1) {
285                                     args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
286                                     for(argi++; argi <= argc; argi++) {
287                                         uargs[uargc++] = args_buffer + args_pos;
288                                         args_pos += sprintf(args_buffer + args_pos, "%s", argv[argi-1]) + 1;
289                                     }
290                                 } else if(allargs == 2) {
291                                     for(;argi <= argc; argi++) {
292                                         args_pos += sprintf(args_buffer + args_pos, (allargs ? "%s" : " %s"), argv[argi-1]);
293                                         allargs = 0;
294                                     }
295                                     args_pos++;
296                                 }
297                             } else if((cbind->func->flags & CMDFLAG_EMPTY_ARGS)) {
298                                 uargs[uargc++] = args_buffer + args_pos;
299                                 args_buffer[args_pos++] = '\0';
300                             }
301                         } else if(!strcmp(b, "c")) {
302                             uargs[uargc++] = args_buffer + args_pos;
303                             args_pos += sprintf(args_buffer + args_pos, "%s", (chan ? chan->name : "")) + 1;
304                         } else if(!strcmp(b, "n")) {
305                             uargs[uargc++] = args_buffer + args_pos;
306                             args_pos += sprintf(args_buffer + args_pos, "%s", user->nick) + 1;
307                         }
308                     } else {
309                         uargs[uargc++] = args_buffer + args_pos;
310                         args_pos += sprintf(args_buffer + args_pos, "%s", b) + 1;
311                     }
312                 }
313                 argv = uargs;
314                 argc = uargc;
315             }
316             if(argc < cbind->func->paramcount) {
317                 reply(tmp_text_client, user, "MODCMD_LESS_PARAM_COUNT");
318                 break;
319             }
320             if((cbind->func->flags & CMDFLAG_REQUIRE_CHAN) && !chan) {
321                 reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
322                 break;
323             }
324             if(((cbind->func->flags & CMDFLAG_CHECK_AUTH) || (chan && chan != sent_chan && !isUserOnChan(user, chan))) && !(user->flags & USERFLAG_ISAUTHED)) {
325                 //check auth...
326                 struct command_check_user_cache *data = malloc(sizeof(*data));
327                 char **temp_argv = malloc(argc*sizeof(*temp_argv));
328                 if (!data || !temp_argv) {
329                     perror("malloc() failed");
330                     break;
331                 }
332                 memcpy(temp_argv, argv, argc*sizeof(*temp_argv));
333                 data->argv = temp_argv;
334                 data->argc = argc;
335                 data->client = client;
336                 data->user = user;
337                 data->chan = chan;
338                 data->sent_chan = sent_chan;
339                 data->message = message;
340                 data->args_buffer = args_buffer;
341                 data->cbind = cbind;
342                 data->textclient = tmp_text_client;
343                 get_userauth(user, command_checked_auth, data);
344                 return;
345             } else
346                 handle_command_async(client, user, chan, sent_chan, cbind, argv, argc);
347             break;
348         }
349     }
350     free(message);
351     if(args_buffer)
352         free(args_buffer);
353 }
354
355 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) {
356     MYSQL_RES *res;
357     MYSQL_ROW row;
358     int uaccess;
359     char requested_uaccess = 0;
360     int eventflags = (cbind->func->flags & (CMDFLAG_LOG | CMDFLAG_OPLOG));
361     if((cbind->func->flags & CMDFLAG_REQUIRE_AUTH) && !(user->flags & USERFLAG_ISAUTHED)) {
362         reply(tmp_text_client, user, "MODCMD_AUTH_REQUIRED");
363         return;
364     }
365     if(chan && sent_chan != chan && !isUserOnChan(user, chan)) {
366         char user_in_chan = 0;
367         if((user->flags & USERFLAG_ISAUTHED)) {
368             //maybe there's another user authed to user->auth on the channel...
369             struct ChanUser *cchanuser;
370             for(cchanuser = getChannelUsers(chan, NULL); cchanuser; cchanuser = getChannelUsers(chan, cchanuser)) {
371                 if((cchanuser->user->flags & USERFLAG_ISAUTHED) && !stricmp(user->auth, cchanuser->user->auth)) {
372                     user_in_chan = 1;
373                     break;
374                 }
375             }
376         }
377         if(!user_in_chan) {
378             //check if we are allowed to execute commands in this channel
379             requested_uaccess = 1;
380             uaccess = getChannelAccess(user, chan);
381             if(!uaccess) {
382                 reply(tmp_text_client, user, "MODCMD_CROSSCHAN", chan->name);
383                 return;
384             }
385         }
386     }
387     if(sent_chan && sent_chan != chan) {
388         //check pubcmd of this channel
389         printf_mysql_query("SELECT `channel_pubcmd` FROM `channels` WHERE `channel_name` = '%s'", escape_string(sent_chan->name));
390         res = mysql_use();
391         if ((row = mysql_fetch_row(res)) != NULL) {
392             int saccess = getChannelAccess(user, sent_chan);
393             if(row[0] && saccess < atoi(row[0]) && !isGodMode(user)) { //NOTE: HARDCODED DEFAULT: pubcmd = 0
394                 reply(tmp_text_client, user, "MODCMD_PUBCMD", sent_chan->name);
395                 return;
396             }
397         }
398     }
399     int global_access = ((cbind->flags & CMDFLAG_OVERRIDE_GLOBAL_ACCESS) ? cbind->global_access : cbind->func->global_access);
400     if(global_access > 0) {
401         int user_global_access = 0;
402         printf_mysql_query("SELECT `user_access` FROM `users` WHERE `user_user` = '%s'", escape_string(user->auth));
403         res = mysql_use();
404         if ((row = mysql_fetch_row(res)) != NULL) {
405             user_global_access = atoi(row[0]);
406         }
407         if(user_global_access < global_access) {
408             if(!user_global_access)
409                 reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
410             else
411                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
412             return;
413         }
414     }
415     if((cbind->func->flags & CMDFLAG_REGISTERED_CHAN)) {
416         MYSQL_ROW defaults = NULL;
417         char access_list[256];
418         int access_pos = 0;
419         int access_count = 0;
420         int minaccess = 0;
421         char *str_a, *str_b = cbind->func->channel_access, *str_c;
422         if(cbind->flags & CMDFLAG_OVERRIDE_CHANNEL_ACCESS)
423             str_b = cbind->channel_access;
424         access_list[0] = '\0';
425         if(str_b) {
426             str_c = strdup(str_b);
427             str_b = str_c;
428             while((str_a = str_b)) {
429                 str_b = strstr(str_a, ",");
430                 if(str_b) {
431                     *str_b = '\0';
432                     str_b++;
433                 }
434                 if(*str_a == '#') {
435                     str_a++;
436                     access_pos += sprintf(access_list+access_pos, ", `%s`", str_a);
437                     access_count++;
438                 } else {
439                     if(atoi(str_a) > minaccess)
440                         minaccess = atoi(str_a);
441                 }
442             }
443             free(str_c);
444         }
445         if(!(chan->flags & CHANFLAG_REQUESTED_CHANINFO) || (sent_chan && sent_chan == chan) || access_count || minaccess) {
446             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = '%s'", access_list, escape_string(chan->name));
447             res = mysql_use();
448             if ((row = mysql_fetch_row(res)) != NULL) {
449                 chan->flags |= CHANFLAG_CHAN_REGISTERED;
450                 chan->channel_id = atoi(row[0]);
451                 if((sent_chan && sent_chan == chan) || access_count || minaccess) {
452                     if(!requested_uaccess) uaccess = getChannelAccess(user, chan);
453                     if(uaccess < minaccess && isGodMode(user)) {
454                         eventflags |= CMDFLAG_OPLOG;
455                     } else if(uaccess < minaccess) {
456                         //ACCESS DENIED
457                         reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
458                         return;
459                     }
460                     if(!row[1] && !defaults) {
461                         printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
462                         defaults = mysql_fetch_row(mysql_use());
463                     }
464                     if(sent_chan && (sent_chan == chan) && uaccess < (row[1] ? atoi(row[1]) : atoi(defaults[1]))) {
465                         if(isGodMode(user)) {
466                             eventflags |= CMDFLAG_OPLOG;
467                         } else {
468                             //PUBCMD
469                             reply(tmp_text_client, user, "MODCMD_PUBCMD", chan->name);
470                             return;
471                         }
472                     }
473                     int i;
474                     for(i = 0; i < access_count; i++) {
475                         if(!row[2+i] && !defaults) {
476                             printf_mysql_query("SELECT `channel_id`, `channel_pubcmd` %s FROM `channels` WHERE `channel_name` = 'defaults'", access_list);
477                             defaults = mysql_fetch_row(mysql_use());
478                         }
479                         if(uaccess < (row[2+i] ? atoi(row[2+i]) : atoi(defaults[2+i]))) {
480                             if(isGodMode(user)) {
481                                 eventflags |= CMDFLAG_OPLOG;
482                             } else {
483                                 reply(tmp_text_client, user, "MODCMD_ACCESS_DENIED");
484                                 return;
485                             }
486                         }
487                     }
488                 }
489             }
490             chan->flags |= CHANFLAG_REQUESTED_CHANINFO;
491         }
492         if(!(chan->flags & CHANFLAG_CHAN_REGISTERED)) {
493             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
494             return;
495         }
496         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);
497         res = mysql_use();
498         if ((row = mysql_fetch_row(res)) == NULL) {
499             reply(tmp_text_client, user, "MODCMD_CHAN_REQUIRED");
500             return;
501         } else if(!strcmp(row[1], "1")) {
502             reply(tmp_text_client, user, "MODCMD_CHAN_SUSPENDED");
503             return;
504         }
505     }
506     if((cbind->func->flags & CMDFLAG_REQUIRE_GOD) && !isGodMode(user)) {
507         reply(tmp_text_client, user, "MODCMD_PRIVILEGED", cbind->cmd);
508         return;
509     }
510     struct Event *event = createEvent(client, user, chan, cbind, argv, argc, eventflags);
511     cbind->func->func(client, user, chan, argv, argc, event);
512 }
513
514 static void got_chanmsg(struct UserNode *user, struct ChanNode *chan, char *message) {
515     fd_set fds, fds2;
516     char *trigger;
517     struct ClientSocket *client;
518     FD_ZERO(&fds);
519     FD_ZERO(&fds2);
520     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
521         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))))  {
522             FD_SET(client->clientid, &fds);
523             FD_SET(client->botid, &fds2);
524             trigger = get_channel_trigger(client->botid, client->clientid, chan);
525             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
526                 handle_command(client, user, chan, message + strlen(trigger));
527             }
528         }
529     }
530     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
531         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
532             FD_SET(client->botid, &fds);
533             FD_SET(client->botid, &fds2);
534             trigger = get_channel_trigger(client->botid, client->clientid, chan);
535             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
536                 handle_command(client, user, chan, message + strlen(trigger));
537             }
538         }
539     }
540 }
541
542 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
543     struct ClientSocket *client;
544     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
545         if(client->user == target) {
546             handle_command(client, user, NULL, message);
547         }
548     }
549 }
550
551 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
552     struct cmd_function *cmdfunc;
553     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
554         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
555             return 0;
556     }
557     cmdfunc = malloc(sizeof(*cmdfunc));
558     if (!cmdfunc) {
559         perror("malloc() failed");
560         return 0;
561     }
562     cmdfunc->botid = botid;
563     cmdfunc->name = strdup(name);
564     cmdfunc->func = func;
565     cmdfunc->flags = flags;
566     cmdfunc->paramcount = paramcount;
567     cmdfunc->channel_access = channel_access;
568     cmdfunc->global_access = global_access;
569     cmdfunc->next = cmd_functions;
570     cmd_functions = cmdfunc;
571     return 1;
572 }
573
574 int set_trigger_callback(int botid, trigger_callback_t *func) {
575     static struct trigger_callback *cb = NULL;
576     for(cb = trigger_callbacks; cb; cb = cb->next) {
577         if(cb->botid == botid)
578             break;
579     }
580     if(!cb) {
581         cb = malloc(sizeof(*cb));
582         if (!cb) {
583             perror("malloc() failed");
584             return 0;
585         }
586         cb->botid = botid;
587         cb->next = trigger_callbacks;
588         trigger_callbacks = cb;
589     }
590     cb->func = func;
591     return 1;
592 }
593
594 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
595     struct trigger_cache *trigger;
596     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
597         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
598             free(trigger->trigger);
599             trigger->trigger = strdup(new_trigger);
600             return 1;
601         }
602     }
603     return 0;
604 }
605
606 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
607     int bind_index = get_binds_index(cmd[0]);
608     struct cmd_binding *cbind;
609     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
610         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
611             return 0;
612     }
613     cbind = malloc(sizeof(*cbind));
614     if (!cbind) {
615         perror("malloc() failed");
616         return 0;
617     }
618     cbind->botid = botid;
619     cbind->clientid = clientid;
620     cbind->cmd = strdup(cmd);
621     cbind->func = func;
622     cbind->paramcount = 0;
623     cbind->global_access = 0;
624     cbind->channel_access = NULL;
625     cbind->flags = 0;
626     cbind->triggered = 0;
627     cbind->next = cmd_binds[bind_index];
628     cmd_binds[bind_index] = cbind;
629     return 1;
630 }
631
632 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
633     struct cmd_function *cmdfunc;
634     int fbotid = botid;
635     char *c;
636     if((c = strstr(func, "."))) {
637         *c = '\0';
638         struct cmd_bot_alias *botalias;
639         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
640             if(!stricmp(botalias->alias, func)) {
641                 fbotid = botalias->botid;
642                 break;
643             }
644         }
645         *c = '.';
646         func = c+1;
647     }
648     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
649         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
650             break;
651     }
652     if(!cmdfunc) return 0;
653     int bind_index = get_binds_index(cmd[0]);
654     struct cmd_binding *cbind;
655     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
656         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
657             return 0;
658     }
659     cbind = malloc(sizeof(*cbind));
660     if (!cbind) {
661         perror("malloc() failed");
662         return 0;
663     }
664     cbind->botid = botid;
665     cbind->clientid = clientid;
666     cbind->cmd = strdup(cmd);
667     cbind->func = cmdfunc;
668     cbind->next = cmd_binds[bind_index];
669     cbind->paramcount = 0;
670     cbind->global_access = 0;
671     cbind->channel_access = NULL;
672     cbind->flags = 0;
673     cbind->triggered = 0;
674     cmd_binds[bind_index] = cbind;
675     return 1;
676 }
677
678 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
679     int bind_index = get_binds_index(cmd[0]);
680     struct cmd_binding *cbind, *last = NULL;
681     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
682         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
683             if(last)
684                 last->next = cbind->next;
685             else
686                 cmd_binds[bind_index] = cbind->next;
687             free(cbind->cmd);
688             if(cbind->paramcount) {
689                 int i;
690                 for(i = 0; i < cbind->paramcount; i++)
691                     free(cbind->parameters[i]);
692             }
693             free(cbind);
694             return 1;
695         } else
696             last = cbind;
697     }
698     return 0;
699 }
700
701 struct cmd_function *find_cmd_function(int botid, char *name) {
702     struct cmd_function *cmdfunc;
703     char *c;
704     if((c = strstr(name, "."))) {
705         *c = '\0';
706         struct cmd_bot_alias *botalias;
707         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
708             if(!stricmp(botalias->alias, name)) {
709                 botid = botalias->botid;
710                 break;
711             }
712         }
713         *c = '.';
714         name = c+1;
715     }
716     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
717         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
718             break;
719     }
720     return cmdfunc;
721 }
722
723 struct ClientSocket *getTextBot() {
724     return tmp_text_client;
725 }
726
727 void init_modcmd() {
728     cmd_binds = calloc(27, sizeof(*cmd_binds));
729     bind_chanmsg(got_chanmsg);
730     bind_privmsg(got_privmsg);
731     register_default_language_table(msgtab);
732     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
733 }
734
735 void free_modcmd() {
736     int i;
737     for(i = 0; i < 27; i++) {
738         struct cmd_binding *cbind, *next;
739         for(cbind = cmd_binds[i]; cbind; cbind = next) {
740             next = cbind->next;
741             free(cbind->cmd);
742             if(cbind->paramcount) {
743                 int j;
744                 for(j = 0; j < cbind->paramcount; j++)
745                     free(cbind->parameters[j]);
746             }
747             if(cbind->channel_access)
748                 free(cbind->channel_access);
749             free(cbind);
750         }
751     }
752     free(cmd_binds);
753     struct cmd_function *cmdfunct, *next;
754     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
755         next = cmdfunct->next;
756         free(cmdfunct->name);
757         free(cmdfunct);
758     }
759     struct trigger_callback *cb, *next_cb;
760     for(cb = trigger_callbacks; cb; cb = next_cb) {
761         next_cb = cb->next;
762         free(next_cb);
763     }
764     struct cmd_bot_alias *botalias, *next_botalias;
765     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
766         next_botalias = botalias->next;
767         free(botalias->alias);
768         free(botalias);
769     }
770     cmd_functions = NULL;
771     trigger_callbacks = NULL;
772     bot_aliases = NULL;
773 }
774
775 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
776     int bind_index = get_binds_index(cmd[0]);
777     struct cmd_binding *cbind;
778     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
779         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
780             if(cbind->paramcount) {
781                 int i;
782                 for(i = 0; i < cbind->paramcount; i++)
783                     free(cbind->parameters[i]);
784                 cbind->paramcount = 0;
785             }
786             char *a, *b = parameters;
787             do {
788                 a = strstr(b, " ");
789                 if(a) *a = '\0';
790                 cbind->parameters[cbind->paramcount++] = strdup(b);
791                 if(a) b = a+1;
792             } while(a);
793             return;
794         }
795     }
796 }
797
798 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
799     int bind_index = get_binds_index(cmd[0]);
800     struct cmd_binding *cbind;
801     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
802         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
803             if(gaccess > -1) {
804                 cbind->global_access = gaccess;
805                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
806             } else {
807                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
808             }
809             return;
810         }
811     }
812 }
813
814 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
815     int bind_index = get_binds_index(cmd[0]);
816     struct cmd_binding *cbind;
817     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
818         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
819             if(cbind->channel_access)
820                 free(cbind->channel_access);
821             if(chanaccess) {
822                 cbind->channel_access = strdup(chanaccess);
823                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
824             } else {
825                 cbind->channel_access = NULL;
826                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
827             }
828             return;
829         }
830     }
831 }
832
833 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
834     int bind_index = get_binds_index(cmd[0]);
835     struct cmd_binding *cbind;
836     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
837         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
838             return cbind;
839         }
840     }
841     return NULL;
842 }
843
844 void bind_botwise_unbound_required_functions(int botid, int clientid) {
845     struct cmd_function *cmdfunc;
846     int i, found;
847     struct cmd_binding *cbind;
848     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
849         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
850             found = 0;
851             for(i = 0; i < 27; i++) {
852                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
853                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
854                         found = 1;
855                         break;
856                     }
857                 }
858                 if(found)
859                     break;
860             }
861             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
862                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
863                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
864             }
865         }
866     }
867 }
868
869 void register_command_alias(int botid, char *alias) {
870     struct cmd_bot_alias *botalias;
871     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
872         if(!stricmp(botalias->alias, alias))
873             return;
874     }
875     botalias = malloc(sizeof(*botalias));
876     if (!botalias) {
877         perror("malloc() failed");
878         return;
879     }
880     botalias->botid = botid;
881     botalias->alias = strdup(alias);
882     botalias->next = bot_aliases;
883     bot_aliases = botalias;
884 }
885
886 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
887     int bind_index;
888     if(last) {
889         if(last->next)
890             return last->next;
891         bind_index = get_binds_index(last->cmd[0]) + 1;
892         if(bind_index > 26)
893             return NULL;
894     } else
895         bind_index = 0;
896     do {
897         if(cmd_binds[bind_index])
898             return cmd_binds[bind_index];
899         bind_index++;
900     } while(bind_index < 27);
901     return NULL;
902 }