fixed cmd_linker output for empty subcommand list
[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             //get a text bot
167             tmp_text_client = get_botwise_prefered_bot(client->botid, (client->botid == 0 ? client->clientid : 0));
168             if(cbind->func->func == modcmd_linker) {
169                 //links subcommands
170                 char command[MAXLEN];
171                 struct cmd_binding *parent_bind = cbind;
172                 if(args) {
173                     char *subcmd = args;
174                     args = strstr(args, " ");
175                     if(args) {
176                         *args = '\0';
177                         args++;
178                     }
179                     sprintf(command, "%s %s", parent_bind->cmd, subcmd);
180                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
181                         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmp(cbind->cmd, command) == 0)
182                             break;
183                     }
184                     if(!cbind)
185                         break;
186                 } else {
187                     //list all sub commands
188                     int commandlen = sprintf(command, "%s ", parent_bind->cmd);
189                     char subcommands[MAXLEN];
190                     int subcompos = 0;
191                     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
192                         if(cbind->botid == client->botid && (cbind->botid || cbind->clientid == client->clientid) && stricmplen(cbind->cmd, command, commandlen) == 0) {
193                             subcompos += sprintf(subcommands + subcompos, (subcompos ? ", %s" : "%s"), cbind->cmd + commandlen);
194                         }
195                     }
196                     reply(tmp_text_client, user, "MODCMD_SUBCOMMANDS", parent_bind->cmd, (subcompos ? subcommands : "\1dnone\1d"));
197                     break;
198                 }
199             }
200             if(statistics_enabled)
201                 statistics_commands++;
202             total_triggered++;
203             cbind->triggered++;
204             if((cbind->func->flags & CMDFLAG_FUNCMD)) {
205                 if(!sent_chan)
206                     break;
207                 chan = sent_chan;
208             }
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     got_chanmsg_loop1:
535     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
536         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))))  {
537             FD_SET(client->clientid, &fds);
538             FD_SET(client->botid, &fds2);
539             trigger = get_channel_trigger(client->botid, client->clientid, chan);
540             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
541                 handle_command(client, user, chan, message + strlen(trigger));
542                 goto got_chanmsg_loop1; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
543             }
544         }
545     }
546     got_chanmsg_loop2:
547     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
548         if(isUserOnChan(client->user, chan) && ((client->botid == 0 && !FD_ISSET(client->clientid, &fds)) || (client->botid && !FD_ISSET(client->botid, &fds2)))) {
549             FD_SET(client->clientid, &fds);
550             FD_SET(client->botid, &fds2);
551             trigger = get_channel_trigger(client->botid, client->clientid, chan);
552             if(trigger && stricmplen(message, trigger, strlen(trigger)) == 0) {
553                 handle_command(client, user, chan, message + strlen(trigger));
554                 goto got_chanmsg_loop2; //Thats really really bad, i know... But we can't count on the "getBots" list anymore after executing a command
555             }
556         }
557     }
558 }
559
560 static void got_privmsg(struct UserNode *user, struct UserNode *target, char *message) {
561     struct ClientSocket *client;
562     for(client = getBots(SOCKET_FLAG_READY, NULL); client; client = getBots(SOCKET_FLAG_READY, client)) {
563         if(client->user == target) {
564             handle_command(client, user, NULL, message);
565         }
566     }
567 }
568
569 int register_command(int botid, char *name, cmd_bind_t *func, int paramcount, char *channel_access, int global_access, unsigned int flags) {
570     struct cmd_function *cmdfunc;
571     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
572         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, name) == 0)
573             return 0;
574     }
575     cmdfunc = malloc(sizeof(*cmdfunc));
576     if (!cmdfunc) {
577         perror("malloc() failed");
578         return 0;
579     }
580     cmdfunc->botid = botid;
581     cmdfunc->name = strdup(name);
582     cmdfunc->func = func;
583     cmdfunc->flags = flags;
584     cmdfunc->paramcount = paramcount;
585     cmdfunc->channel_access = channel_access;
586     cmdfunc->global_access = global_access;
587     cmdfunc->next = cmd_functions;
588     cmd_functions = cmdfunc;
589     return 1;
590 }
591
592 int set_trigger_callback(int botid, trigger_callback_t *func) {
593     static struct trigger_callback *cb = NULL;
594     for(cb = trigger_callbacks; cb; cb = cb->next) {
595         if(cb->botid == botid)
596             break;
597     }
598     if(!cb) {
599         cb = malloc(sizeof(*cb));
600         if (!cb) {
601             perror("malloc() failed");
602             return 0;
603         }
604         cb->botid = botid;
605         cb->next = trigger_callbacks;
606         trigger_callbacks = cb;
607     }
608     cb->func = func;
609     return 1;
610 }
611
612 int changeBotwiseChannelTrigger(int botid, int clientid, struct ChanNode *chan, char *new_trigger) {
613     struct trigger_cache *trigger;
614     for(trigger = chan->trigger; trigger; trigger = trigger->next) {
615         if(trigger->botid == botid && (botid || trigger->clientid == clientid)) {
616             free(trigger->trigger);
617             trigger->trigger = strdup(new_trigger);
618             return 1;
619         }
620     }
621     return 0;
622 }
623
624 int bind_botwise_cmd_to_function(int botid, int clientid, char *cmd, struct cmd_function *func) {
625     int bind_index = get_binds_index(cmd[0]);
626     struct cmd_binding *cbind;
627     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
628         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
629             return 0;
630     }
631     cbind = malloc(sizeof(*cbind));
632     if (!cbind) {
633         perror("malloc() failed");
634         return 0;
635     }
636     cbind->botid = botid;
637     cbind->clientid = clientid;
638     cbind->cmd = strdup(cmd);
639     cbind->func = func;
640     cbind->paramcount = 0;
641     cbind->global_access = 0;
642     cbind->channel_access = NULL;
643     cbind->flags = 0;
644     cbind->triggered = 0;
645     cbind->next = cmd_binds[bind_index];
646     cmd_binds[bind_index] = cbind;
647     return 1;
648 }
649
650 int bind_botwise_cmd_to_command(int botid, int clientid, char *cmd, char *func) {
651     struct cmd_function *cmdfunc;
652     int fbotid = botid;
653     char *c;
654     if((c = strstr(func, "."))) {
655         *c = '\0';
656         struct cmd_bot_alias *botalias;
657         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
658             if(!stricmp(botalias->alias, func)) {
659                 fbotid = botalias->botid;
660                 break;
661             }
662         }
663         *c = '.';
664         func = c+1;
665     }
666     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
667         if((cmdfunc->botid == fbotid || cmdfunc->botid == 0) && strcmp(cmdfunc->name, func) == 0)
668             break;
669     }
670     if(!cmdfunc) return 0;
671     int bind_index = get_binds_index(cmd[0]);
672     struct cmd_binding *cbind;
673     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
674         if(((botid && cbind->botid == botid) || (botid == 0 && clientid == cbind->clientid)) && strcmp(cbind->cmd, cmd) == 0)
675             return 0;
676     }
677     cbind = malloc(sizeof(*cbind));
678     if (!cbind) {
679         perror("malloc() failed");
680         return 0;
681     }
682     cbind->botid = botid;
683     cbind->clientid = clientid;
684     cbind->cmd = strdup(cmd);
685     cbind->func = cmdfunc;
686     cbind->next = cmd_binds[bind_index];
687     cbind->paramcount = 0;
688     cbind->global_access = 0;
689     cbind->channel_access = NULL;
690     cbind->flags = 0;
691     cbind->triggered = 0;
692     cmd_binds[bind_index] = cbind;
693     return 1;
694 }
695
696 int unbind_botwise_cmd(int botid, int clientid, char *cmd) {
697     int bind_index = get_binds_index(cmd[0]);
698     struct cmd_binding *cbind, *last = NULL;
699     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
700         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
701             if(last)
702                 last->next = cbind->next;
703             else
704                 cmd_binds[bind_index] = cbind->next;
705             free(cbind->cmd);
706             if(cbind->paramcount) {
707                 int i;
708                 for(i = 0; i < cbind->paramcount; i++)
709                     free(cbind->parameters[i]);
710             }
711             if(cbind->channel_access)
712                 free(cbind->channel_access);
713             free(cbind);
714             return 1;
715         } else
716             last = cbind;
717     }
718     return 0;
719 }
720
721 int unbind_botwise_allcmd(int clientid) {
722     int i;
723     for(i = 0; i < 27; i++) {
724         struct cmd_binding *cbind, *next, *last = NULL;
725         for(cbind = cmd_binds[i]; cbind; cbind = next) {
726             next = cbind->next;
727             if(clientid == cbind->clientid) {
728                 if(last)
729                     last->next = cbind->next;
730                 else
731                     cmd_binds[i] = cbind->next;
732                 free(cbind->cmd);
733                 if(cbind->paramcount) {
734                     int j;
735                     for(j = 0; j < cbind->paramcount; j++)
736                         free(cbind->parameters[j]);
737                 }
738                 if(cbind->channel_access)
739                     free(cbind->channel_access);
740                 free(cbind);
741             } else
742                 last = cbind;
743         }
744     }
745     return 1;
746 }
747
748 struct cmd_function *find_cmd_function(int botid, char *name) {
749     struct cmd_function *cmdfunc;
750     char *c;
751     if((c = strstr(name, "."))) {
752         *c = '\0';
753         struct cmd_bot_alias *botalias;
754         for(botalias = bot_aliases; botalias; botalias = botalias->next) {
755             if(!stricmp(botalias->alias, name)) {
756                 botid = botalias->botid;
757                 break;
758             }
759         }
760         *c = '.';
761         name = c+1;
762     }
763     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
764         if((cmdfunc->botid == botid || cmdfunc->botid == 0) && stricmp(cmdfunc->name, name) == 0)
765             break;
766     }
767     return cmdfunc;
768 }
769
770 struct ClientSocket *getTextBot() {
771     return tmp_text_client;
772 }
773
774 void init_modcmd() {
775     cmd_binds = calloc(27, sizeof(*cmd_binds));
776     bind_chanmsg(got_chanmsg);
777     bind_privmsg(got_privmsg);
778     register_default_language_table(msgtab);
779     register_command(0, "linker", modcmd_linker, 0, 0, 0, 0); //fake command for subcommands
780 }
781
782 void free_modcmd() {
783     int i;
784     for(i = 0; i < 27; i++) {
785         struct cmd_binding *cbind, *next;
786         for(cbind = cmd_binds[i]; cbind; cbind = next) {
787             next = cbind->next;
788             free(cbind->cmd);
789             if(cbind->paramcount) {
790                 int j;
791                 for(j = 0; j < cbind->paramcount; j++)
792                     free(cbind->parameters[j]);
793             }
794             if(cbind->channel_access)
795                 free(cbind->channel_access);
796             free(cbind);
797         }
798     }
799     free(cmd_binds);
800     struct cmd_function *cmdfunct, *next;
801     for(cmdfunct = cmd_functions; cmdfunct; cmdfunct = next) {
802         next = cmdfunct->next;
803         free(cmdfunct->name);
804         free(cmdfunct);
805     }
806     struct trigger_callback *cb, *next_cb;
807     for(cb = trigger_callbacks; cb; cb = next_cb) {
808         next_cb = cb->next;
809         free(next_cb);
810     }
811     struct cmd_bot_alias *botalias, *next_botalias;
812     for(botalias = bot_aliases; botalias; botalias = next_botalias) {
813         next_botalias = botalias->next;
814         free(botalias->alias);
815         free(botalias);
816     }
817     cmd_functions = NULL;
818     trigger_callbacks = NULL;
819     bot_aliases = NULL;
820 }
821
822 void bind_botwise_set_parameters(int botid, int clientid, char *cmd, char *parameters) {
823     int bind_index = get_binds_index(cmd[0]);
824     struct cmd_binding *cbind;
825     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
826         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
827             if(cbind->paramcount) {
828                 int i;
829                 for(i = 0; i < cbind->paramcount; i++)
830                     free(cbind->parameters[i]);
831                 cbind->paramcount = 0;
832             }
833             char *a, *b = parameters;
834             do {
835                 a = strstr(b, " ");
836                 if(a) *a = '\0';
837                 cbind->parameters[cbind->paramcount++] = strdup(b);
838                 if(a) b = a+1;
839             } while(a);
840             return;
841         }
842     }
843 }
844
845 void bind_botwise_set_global_access(int botid, int clientid, char *cmd, int gaccess) {
846     int bind_index = get_binds_index(cmd[0]);
847     struct cmd_binding *cbind;
848     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
849         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
850             if(gaccess > -1) {
851                 cbind->global_access = gaccess;
852                 cbind->flags |= CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
853             } else {
854                 cbind->flags &= ~CMDFLAG_OVERRIDE_GLOBAL_ACCESS;
855             }
856             return;
857         }
858     }
859 }
860
861 void bind_botwise_set_channel_access(int botid, int clientid, char *cmd, char *chanaccess) {
862     int bind_index = get_binds_index(cmd[0]);
863     struct cmd_binding *cbind;
864     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
865         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
866             if(cbind->channel_access)
867                 free(cbind->channel_access);
868             if(chanaccess) {
869                 cbind->channel_access = strdup(chanaccess);
870                 cbind->flags |= CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
871             } else {
872                 cbind->channel_access = NULL;
873                 cbind->flags &= ~CMDFLAG_OVERRIDE_CHANNEL_ACCESS;
874             }
875             return;
876         }
877     }
878 }
879
880 struct cmd_binding *find_botwise_cmd_binding(int botid, int clientid, char *cmd) {
881     int bind_index = get_binds_index(cmd[0]);
882     struct cmd_binding *cbind;
883     for(cbind = cmd_binds[bind_index]; cbind; cbind = cbind->next) {
884         if(cbind->botid == botid && (botid || clientid == cbind->clientid) && strcmp(cbind->cmd, cmd) == 0) {
885             return cbind;
886         }
887     }
888     return NULL;
889 }
890
891 void bind_botwise_unbound_required_functions(int botid, int clientid) {
892     struct cmd_function *cmdfunc;
893     int i, found;
894     struct cmd_binding *cbind;
895     for(cmdfunc = cmd_functions; cmdfunc; cmdfunc = cmdfunc->next) {
896         if((cmdfunc->flags & CMDFLAG_REQUIRED)) {
897             found = 0;
898             for(i = 0; i < 27; i++) {
899                 for(cbind = cmd_binds[i]; cbind; cbind = cbind->next) {
900                     if(cbind->botid == botid && (botid || clientid == cbind->clientid) && cbind->func == cmdfunc) {
901                         found = 1;
902                         break;
903                     }
904                 }
905                 if(found)
906                     break;
907             }
908             if(!found && bind_botwise_cmd_to_function(botid, clientid, cmdfunc->name, cmdfunc)) {
909                 cbind = find_botwise_cmd_binding(botid, clientid, cmdfunc->name);
910                 cbind->flags |= CMDFLAG_TEMPONARY_BIND;
911             }
912         }
913     }
914 }
915
916 void register_command_alias(int botid, char *alias) {
917     struct cmd_bot_alias *botalias;
918     for(botalias = bot_aliases; botalias; botalias = botalias->next) {
919         if(!stricmp(botalias->alias, alias))
920             return;
921     }
922     botalias = malloc(sizeof(*botalias));
923     if (!botalias) {
924         perror("malloc() failed");
925         return;
926     }
927     botalias->botid = botid;
928     botalias->alias = strdup(alias);
929     botalias->next = bot_aliases;
930     bot_aliases = botalias;
931 }
932
933 struct cmd_binding *getAllBinds(struct cmd_binding *last) {
934     int bind_index;
935     if(last) {
936         if(last->next)
937             return last->next;
938         bind_index = get_binds_index(last->cmd[0]) + 1;
939         if(bind_index > 26)
940             return NULL;
941     } else
942         bind_index = 0;
943     do {
944         if(cmd_binds[bind_index])
945             return cmd_binds[bind_index];
946         bind_index++;
947     } while(bind_index < 27);
948     return NULL;
949 }