da6826a71d88042c561195261f784fa3751f5623
[srvx.git] / src / modcmd.c
1 /* modcmd.c - Generalized module command support
2  * Copyright 2002-2007 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "chanserv.h"
22 #include "conf.h"
23 #include "modcmd.h"
24 #include "saxdb.h"
25
26 struct pending_template {
27     struct svccmd *cmd;
28     char *base;
29     struct pending_template *next;
30 };
31
32 static struct dict *modules;
33 static struct dict *services;
34 static struct pending_template *pending_templates;
35 static struct module *modcmd_module;
36 static struct modcmd *bind_command, *help_command, *version_command;
37 static const struct message_entry msgtab[] = {
38     { "MCMSG_BARE_FLAG", "Flag %.*s must be preceded by a + or -." },
39     { "MCMSG_UNKNOWN_FLAG", "Unknown module flag %.*s." },
40     { "MCMSG_BAD_OPSERV_LEVEL", "Invalid $O access level %s." },
41     { "MCMSG_BAD_CHANSERV_LEVEL", "Invalid $C access level %s." },
42     { "MCMSG_LEVEL_TOO_LOW", "You cannot set the access requirements for %s (your level is too low.)" },
43     { "MCMSG_LEVEL_TOO_HIGH", "You cannot set the access requirements to %s (that is too high)." },
44     { "MCMSG_BAD_OPTION", "Unknown option %s." },
45     { "MCMSG_MUST_QUALIFY", "You $bMUST$b \"/msg %s@$s %s\" (not just /msg %s)." },
46     { "MCMSG_ACCOUNT_SUSPENDED", "Your account has been suspended." },
47     { "MCMSG_CHAN_NOT_REGISTERED", "%s has not been registered with $C." },
48     { "MCMSG_CHAN_SUSPENDED", "$b$C$b access to $b%s$b has been temporarily suspended (%s)." },
49     { "MCMSG_NO_CHANNEL_ACCESS", "You lack access to %s." },
50     { "MCMSG_LOW_CHANNEL_ACCESS", "You lack sufficient access in %s to use this command." },
51     { "MCMSG_REQUIRES_JOINABLE", "You must be in %s (or on its userlist) to use this command." },
52     { "MCMSG_MUST_BE_HELPING", "You must have security override (helping mode) on to use this command." },
53     { "MCMSG_MISSING_COMMAND", "You must specify a command as well as a channel." },
54     { "MCMSG_NO_CHANNEL_BEFORE", "You may not give a channel name before this command." },
55     { "MCMSG_NO_PLUS_CHANNEL", "You may not use a +channel with this command." },
56     { "MCMSG_COMMAND_ALIASES", "%s is an alias for: %s" },
57     { "MCMSG_COMMAND_BINDING", "%s is a binding of: %s" },
58     { "MCMSG_ALIAS_ERROR", "Error in alias expansion for %s; check the error log for details." },
59     { "MCMSG_INTERNAL_COMMAND", "$b%s$b is an internal command and cannot be called directly; please check command bindings." },
60     { "MCMSG_UNKNOWN_MODULE", "Unknown module %s." },
61     { "MCMSG_UNKNOWN_SERVICE", "Unknown service %s." },
62     { "MCMSG_ALREADY_BOUND", "%s already has a command bound as %s." },
63     { "MCMSG_UNKNOWN_COMMAND_2", "Unknown command name %s (relative to service %s)." },
64     { "MCMSG_COMMAND_MODIFIED", "Option $b%s$b for $b%s$b has been set." },
65     { "MCMSG_INSPECTION_REFUSED", "You do not have access to inspect command %s." },
66     { "MCMSG_CANNOT_DOUBLE_ALIAS", "You cannot bind to a complex (argument-carrying) bind." },
67     { "MCMSG_BAD_ALIAS_ARGUMENT", "Invalid alias argument $b%s$b." },
68     { "MCMSG_COMMAND_BOUND", "New command %s bound to %s." },
69     { "MCMSG_MODULE_BOUND", "Bound %d commands from %s to %s." },
70     { "MCMSG_NO_COMMAND_BOUND", "%s has nothing bound as command %s." },
71     { "MCMSG_UNBIND_PROHIBITED", "It wouldn't be very much fun to unbind the last %s command, now would it?" },
72     { "MCMSG_COMMAND_UNBOUND", "Unbound command %s from %s." },
73     { "MCMSG_HELPFILE_UNBOUND", "Since that was the last command from module %s on the service, the helpfile for %s was removed." },
74     { "MCMSG_NO_HELPFILE", "Module %s does not have a help file." },
75     { "MCMSG_HELPFILE_ERROR", "Syntax error reading %s; help contents not changed." },
76     { "MCMSG_HELPFILE_READ", "Read %s help database in %lu.%03lu seconds." },
77     { "MCMSG_COMMAND_TIME", "Command $b%s$b finished in %lu.%06lu seconds." },
78     { "MCMSG_NEED_OPSERV_LEVEL", "You must have $O access of at least $b%u$b." },
79     { "MCMSG_NEED_CHANSERV_LEVEL", "You must have $C access of at least $b%u$b in the channel." },
80     { "MCMSG_NEED_ACCOUNT_FLAGS", "You must have account flags $b%s$b." },
81     { "MCMSG_NEED_NOTHING", "Anyone may use the $b%s$b command." },
82     { "MCMSG_NEED_STAFF_ACCESS", "You must be network staff." },
83     { "MCMSG_NEED_STAFF_OPER", "You must be an IRC operator." },
84     { "MCMSG_NEED_STAFF_NETHELPER", "You must be a network helper." },
85     { "MCMSG_NEED_STAFF_NETHELPER_OR_OPER", "You must be a network helper or IRC operator." },
86     { "MCMSG_NEED_STAFF_SHELPER", "You must be a support helper." },
87     { "MCMSG_NEED_STAFF_SHELPER_OR_OPER", "You must be a support helper or IRC operator." },
88     { "MCMSG_NEED_STAFF_HELPER", "You must be a network or support helper." },
89     { "MCMSG_NEED_JOINABLE", "The channel must be open or you must be in the channel or on its userlist." },
90     { "MCMSG_NEED_CHANUSER_CSUSPENDABLE", "You must be on the channel's userlist, and the channel can be suspended." },
91     { "MCMSG_NEED_CHANUSER", "You must be on the channel's userlist." },
92     { "MCMSG_NEED_REGCHAN", "You must specify a channel registered with $C." },
93     { "MCMSG_NEED_CHANNEL", "You must specify a channel that exists." },
94     { "MCMSG_NEED_AUTHED", "You must be authenticated with $N." },
95     { "MCMSG_IS_TOY", "$b%s$b is a toy command." },
96     { "MCMSG_END_REQUIREMENTS", "End of requirements for $b%s$b." },
97     { "MCMSG_ALREADY_HELPING", "You already have security override enabled." },
98     { "MCMSG_ALREADY_NOT_HELPING", "You already have security override disabled." },
99     { "MCMSG_NOW_HELPING", "Security override has been enabled." },
100     { "MCMSG_NOW_NOT_HELPING", "Security override has been disabled." },
101     { "MCMSG_JOINER_CHOICES", "Subcommands of %s: %s" },
102     { "MCMSG_MODULE_INFO", "Commands exported by module $b%s$b:" },
103     { "MCMSG_SERVICE_INFO", "Commands bound to service $b%s$b:" },
104     { "MCMSG_TOYS_DISABLED", "Toys are disabled in %s." },
105     { "MCMSG_PUBLIC_DENY", "Public commands in $b%s$b are restricted." },
106     { "MCMSG_HELPFILE_SEQUENCE", "Help priority %d: %s" },
107     { "MCMSG_HELPFILE_SEQUENCE_SET", "Set helpfile priority sequence for %s." },
108     { "MCMSG_BAD_SERVICE_NICK", "$b%s$b is an invalid nickname." },
109     { "MCMSG_ALREADY_SERVICE", "$b%s$b is already a service." },
110     { "MCMSG_NEW_SERVICE", "Added new service bot $b%s$b." },
111     { "MCMSG_SERVICE_RENAMED", "Service renamed to $b%s$b." },
112     { "MCMSG_NO_TRIGGER", "$b%s$b does not have an in-channel trigger." },
113     { "MCMSG_REMOVED_TRIGGER", "Removed trigger from $b%s$b." },
114     { "MCMSG_DUPLICATE_TRIGGER", "$b%s$b already uses trigger $b%c$b." },
115     { "MCMSG_CURRENT_TRIGGER", "Trigger for $b%s$b is $b%c$b." },
116     { "MCMSG_NEW_TRIGGER", "Changed trigger for $b%s$b to $b%c$b." },
117     { "MCMSG_SERVICE_PRIVILEGED", "Service $b%s$b privileged: $b%s$b." },
118     { "MCMSG_SERVICE_REMOVED", "Service $b%s$b has been deleted." },
119     { "MCMSG_FILE_NOT_OPENED", "Unable to open file $b%s$b for writing." },
120     { "MCMSG_MESSAGES_DUMPED", "Messages written to $b%s$b." },
121     { "MCMSG_MESSAGE_DUMP_FAILED", "Message dump failed: %s." },
122     { "MCMSG_COMMAND_FLAGS", "Command flags are %s (inferred: %s)." },
123     { "MCMSG_COMMAND_ACCOUNT_FLAGS", "Requires account flags +%s, prohibits account flags +%s." },
124     { "MCMSG_COMMAND_ACCESS_LEVEL", "Requires channel access %d and $O access %d." },
125     { "MCMSG_COMMAND_USES", "%s has been used %d times." },
126     { NULL, NULL }
127 };
128 struct userData *_GetChannelUser(struct chanData *channel, struct handle_info *handle, int override, int allow_suspended);
129
130 #define ACTION_ALLOW     1
131 #define ACTION_OVERRIDE  2
132 #define ACTION_NOCHANNEL 4
133 #define ACTION_STAFF     8
134
135 #define RESOLVE_DEPTH    4
136
137 static struct modcmd_flag {
138     const char *name;
139     unsigned int flag;
140 } flags[] = {
141     { "acceptchan", MODCMD_ACCEPT_CHANNEL },
142     { "acceptpluschan", MODCMD_ACCEPT_PCHANNEL },
143     { "authed", MODCMD_REQUIRE_AUTHED },
144     { "channel", MODCMD_REQUIRE_CHANNEL },
145     { "chanuser", MODCMD_REQUIRE_CHANUSER },
146     { "disabled", MODCMD_DISABLED },
147     { "helping", MODCMD_REQUIRE_HELPING },
148     { "ignore_csuspend", MODCMD_IGNORE_CSUSPEND },
149     { "joinable", MODCMD_REQUIRE_JOINABLE },
150     { "keepbound", MODCMD_KEEP_BOUND },
151     { "loghostmask", MODCMD_LOG_HOSTMASK },
152     { "networkhelper", MODCMD_REQUIRE_NETWORK_HELPER },
153     { "never_csuspend", MODCMD_NEVER_CSUSPEND },
154     { "nolog", MODCMD_NO_LOG },
155     { "oper", MODCMD_REQUIRE_OPER },
156     { "qualified", MODCMD_REQUIRE_QUALIFIED },
157     { "regchan", MODCMD_REQUIRE_REGCHAN },
158     { "supporthelper", MODCMD_REQUIRE_SUPPORT_HELPER },
159     { "toy", MODCMD_TOY },
160     { NULL, 0 }
161 };
162
163 static int
164 flags_bsearch(const void *a, const void *b) {
165     const char *key = a;
166     const struct modcmd_flag *flag = b;
167     return ircncasecmp(key, flag->name, strlen(flag->name));
168 }
169
170 static int
171 flags_qsort(const void *a, const void *b) {
172     const struct modcmd_flag *fa = a, *fb = b;
173     return irccasecmp(fa->name, fb->name);
174 }
175
176 DEFINE_LIST(svccmd_list, struct svccmd*)
177 DEFINE_LIST(module_list, struct module*)
178
179 static void
180 free_service_command(void *data) {
181     struct svccmd *svccmd;
182     unsigned int nn;
183
184     svccmd = data;
185     if (svccmd->alias.used) {
186         for (nn=0; nn<svccmd->alias.used; ++nn)
187             free(svccmd->alias.list[nn]);
188         free(svccmd->alias.list);
189     }
190     free(svccmd->name);
191     free(svccmd);
192 }
193
194 static void
195 free_service(void *data) {
196     struct service *service = data;
197     dict_delete(service->commands);
198     module_list_clean(&service->modules);
199     free(service);
200 }
201
202 static void
203 free_module_command(void *data) {
204     struct modcmd *modcmd = data;
205     free_service_command(modcmd->defaults);
206     free(modcmd->name);
207     free(modcmd);
208 }
209
210 static void
211 free_module(void *data) {
212     struct module *module = data;
213     dict_delete(module->commands);
214     close_helpfile(module->helpfile);
215     free(module->name);
216     free(module);
217 }
218
219 struct module *
220 module_register(const char *name, struct log_type *clog, const char *helpfile_name, expand_func_t expand_help) {
221     struct module *newmod;
222
223     newmod = calloc(1, sizeof(*newmod));
224     newmod->name = strdup(name);
225     newmod->commands = dict_new();
226     dict_set_free_data(newmod->commands, free_module_command);
227     newmod->clog = clog;
228     newmod->helpfile_name = helpfile_name;
229     newmod->expand_help = expand_help;
230     if (newmod->helpfile_name) {
231         newmod->helpfile = open_helpfile(newmod->helpfile_name, newmod->expand_help);
232     }
233     dict_insert(modules, newmod->name, newmod);
234     return newmod;
235 }
236
237 struct module *
238 module_find(const char *name) {
239     return dict_find(modules, name, NULL);
240 }
241
242 static void
243 add_pending_template(struct svccmd *cmd, const char *target) {
244     struct pending_template *pending = calloc(1, sizeof(*pending));
245     pending->cmd = cmd;
246     pending->base = strdup(target);
247     pending->next = pending_templates;
248     pending_templates = pending;
249 }
250
251 static struct svccmd *
252 svccmd_resolve_name(struct svccmd *origin, const char *name) {
253     char *sep, svcname[MAXLEN];
254
255     if ((sep = strchr(name, '.'))) {
256         memcpy(svcname, name, sep-name);
257         svcname[sep-name] = 0;
258         name = sep + 1;
259         if (svcname[0] == '*') {
260             struct module *module = module_find(svcname+1);
261             struct modcmd *cmd = module ? dict_find(module->commands, name, NULL) : NULL;
262             return cmd ? cmd->defaults : NULL;
263         } else {
264             struct service *service = service_find(svcname);
265             return service ? dict_find(service->commands, name, NULL) : NULL;
266         }
267     } else {
268         if (origin->parent) {
269             return dict_find(origin->parent->commands, name, NULL);
270         } else {
271             struct modcmd *cmd = dict_find(origin->command->parent->commands, name, NULL);
272             return cmd ? cmd->defaults : NULL;
273         }
274     }
275 }
276
277 static void
278 modcmd_set_effective_flags(struct svccmd *cmd) {
279     int flags = cmd->flags | cmd->command->flags;
280     if (cmd->min_opserv_level > 0)
281         flags |= MODCMD_REQUIRE_OPER;
282     if (cmd->min_channel_access > 0)
283         flags |= MODCMD_REQUIRE_CHANUSER;
284     if (flags & MODCMD_REQUIRE_CHANUSER)
285         flags |= MODCMD_REQUIRE_REGCHAN;
286     if (flags & MODCMD_REQUIRE_REGCHAN)
287         flags |= MODCMD_REQUIRE_CHANNEL;
288     if (flags & (MODCMD_REQUIRE_STAFF|MODCMD_REQUIRE_HELPING))
289         flags |= MODCMD_REQUIRE_AUTHED;
290     cmd->effective_flags = flags;
291 }
292
293 static void
294 svccmd_copy_rules(struct svccmd *dest, struct svccmd *src) {
295     dest->flags |= src->flags;
296     dest->req_account_flags |= src->req_account_flags;
297     dest->deny_account_flags |= src->deny_account_flags;
298     if (src->min_opserv_level > dest->min_opserv_level)
299         dest->min_opserv_level = src->min_opserv_level;
300     if (src->min_channel_access > dest->min_channel_access)
301         dest->min_channel_access = src->min_channel_access;
302     modcmd_set_effective_flags(dest);
303 }
304
305 static int
306 svccmd_configure(struct svccmd *cmd, struct userNode *user, struct userNode *bot, const char *param, const char *value) {
307     if (!irccasecmp(param, "flags")) {
308         unsigned int set_flags, rem_flags;
309         struct modcmd_flag *flag;
310         int opt, end;
311
312         for (set_flags = rem_flags = 0; 1; value += end) {
313             end = strcspn(value, ",");
314             if (*value == '+')
315                 opt = 1;
316             else if (*value == '-')
317                 opt = 0;
318             else {
319                 if (user)
320                     send_message(user, bot, "MCMSG_BARE_FLAG", end, value);
321                 else
322                     log_module(MAIN_LOG, LOG_ERROR, "Flag %.*s must be preceded by a + or - (for command %s).", end, value, cmd->name);
323                 return 0;
324             }
325             value++;
326             flag = bsearch(value, flags, ArrayLength(flags)-1, sizeof(flags[0]), flags_bsearch);
327             if (!flag) {
328                 if (user)
329                     send_message(user, bot, "MCMSG_UNKNOWN_FLAG", end, value);
330                 else
331                     log_module(MAIN_LOG, LOG_ERROR, "Unknown module flag %.*s (for command %s).", end, value, cmd->name);
332                 return 0;
333             }
334             if (opt)
335                 set_flags |= flag->flag, rem_flags &= ~flag->flag;
336             else
337                 rem_flags |= flag->flag, set_flags &= ~flag->flag;
338             if (!value[end-1])
339                 break;
340         }
341         cmd->flags = (cmd->flags | set_flags) & ~rem_flags;
342         return 1;
343     } else if (!irccasecmp(param, "channel_level") || !irccasecmp(param, "channel_access") || !irccasecmp(param, "access")) {
344         unsigned short ul;
345         if (!irccasecmp(value, "none") || !irccasecmp(value, "0")) {
346             cmd->min_channel_access = 0;
347             return 1;
348         } else if ((ul = user_level_from_name(value, UL_OWNER)) > 0) {
349             cmd->min_channel_access = ul;
350             return 1;
351         } else if (user) {
352             send_message(user, bot, "MCMSG_BAD_CHANSERV_LEVEL", value);
353             return 0;
354         } else {
355             log_module(MAIN_LOG, LOG_ERROR, "Invalid ChanServ access level %s (for command %s).", value, cmd->name);
356             return 0;
357         }
358     } else if (!irccasecmp(param, "oper_level") || !irccasecmp(param, "oper_access") || !irccasecmp(param, "level")) {
359         unsigned int newval = atoi(value);
360         if (!isdigit(value[0]) || (newval > 1000)) {
361             if (user)
362                 send_message(user, bot, "MCMSG_BAD_OPSERV_LEVEL", value);
363             else
364                 log_module(MAIN_LOG, LOG_ERROR, "Invalid OpServ access level %s (for command %s).", value, cmd->name);
365             return 0;
366         }
367         if (user && (!user->handle_info || (cmd->min_opserv_level > user->handle_info->opserv_level))) {
368             send_message(user, bot, "MCMSG_LEVEL_TOO_LOW", cmd->name);
369             return 0;
370         }
371         if (user && (!user->handle_info || (newval > user->handle_info->opserv_level))) {
372             send_message(user, bot, "MCMSG_LEVEL_TOO_HIGH", value);
373             return 0;
374         }
375         cmd->min_opserv_level = newval;
376         return 1;
377     } else if (!irccasecmp(param, "account_flags")) {
378         return nickserv_modify_handle_flags(user, bot, value, &cmd->req_account_flags, &cmd->deny_account_flags);
379     } else {
380         if (user)
381             send_message(user, bot, "MCMSG_BAD_OPTION", param);
382         else
383             log_module(MAIN_LOG, LOG_ERROR, "Unknown option %s (for command %s).", param, cmd->name);
384         return 0;
385     }
386 }
387
388 struct modcmd *
389 modcmd_register(struct module *module, const char *name, modcmd_func_t func, unsigned int min_argc, unsigned int flags, ...) {
390     struct modcmd *newcmd;
391     va_list args;
392     const char *param, *value;
393
394     newcmd = calloc(1, sizeof(*newcmd));
395     newcmd->name = strdup(name);
396     newcmd->parent = module;
397     newcmd->func = func;
398     newcmd->min_argc = min_argc;
399     newcmd->flags = flags;
400     newcmd->defaults = calloc(1, sizeof(*newcmd->defaults));
401     newcmd->defaults->name = strdup(newcmd->name);
402     newcmd->defaults->command = newcmd;
403     dict_insert(module->commands, newcmd->name, newcmd);
404     if (newcmd->flags & (MODCMD_REQUIRE_REGCHAN|MODCMD_REQUIRE_CHANNEL|MODCMD_REQUIRE_CHANUSER|MODCMD_REQUIRE_JOINABLE)) {
405         newcmd->defaults->flags |= MODCMD_ACCEPT_CHANNEL;
406     }
407     if (newcmd->flags & MODCMD_REQUIRE_STAFF) {
408         newcmd->defaults->flags |= MODCMD_REQUIRE_AUTHED;
409     }
410     va_start(args, flags);
411     while ((param = va_arg(args, const char*))) {
412         value = va_arg(args, const char*);
413         if (!irccasecmp(param, "template")) {
414             struct svccmd *svccmd = svccmd_resolve_name(newcmd->defaults, value);
415             if (svccmd) {
416                 svccmd_copy_rules(newcmd->defaults, svccmd);
417             } else {
418                 log_module(MAIN_LOG, LOG_ERROR, "Unable to resolve template name %s for %s.%s.", value, newcmd->parent->name, newcmd->name);
419             }
420             add_pending_template(newcmd->defaults, value);
421         } else {
422             svccmd_configure(newcmd->defaults, NULL, NULL, param, value);
423         }
424     }
425     modcmd_set_effective_flags(newcmd->defaults);
426     va_end(args);
427     return newcmd;
428 }
429
430 /* This is kind of a lame hack, but it is actually simpler than having
431  * the permission check vary based on the command itself, or having a
432  * more generic rule system.
433  */
434 int
435 svccmd_can_invoke(struct userNode *user, struct userNode *bot, struct svccmd *cmd, struct chanNode *channel, int options) {
436     extern struct userNode *chanserv;
437     unsigned int uData_checked = 0;
438     struct userData *uData = NULL;
439     int rflags = 0, flags = cmd->effective_flags;
440
441     if (flags & MODCMD_DISABLED) {
442         if (options & SVCCMD_NOISY)
443             send_message(user, bot, "MSG_COMMAND_DISABLED", cmd->name);
444         return 0;
445     }
446     if ((flags & MODCMD_REQUIRE_QUALIFIED) && !(options & SVCCMD_QUALIFIED)) {
447         if (options & SVCCMD_NOISY)
448             send_message(user, bot, "MCMSG_MUST_QUALIFY", bot->nick, cmd->name, bot->nick);
449         return 0;
450     }
451     if (flags & MODCMD_REQUIRE_AUTHED) {
452         if (!user->handle_info) {
453             if (options & SVCCMD_NOISY)
454                 send_message(user, bot, "MSG_AUTHENTICATE");
455             return 0;
456         }
457         if (HANDLE_FLAGGED(user->handle_info, SUSPENDED)) {
458             if (options & SVCCMD_NOISY)
459                 send_message(user, bot, "MCMSG_ACCOUNT_SUSPENDED");
460             return 0;
461         }
462     }
463     if (channel || (options & SVCCMD_NOISY)) {
464         if ((flags & MODCMD_REQUIRE_CHANNEL) && !channel) {
465             if (options & SVCCMD_NOISY)
466                 send_message(user, bot, "MSG_INVALID_CHANNEL");
467             return 0;
468         }
469         if (flags & MODCMD_REQUIRE_REGCHAN) {
470             if (!chanserv) {
471                 /* Just use the inferred MODCMD_REQUIRE_CHANNEL. */
472             } else if (!channel->channel_info) {
473                 if (options & SVCCMD_NOISY)
474                     send_message(user, bot, "MCMSG_CHAN_NOT_REGISTERED", channel->name);
475                 return 0;
476             } else if (IsSuspended(channel->channel_info) && !(flags & MODCMD_IGNORE_CSUSPEND)) {
477                 /* Allow security-override users to ignore most channel
478                  * suspensions, but flag that use as a staff command.
479                  */
480                 if (!IsHelping(user) || (flags & MODCMD_NEVER_CSUSPEND)) {
481                     if (options & SVCCMD_NOISY)
482                         send_message(user, bot, "MCMSG_CHAN_SUSPENDED", channel->name, channel->channel_info->suspended->reason);
483                     return 0;
484                 }
485                 rflags |= ACTION_STAFF;
486             }
487         }
488         if (flags & MODCMD_REQUIRE_CHANUSER) {
489             if (!uData_checked)
490                 uData = _GetChannelUser(channel->channel_info, user->handle_info, 1, 0), uData_checked = 1;
491             if (!chanserv) {
492                 /* Assume someone knows what they're doing. */
493             } else if (!uData) {
494                 if (options & SVCCMD_NOISY)
495                     send_message(user, bot, "MCMSG_NO_CHANNEL_ACCESS", channel->name);
496                 return 0;
497             } else if (uData->access < cmd->min_channel_access) {
498                 if (options & SVCCMD_NOISY)
499                     send_message(user, bot, "MCMSG_LOW_CHANNEL_ACCESS", channel->name);
500                 return 0;
501             }
502         }
503         if ((flags & MODCMD_REQUIRE_JOINABLE) && channel) {
504             if (!uData_checked)
505                 uData = _GetChannelUser(channel->channel_info, user->handle_info, 1, 0), uData_checked = 1;
506             if ((channel->modes & (MODE_INVITEONLY|MODE_KEY|MODE_SECRET))
507                 && !uData
508                 && !IsService(user)
509                 && !GetUserMode(channel, user)) {
510                 if (options & SVCCMD_NOISY)
511                     send_message(user, bot, "MCMSG_REQUIRES_JOINABLE", channel->name);
512                 return 0;
513             }
514         }
515         if ((flags & MODCMD_TOY) && channel) {
516             if (!channel->channel_info)
517                 rflags |= ACTION_NOCHANNEL;
518             else switch (channel->channel_info->chOpts[chToys]) {
519             case 'd':
520                 if (options & SVCCMD_NOISY)
521                     send_message(user, bot, "MCMSG_TOYS_DISABLED", channel->name);
522                 return 0;
523             case 'n':
524                 rflags |= ACTION_NOCHANNEL;
525                 break;
526             case 'p':
527                 break;
528             }
529         }
530     }
531     if (flags & MODCMD_REQUIRE_STAFF) {
532         if (((flags & MODCMD_REQUIRE_OPER) && IsOper(user))
533             || ((flags & MODCMD_REQUIRE_NETWORK_HELPER) && IsNetworkHelper(user))
534             || ((flags & MODCMD_REQUIRE_SUPPORT_HELPER) && IsSupportHelper(user))) {
535             /* allow it */
536             rflags |= ACTION_STAFF;
537         } else {
538             if (options & SVCCMD_NOISY)
539                 send_message(user, bot, "MSG_COMMAND_PRIVILEGED", cmd->name);
540             return 0;
541         }
542     }
543     if (flags & MODCMD_REQUIRE_HELPING) {
544         if (!HANDLE_FLAGGED(user->handle_info, HELPING)) {
545             if (options & SVCCMD_NOISY)
546                 send_message(user, bot, "MCMSG_MUST_BE_HELPING");
547             return 0;
548         }
549         rflags |= ACTION_STAFF;
550     }
551     if (cmd->min_opserv_level > 0) {
552         if (!oper_has_access(user, bot, cmd->min_opserv_level, !(options & SVCCMD_NOISY)))
553             return 0;
554         rflags |= ACTION_STAFF;
555     }
556     if (cmd->req_account_flags || cmd->deny_account_flags) {
557         if (!user->handle_info) {
558             if (options & SVCCMD_NOISY)
559                 send_message(user, bot, "MSG_AUTHENTICATE");
560             return 0;
561         }
562         /* Do we want separate or different messages here? */
563         if ((cmd->req_account_flags & ~user->handle_info->flags)
564             || (cmd->deny_account_flags & user->handle_info->flags)) {
565             if (options & SVCCMD_NOISY)
566                 send_message(user, bot, "MSG_COMMAND_PRIVILEGED", cmd->name);
567             return 0;
568         }
569     }
570
571     /* If it's an override, return a special value. */
572     if ((flags & MODCMD_REQUIRE_CHANUSER)
573         && (options & SVCCMD_NOISY)
574         && (!uData || (uData->access > 500))
575         && (!(uData = _GetChannelUser(channel->channel_info, user->handle_info, 0, 0))
576             || uData->access < cmd->min_channel_access)
577         && !(flags & (MODCMD_REQUIRE_STAFF|MODCMD_REQUIRE_HELPING))) {
578         rflags |= ACTION_OVERRIDE;
579     }
580     return rflags | ACTION_ALLOW;
581 }
582
583 static int
584 svccmd_expand_alias(struct svccmd *cmd, unsigned int old_argc, char *old_argv[], char *new_argv[]) {
585     unsigned int ii, new_argc;
586     char *arg;
587
588     for (ii=new_argc=0; ii<cmd->alias.used; ++ii) {
589         arg = cmd->alias.list[ii];
590         if (arg[0] != '$') {
591             new_argv[new_argc++] = arg;
592             continue;
593         }
594         if (arg[1] == '$') {
595             new_argv[new_argc++] = arg + 1;
596         } else if (isdigit(arg[1])) {
597             unsigned int lbound, ubound, jj;
598             char *end_num;
599
600             lbound = strtoul(arg+1, &end_num, 10);
601             switch (end_num[0]) {
602             case 0: ubound = lbound; break;
603             case '-':
604                 if (end_num[1] == 0) {
605                     ubound = old_argc - 1;
606                     break;
607                 } else if (isdigit(end_num[1])) {
608                     ubound = strtoul(end_num+1, NULL, 10);
609                     break;
610                 }
611                 /* else fall through to default case */
612             default:
613                 log_module(MAIN_LOG, LOG_ERROR, "Alias expansion parse error in %s (near %s; %s.%s arg %d).", arg, end_num, cmd->parent->bot->nick, cmd->name, ii);
614                 return 0;
615             }
616             if (lbound >= old_argc)
617                 return -1;
618             if (ubound >= old_argc)
619                 ubound = old_argc - 1;
620             if (lbound < old_argc)
621                 for (jj = lbound; jj <= ubound; )
622                     new_argv[new_argc++] = old_argv[jj++];
623         } else {
624             log_module(MAIN_LOG, LOG_ERROR, "Alias expansion: I do not know how to handle %s (%s.%s arg %d).", arg, cmd->parent->bot->nick, cmd->name, ii);
625             return 0;
626         }
627     }
628     return new_argc;
629 }
630
631 int
632 svccmd_invoke_argv(struct userNode *user, struct service *service, struct chanNode *channel, unsigned int argc, char *argv[], unsigned int server_qualified) {
633     extern struct userNode *chanserv;
634     struct svccmd *cmd;
635     unsigned int cmd_arg, perms, flags, options, result;
636     char channel_name[CHANNELLEN+1];
637
638     /* First check pubcmd for the channel. */
639     if (channel && (channel->channel_info) && (service->bot == chanserv)
640         && !check_user_level(channel, user, lvlPubCmd, 1, 0)) {
641         send_message(user, service->bot, "MCMSG_PUBLIC_DENY", channel->name);
642         return 0;
643     }
644
645     options = (server_qualified ? SVCCMD_QUALIFIED : 0) | SVCCMD_DEBIT | SVCCMD_NOISY;
646     /* Find the command argument. */
647     cmd_arg = IsChannelName(argv[0]) ? 1 : 0;
648     if (argc < cmd_arg+1) {
649         send_message(user, service->bot, "MCMSG_MISSING_COMMAND");
650         return 0;
651     }
652     if (!isalnum(*argv[cmd_arg])) {
653         /* Silently ignore stuff that doesn't begin with a letter or number. */
654         return 0;
655     }
656     cmd = dict_find(service->commands, argv[cmd_arg], NULL);
657     if (!cmd) {
658         if (!channel)
659             send_message(user, service->bot, "MSG_COMMAND_UNKNOWN", argv[cmd_arg]);
660         return 0;
661     }
662     flags = cmd->effective_flags;
663     /* If they put a channel name first, check if the command allows
664      * it.  If so, swap it with the command name.
665      */
666     if (cmd_arg == 1) {
667         char *tmp;
668         /* Complain if we're not supposed to accept the channel. */
669         if (!(flags & MODCMD_ACCEPT_CHANNEL)) {
670             send_message(user, service->bot, "MCMSG_NO_CHANNEL_BEFORE");
671             return 0;
672         }
673         if (!(flags & MODCMD_ACCEPT_PCHANNEL)
674             && (argv[0][0] == '+')) {
675             send_message(user, service->bot, "MCMSG_NO_PLUS_CHANNEL");
676             return 0;
677         }
678         tmp = argv[1];
679         argv[1] = argv[0];
680         argv[0] = tmp;
681     }
682
683     /* Try to grab a channel handle before alias expansion.
684      * If the command accepts a channel name, and argv[1] is
685      * one, use it as a channel name, and hide it from logging.
686      */
687     if ((argc > 1)
688         && (flags & MODCMD_ACCEPT_CHANNEL)
689         && IsChannelName(argv[1])
690         && ((argv[1][0] != '+') || (flags & MODCMD_ACCEPT_PCHANNEL))
691         && (channel = dict_find(channels, argv[1], NULL))) {
692         argv[1] = argv[0];
693         argv++, argc--;
694         cmd_arg = 1;
695     }
696
697     /* Expand the alias arguments, if there are any. */
698     if (cmd->alias.used) {
699         char *new_argv[MAXNUMPARAMS];
700         int res;
701
702         res = svccmd_expand_alias(cmd, argc, argv, new_argv);
703         if (res < 0) {
704             send_message(user, service->bot, "MSG_MISSING_PARAMS", cmd->name);
705             return 0;
706         } else if (res == 0) {
707             send_message(user, service->bot, "MCMSG_ALIAS_ERROR", cmd->name);
708             return 0;
709         }
710         argc = res;
711         argv = new_argv;
712
713         /* Try again to grab a handle to the channel after alias
714          * expansion, overwriting any previous channel. This should,
715          * of course, only be done again if an alias was acually
716          * expanded. */
717         if ((argc > 1)
718             && (flags & MODCMD_ACCEPT_CHANNEL)
719             && IsChannelName(argv[1])
720             && ((argv[1][0] != '+') || (flags & MODCMD_ACCEPT_PCHANNEL))
721             && (channel = dict_find(channels, argv[1], NULL))) {
722             argv[1] = argv[0];
723             argv++, argc--;
724             cmd_arg = 1;
725         }
726     }
727
728     /* Figure out what actions we should do for it.. */
729     if (cmd_arg && (flags & MODCMD_TOY)) {
730         /* Do not let user manually specify a channel. */
731         channel = NULL;
732     }
733     if (argc < cmd->command->min_argc) {
734         send_message(user, service->bot, "MSG_MISSING_PARAMS", cmd->name);
735         return 0;
736     }
737     if (!cmd->command->func) {
738         send_message(user, service->bot, "MCMSG_INTERNAL_COMMAND", cmd->name);
739         return 0;
740     }
741     perms = svccmd_can_invoke(user, service->bot, cmd, channel, options);
742     if (!perms)
743         return 0;
744     cmd->uses++;
745     if (perms & ACTION_NOCHANNEL)
746         channel = NULL;
747
748     if (channel)
749         safestrncpy(channel_name, channel->name, sizeof(channel_name));
750     else
751         channel_name[0] = 0;
752     if (!(result = cmd->command->func(user, channel, argc, argv, cmd)))
753         return 0;
754     if (!(flags & MODCMD_NO_LOG)) {
755         enum log_severity slvl;
756         if (result & CMD_LOG_OVERRIDE)
757             slvl = LOG_OVERRIDE;
758         else if ((perms & ACTION_STAFF) || (result & CMD_LOG_STAFF))
759             slvl = LOG_STAFF;
760         else if (perms & ACTION_OVERRIDE)
761             slvl = LOG_OVERRIDE;
762         else
763             slvl = LOG_COMMAND;
764         /* Unsplit argv after running the function to get the benefit
765          * of any mangling/hiding done by the commands. */
766         log_audit(cmd->command->parent->clog, slvl, user, service->bot, channel_name, ((flags & MODCMD_LOG_HOSTMASK) ? AUDIT_HOSTMASK : 0), unsplit_string(argv, argc, NULL));
767     }
768     return 1;
769 }
770
771 int
772 svccmd_send_help(struct userNode *user, struct userNode *bot, struct svccmd *cmd) {
773     char cmdname[MAXLEN];
774     unsigned int nn;
775     /* Show command name (in bold). */
776     for (nn=0; cmd->name[nn]; nn++)
777         cmdname[nn] = toupper(cmd->name[nn]);
778     cmdname[nn] = 0;
779     send_message_type(4, user, bot, "$b%s$b", cmdname);
780     /* If it's an alias, show what it's an alias for. */
781     if (cmd->alias.used) {
782         char alias_text[MAXLEN];
783         unsplit_string((char**)cmd->alias.list, cmd->alias.used, alias_text);
784         send_message(user, bot, "MCMSG_COMMAND_ALIASES", cmd->name, alias_text);
785     }
786     /* Show the help entry for the underlying command. */
787     return send_help(user, bot, cmd->command->parent->helpfile, cmd->command->name);
788 }
789
790 int
791 svccmd_send_help_2(struct userNode *user, struct service *service, const char *topic) {
792     struct module *module;
793     struct svccmd *cmd;
794     unsigned int ii;
795
796     if ((cmd = dict_find(service->commands, topic, NULL)))
797         return svccmd_send_help(user, service->bot, cmd);
798     if (!topic)
799         topic = "<index>";
800     for (ii = 0; ii < service->modules.used; ++ii) {
801         module = service->modules.list[ii];
802         if (!module->helpfile)
803             continue;
804         if (dict_find(module->helpfile->db, topic, NULL))
805             return send_help(user, service->bot, module->helpfile, topic);
806     }
807     send_message(user, service->bot, "MSG_TOPIC_UNKNOWN");
808     return 0;
809 }
810
811 static int
812 svccmd_invoke(struct userNode *user, struct service *service, struct chanNode *channel, const char *text, int server_qualified) {
813     unsigned int argc;
814     char *argv[MAXNUMPARAMS];
815     char tmpline[MAXLEN];
816
817     if (!*text)
818         return 0;
819     if (service->privileged) {
820         if (!IsOper(user)) {
821             send_message(user, service->bot, "MSG_SERVICE_PRIVILEGED", service->bot->nick);
822             return 0;
823         }
824         if (!user->handle_info) {
825             send_message(user, service->bot, "MSG_AUTHENTICATE");
826             return 0;
827         }
828         if (HANDLE_FLAGGED(user->handle_info, OPER_SUSPENDED)) {
829             send_message(user, service->bot, "MSG_OPER_SUSPENDED");
830             return 0;
831         }
832     }
833     safestrncpy(tmpline, text, sizeof(tmpline));
834     argc = split_line(tmpline, false, ArrayLength(argv), argv);
835     return argc ? svccmd_invoke_argv(user, service, channel, argc, argv, server_qualified) : 0;
836 }
837
838 void
839 modcmd_privmsg(struct userNode *user, struct userNode *bot, const char *text, int server_qualified) {
840     struct service *service;
841
842     if (!(service = dict_find(services, bot->nick, NULL))) {
843         log_module(MAIN_LOG, LOG_ERROR, "modcmd_privmsg got privmsg for unhandled service %s, unregistering.", bot->nick);
844         reg_privmsg_func(bot, NULL);
845         return;
846     }
847
848     if (text[0] == '\x01') {
849         char *term, response[MAXLEN];
850
851         text++; /* Skip leading ^A. */
852         /* Chop off final ^A. */
853         term = strchr(text, '\x01');
854         if (!term)
855             return;
856         *term = '\0';
857         /* Parse out leading text. */
858         term = strchr(text, ' ');
859         if (term) {
860             *term++ = '\0';
861             if (!*term)
862                 term = NULL;
863         }
864         /* No dict lookup since these are so few. */
865         if (!irccasecmp(text, "CLIENTINFO")) {
866             /* Use \001 instead of \x01 because apparently \x01C is
867              * interpreted as ASCII FS (\034, decimal 28, hex 1C).
868              */
869             irc_notice_user(bot, user, "\001CLIENTINFO CLIENTINFO PING TIME USERINFO VERSION\x01");
870         } else if (!irccasecmp(text, "PING")) {
871             if (term) {
872                 snprintf(response, sizeof(response), "\x01PING %s\x01", term);
873                 irc_notice_user(bot, user, response);
874             } else {
875                 irc_notice_user(bot,user, "\x01PING\x01");
876             }
877         } else if (!irccasecmp(text, "TIME")) {
878             time_t feh;
879             feh = now;
880             strftime(response, sizeof(response), "\x01TIME %a %b %d %H:%M:%S %Y\x01", localtime(&feh));
881             irc_notice_user(bot, user, response);
882         } else if (!irccasecmp(text, "USERINFO")) {
883             snprintf(response, sizeof(response), "\x01USERINFO %s\x01", bot->info);
884             irc_notice_user(bot, user, response);
885         } else if (!irccasecmp(text, "VERSION")) {
886             /* This function provides copyright management information
887              * to end users of srvx. You should not alter, disable or
888              * remove this command or its accessibility to normal IRC
889              * users, except to add copyright information pertaining
890              * to changes you make to srvx.
891              */
892             snprintf(response, sizeof(response), "\x01VERSION %s (%s) %s\x01", PACKAGE_STRING, CODENAME, git_version);
893             irc_notice_user(bot, user, response);
894         }
895         return;
896     }
897
898     if (service->msg_hook && service->msg_hook(user, bot, text, server_qualified))
899         return;
900     svccmd_invoke(user, service, NULL, text, server_qualified);
901 }
902
903 void
904 modcmd_chanmsg(struct userNode *user, struct chanNode *chan, const char *text, struct userNode *bot, unsigned int is_notice) {
905     struct service *service;
906     if (!(service = dict_find(services, bot->nick, NULL)))
907         return;
908     svccmd_invoke(user, service, chan, text, 0);
909     (void)is_notice;
910 }
911
912 struct service *
913 service_register(struct userNode *bot) {
914     struct service *service;
915     if ((service = dict_find(services, bot->nick, NULL)))
916         return service;
917     service = calloc(1, sizeof(*service));
918     module_list_init(&service->modules);
919     service->commands = dict_new();
920     service->bot = bot;
921     dict_set_free_data(service->commands, free_service_command);
922     dict_insert(services, service->bot->nick, service);
923     reg_privmsg_func(bot, modcmd_privmsg);
924     return service;
925 }
926
927 struct service *
928 service_find(const char *name) {
929     return dict_find(services, name, NULL);
930 }
931
932 static void
933 svccmd_insert(struct service *service, char *name, struct svccmd *svccmd, struct modcmd *modcmd) {
934     unsigned int ii;
935     svccmd->parent = service;
936     svccmd->name = name;
937     svccmd->command = modcmd;
938     svccmd->command->bind_count++;
939     dict_insert(service->commands, svccmd->name, svccmd);
940     for (ii=0; ii<service->modules.used; ++ii) {
941         if (service->modules.list[ii] == svccmd->command->parent) break;
942     }
943     if (ii == service->modules.used) {
944         module_list_append(&service->modules, svccmd->command->parent);
945     }
946 }
947
948 struct svccmd *
949 service_bind_modcmd(struct service *service, struct modcmd *cmd, const char *name) {
950     struct svccmd *svccmd;
951     if ((svccmd = dict_find(service->commands, name, NULL))) {
952         if (svccmd->command == cmd) return svccmd;
953         log_module(MAIN_LOG, LOG_ERROR, "Tried to bind command %s.%s into service %s as %s, but already bound (as %s.%s).", cmd->parent->name, cmd->name, service->bot->nick, name, svccmd->command->parent->name, svccmd->command->name);
954         return NULL;
955     }
956     svccmd = calloc(1, sizeof(*svccmd));
957     svccmd_insert(service, strdup(name), svccmd, cmd);
958     svccmd_copy_rules(svccmd, cmd->defaults);
959     return svccmd;
960 }
961
962 static unsigned int
963 service_bind_module(struct service *service, struct module *module) {
964     dict_iterator_t it;
965     struct modcmd *modcmd;
966     unsigned int count;
967
968     count = 0;
969     for (it = dict_first(module->commands); it; it = iter_next(it)) {
970         modcmd = iter_data(it);
971         if (!((modcmd->flags | modcmd->defaults->flags) & MODCMD_NO_DEFAULT_BIND))
972             if (service_bind_modcmd(service, modcmd, iter_key(it)))
973                 count++;
974     }
975     return count;
976 }
977
978 /* This MUST return argc if the alias expansion code knows how to deal
979  * with every argument in argv; otherwise, it MUST return the index of
980  * an argument that the expansion code does not know how to deal with.
981  */
982 static unsigned int
983 check_alias_args(char *argv[], unsigned int argc) {
984     unsigned int arg;
985
986     for (arg=0; arg<argc; ++arg) {
987         if (argv[arg][0] != '$') {
988             continue;
989         } else if (argv[arg][1] == '$') {
990             continue;
991         } else if (isdigit(argv[arg][1])) {
992             char *end_num;
993             unsigned long arg;
994
995             arg = strtoul(argv[arg]+1, &end_num, 10);
996             switch (end_num[0]) {
997             case 0:
998                 continue;
999             case '-':
1000                 if (end_num[1] == 0)
1001                     continue;
1002                 else if (isdigit(end_num[1]))
1003                     continue;
1004                 /* else fall through to default case */
1005             default:
1006                 return arg;
1007             }
1008         } else
1009             return arg;
1010     }
1011     return arg;
1012 }
1013
1014 static unsigned int
1015 collapse_cmdname(char *argv[], unsigned int argc, char *dest) {
1016     unsigned int ii, pos, arg;
1017     if (!argc) {
1018         dest[0] = 0;
1019         return 0;
1020     }
1021     for (ii=pos=0, arg=0; argv[arg][ii]; ) {
1022         if (argv[arg][ii] == '\\') {
1023             if (argv[arg][ii+1]) {
1024                 /* escaping a real character just puts it in literally */
1025                 dest[pos++] = argv[arg][++ii];
1026             } else if ((arg+1) == argc) {
1027                 /* we ran to the end of the argument list; abort */
1028                 break;
1029             } else {
1030                 /* escape at end of a word is a space */
1031                 dest[pos++] = ' ';
1032                 ii = 0;
1033                 arg++;
1034             }
1035         } else {
1036             /* normal characters don't need escapes */
1037             dest[pos++] = argv[arg][ii++];
1038         }
1039     }
1040     dest[pos] = 0;
1041     return arg + 1;
1042 }
1043
1044 static MODCMD_FUNC(cmd_bind) {
1045     struct service *service;
1046     struct svccmd *template, *newcmd;
1047     char *svcname, *dot;
1048     char newname[MAXLEN], cmdname[MAXLEN];
1049     unsigned int arg, diff;
1050
1051     assert(argc > 3);
1052     svcname = argv[1];
1053     arg = collapse_cmdname(argv+2, argc-2, newname) + 2;
1054     if (!arg) {
1055         reply("MSG_MISSING_PARAMS", cmd->name);
1056         return 0;
1057     }
1058     diff = collapse_cmdname(argv+arg, argc-arg, cmdname);
1059     if (!diff) {
1060         reply("MSG_MISSING_PARAMS", cmd->name);
1061         return 0;
1062     }
1063     arg += diff;
1064
1065     if (!(service = service_find(svcname))) {
1066         reply("MCMSG_UNKNOWN_SERVICE", svcname);
1067         return 0;
1068     }
1069
1070     if ((newcmd = dict_find(service->commands, newname, NULL))) {
1071         reply("MCMSG_ALREADY_BOUND", service->bot->nick, newname);
1072         return 0;
1073     }
1074
1075     if ((dot = strchr(cmdname, '.')) && (dot[1] == '*') && (dot[2] == 0)) {
1076         unsigned int count;
1077         struct module *module;
1078         *dot = 0;
1079         module = module_find((cmdname[0] == '*') ? cmdname+1 : cmdname);
1080         if (!module) {
1081             reply("MSG_MODULE_UNKNOWN", cmdname);
1082             return 0;
1083         }
1084         count = service_bind_module(service, module);
1085         reply("MCMSG_MODULE_BOUND", count, module->name, service->bot->nick);
1086         return count != 0;
1087     }
1088     newcmd = calloc(1, sizeof(*newcmd));
1089     newcmd->name = strdup(newname);
1090     newcmd->parent = service;
1091     if (!(template = svccmd_resolve_name(newcmd, cmdname))) {
1092         reply("MCMSG_UNKNOWN_COMMAND_2", cmdname, service->bot->nick);
1093         free(newcmd->name);
1094         free(newcmd);
1095         return 0;
1096     }
1097     if (template->alias.used) {
1098         reply("MCMSG_CANNOT_DOUBLE_ALIAS");
1099         free(newcmd->name);
1100         free(newcmd);
1101         return 0;
1102     }
1103
1104     if (argc > arg) {
1105         /* a more complicated alias; fix it up */
1106         unsigned int nn;
1107
1108         arg -= diff;
1109         nn = check_alias_args(argv+arg, argc-arg);
1110         if (nn+arg < argc) {
1111             reply("MCMSG_BAD_ALIAS_ARGUMENT", argv[nn+arg]);
1112             free(newcmd->name);
1113             free(newcmd);
1114             return 0;
1115         }
1116         newcmd->alias.used = newcmd->alias.size = argc-arg;
1117         newcmd->alias.list = calloc(newcmd->alias.size, sizeof(newcmd->alias.list[0]));
1118         for (nn=0; nn<newcmd->alias.used; ++nn)
1119             newcmd->alias.list[nn] = strdup(argv[nn+arg]);
1120     }
1121
1122     svccmd_insert(service, newcmd->name, newcmd, template->command);
1123     svccmd_copy_rules(newcmd, template);
1124     reply("MCMSG_COMMAND_BOUND", newcmd->name, newcmd->parent->bot->nick);
1125     return 1;
1126 }
1127
1128 static int
1129 service_recheck_bindings(struct service *service, struct module *module) {
1130     dict_iterator_t it;
1131     struct svccmd *cmd;
1132
1133     for (it = dict_first(service->commands); it; it = iter_next(it)) {
1134         cmd = iter_data(it);
1135         if (cmd->command->parent == module) return 0;
1136     }
1137     /* No more bindings, remove it from our list. */
1138     module_list_remove(&service->modules, module);
1139     return 1;
1140 }
1141
1142 static svccmd_unbind_func_t *suf_list;
1143 unsigned int suf_size, suf_used;
1144
1145 void
1146 reg_svccmd_unbind_func(svccmd_unbind_func_t handler) {
1147     if (suf_used == suf_size) {
1148         if (suf_size) {
1149             suf_size <<= 1;
1150             suf_list = realloc(suf_list, suf_size*sizeof(svccmd_unbind_func_t));
1151         } else {
1152             suf_size = 8;
1153             suf_list = malloc(suf_size*sizeof(svccmd_unbind_func_t));
1154         }
1155     }
1156     suf_list[suf_used++] = handler;
1157 }
1158
1159 static MODCMD_FUNC(cmd_unbind) {
1160     struct service *service;
1161     struct userNode *bot;
1162     struct svccmd *bound;
1163     struct module *module;
1164     const char *svcname;
1165     unsigned int arg, ii;
1166     char cmdname[MAXLEN];
1167
1168     assert(argc > 2);
1169     svcname = argv[1];
1170     arg = collapse_cmdname(argv+2, argc-2, cmdname) + 2;
1171     if (!arg) {
1172         reply("MSG_MISSING_PARAMS", cmd->name);
1173         return 0;
1174     }
1175     if (!(service = service_find(svcname))) {
1176         reply("MCMSG_UNKNOWN_SERVICE", svcname);
1177         return 0;
1178     }
1179     if (!(bound = dict_find(service->commands, cmdname, NULL))) {
1180         reply("MCMSG_NO_COMMAND_BOUND", service->bot->nick, cmdname);
1181         return 0;
1182     }
1183     if ((bound->command->flags & MODCMD_KEEP_BOUND) && (bound->command->bind_count == 1)) {
1184         reply("MCMSG_UNBIND_PROHIBITED", bound->command->name);
1185         return 0;
1186     }
1187
1188     for (ii=0; ii<suf_used; ii++)
1189         suf_list[ii](bound);
1190     /* If this command binding is removing itself, we must take care
1191      * not to dereference it after the dict_remove.
1192      */
1193     bot = cmd->parent->bot;
1194     module = cmd->command->parent;
1195     dict_remove(service->commands, bound->name);
1196     send_message(user, bot, "MCMSG_COMMAND_UNBOUND", cmdname, service->bot->nick);
1197     if (service_recheck_bindings(service, module))
1198         send_message(user, bot, "MCMSG_HELPFILE_UNBOUND", module->name, module->name);
1199     return 1;
1200 }
1201
1202 static MODCMD_FUNC(cmd_readhelp) {
1203     const char *modname;
1204     struct module *module;
1205     struct helpfile *old_helpfile;
1206     struct timeval start, stop;
1207
1208     assert(argc > 1);
1209     modname = argv[1];
1210     if (!(module = module_find(modname))) {
1211         reply("MSG_MODULE_UNKNOWN", modname);
1212         return 0;
1213     }
1214     if (!module->helpfile_name) {
1215         reply("MCMSG_NO_HELPFILE", module->name);
1216         return 0;
1217     }
1218     old_helpfile = module->helpfile;
1219     gettimeofday(&start, NULL);
1220     module->helpfile = open_helpfile(module->helpfile_name, module->expand_help);
1221     if (!module->helpfile) {
1222         module->helpfile = old_helpfile;
1223         reply("MCMSG_HELPFILE_ERROR", module->helpfile_name);
1224         return 0;
1225     }
1226     if (old_helpfile) close_helpfile(old_helpfile);
1227     gettimeofday(&stop, NULL);
1228     stop.tv_sec -= start.tv_sec;
1229     stop.tv_usec -= start.tv_usec;
1230     if (stop.tv_usec < 0) {
1231         stop.tv_sec -= 1;
1232         stop.tv_usec += 1000000;
1233     }
1234     reply("MCMSG_HELPFILE_READ", module->name, (unsigned long)stop.tv_sec, (unsigned long)stop.tv_usec/1000);
1235     return 1;
1236 }
1237
1238 static MODCMD_FUNC(cmd_help) {
1239     const char *topic;
1240
1241     topic = (argc < 2) ? NULL : unsplit_string(argv+1, argc-1, NULL);
1242     return svccmd_send_help_2(user, cmd->parent, topic);
1243 }
1244
1245 static MODCMD_FUNC(cmd_timecmd) {
1246     struct timeval start, stop;
1247     char cmd_text[MAXLEN];
1248
1249     unsplit_string(argv+1, argc-1, cmd_text);
1250     gettimeofday(&start, NULL);
1251     svccmd_invoke(user, cmd->parent, channel, cmd_text, 0);
1252     gettimeofday(&stop, NULL);
1253     stop.tv_sec -= start.tv_sec;
1254     stop.tv_usec -= start.tv_usec;
1255     if (stop.tv_usec < 0) {
1256         stop.tv_sec -= 1;
1257         stop.tv_usec += 1000000;
1258     }
1259     reply("MCMSG_COMMAND_TIME", cmd_text, (unsigned long)stop.tv_sec, (unsigned long)stop.tv_usec);
1260     return 1;
1261 }
1262
1263 static MODCMD_FUNC(cmd_command) {
1264     struct svccmd *svccmd;
1265     const char *cmd_name, *fmt_str;
1266     unsigned int flags, shown_flags, nn, pos;
1267     char buf[MAXLEN];
1268
1269     assert(argc >= 2);
1270     cmd_name = unsplit_string(argv+1, argc-1, NULL);
1271     if (!(svccmd = svccmd_resolve_name(cmd, cmd_name))) {
1272         reply("MCMSG_UNKNOWN_COMMAND_2", cmd_name, cmd->parent->bot->nick);
1273         return 0;
1274     }
1275     pos = snprintf(buf, sizeof(buf), "%s.%s", svccmd->command->parent->name, svccmd->command->name);
1276     if (svccmd->alias.used) {
1277         buf[pos++] = ' ';
1278         unsplit_string((char**)svccmd->alias.list+1, svccmd->alias.used-1, buf+pos);
1279         reply("MCMSG_COMMAND_ALIASES", svccmd->name, buf);
1280     } else {
1281         reply("MCMSG_COMMAND_BINDING", svccmd->name, buf);
1282     }
1283     flags = svccmd->effective_flags;
1284     if ((svccmd->parent && svccmd->parent->privileged && !IsOper(user))
1285         || ((flags & MODCMD_REQUIRE_STAFF)
1286             && !IsOper(user) && !IsNetworkHelper(user) && !IsSupportHelper(user))) {
1287         reply("MCMSG_INSPECTION_REFUSED", svccmd->name);
1288         return 0;
1289     }
1290     if (flags & MODCMD_DISABLED) {
1291         reply("MSG_COMMAND_DISABLED", svccmd->name);
1292         return 1;
1293     }
1294     shown_flags = 0;
1295     if (svccmd->min_opserv_level > 0) {
1296         reply("MCMSG_NEED_OPSERV_LEVEL", svccmd->min_opserv_level);
1297         shown_flags |= MODCMD_REQUIRE_OPER | MODCMD_REQUIRE_AUTHED;
1298     }
1299     if (svccmd->min_channel_access > 0) {
1300         reply("MCMSG_NEED_CHANSERV_LEVEL", svccmd->min_channel_access);
1301         shown_flags |= MODCMD_REQUIRE_CHANUSER | MODCMD_REQUIRE_REGCHAN | MODCMD_REQUIRE_CHANNEL | MODCMD_REQUIRE_AUTHED;
1302     }
1303     if (svccmd->req_account_flags) {
1304         for (nn=pos=0; nn<32; nn++) {
1305             if (!(svccmd->req_account_flags & (1 << nn))) continue;
1306             buf[pos++] = HANDLE_FLAGS[nn];
1307         }
1308         buf[pos] = 0;
1309         reply("MCMSG_NEED_ACCOUNT_FLAGS", buf);
1310         shown_flags |= MODCMD_REQUIRE_AUTHED;
1311     }
1312     if (!flags && !shown_flags) {
1313         reply("MCMSG_NEED_NOTHING", svccmd->name);
1314         return 1;
1315     }
1316     if (flags & ~shown_flags & MODCMD_REQUIRE_HELPING) {
1317         reply("MCMSG_MUST_BE_HELPING");
1318         shown_flags |= MODCMD_REQUIRE_AUTHED | MODCMD_REQUIRE_STAFF;
1319     }
1320     if (flags & ~shown_flags & MODCMD_REQUIRE_STAFF) {
1321         switch (flags & MODCMD_REQUIRE_STAFF) {
1322         default: case MODCMD_REQUIRE_STAFF:
1323             fmt_str = "MCMSG_NEED_STAFF_ACCESS";
1324             break;
1325         case MODCMD_REQUIRE_OPER:
1326             fmt_str = "MCMSG_NEED_STAFF_OPER";
1327             break;
1328         case MODCMD_REQUIRE_NETWORK_HELPER:
1329             fmt_str = "MCMSG_NEED_STAFF_NETHELPER";
1330             break;
1331         case MODCMD_REQUIRE_OPER|MODCMD_REQUIRE_NETWORK_HELPER:
1332             fmt_str = "MCMSG_NEED_STAFF_NETHELPER_OR_OPER";
1333             break;
1334         case MODCMD_REQUIRE_SUPPORT_HELPER:
1335             fmt_str = "MCMSG_NEED_STAFF_SHELPER";
1336             break;
1337         case MODCMD_REQUIRE_OPER|MODCMD_REQUIRE_SUPPORT_HELPER:
1338             fmt_str = "MCMSG_NEED_STAFF_SHELPER_OR_OPER";
1339             break;
1340         case MODCMD_REQUIRE_SUPPORT_HELPER|MODCMD_REQUIRE_NETWORK_HELPER:
1341             fmt_str = "MCMSG_NEED_STAFF_HELPER";
1342             break;
1343         }
1344         reply(fmt_str);
1345         shown_flags |= MODCMD_REQUIRE_AUTHED | MODCMD_REQUIRE_STAFF;
1346     }
1347     if (flags & ~shown_flags & MODCMD_REQUIRE_JOINABLE) {
1348         reply("MCMSG_NEED_JOINABLE");
1349         shown_flags |= MODCMD_REQUIRE_CHANUSER;
1350     }
1351     if (flags & ~shown_flags & MODCMD_REQUIRE_CHANUSER) {
1352         if (flags & ~shown_flags & MODCMD_IGNORE_CSUSPEND)
1353             reply("MCMSG_NEED_CHANUSER_CSUSPENDABLE");
1354         else
1355             reply("MCMSG_NEED_CHANUSER");
1356         shown_flags |= MODCMD_IGNORE_CSUSPEND | MODCMD_REQUIRE_REGCHAN | MODCMD_REQUIRE_CHANNEL | MODCMD_REQUIRE_AUTHED;
1357     }
1358     if (flags & ~shown_flags & MODCMD_REQUIRE_REGCHAN) {
1359         reply("MCMSG_NEED_REGCHAN");
1360         shown_flags |= MODCMD_REQUIRE_CHANNEL;
1361     }
1362     if (flags & ~shown_flags & MODCMD_REQUIRE_CHANNEL)
1363         reply("MCMSG_NEED_CHANNEL");
1364     if (flags & ~shown_flags & MODCMD_REQUIRE_AUTHED)
1365         reply("MCMSG_NEED_AUTHED");
1366     if (flags & ~shown_flags & MODCMD_TOY)
1367         reply("MCMSG_IS_TOY", svccmd->name);
1368     if (flags & ~shown_flags & MODCMD_REQUIRE_QUALIFIED) {
1369         const char *botnick = svccmd->parent ? svccmd->parent->bot->nick : "SomeBot";
1370         reply("MCMSG_MUST_QUALIFY", botnick, svccmd->name, botnick);
1371     }
1372     reply("MCMSG_END_REQUIREMENTS", svccmd->name);
1373     return 1;
1374 }
1375
1376 static void
1377 modcmd_describe_command(struct userNode *user, struct svccmd *cmd, struct svccmd *target) {
1378     char buf1[MAXLEN], buf2[MAXLEN];
1379     unsigned int ii, len, buf1_used, buf2_used;
1380
1381     if (target->alias.used) {
1382         unsplit_string((char**)target->alias.list, target->alias.used, buf1);
1383         reply("MCMSG_COMMAND_ALIASES", target->name, buf1);
1384     } else {
1385         snprintf(buf1, sizeof(buf1), "%s.%s", target->command->parent->name, target->command->name);
1386         reply("MCMSG_COMMAND_BINDING", target->name, buf1);
1387     }
1388     for (ii = buf1_used = buf2_used = 0; flags[ii].name; ++ii) {
1389         if (target->flags & flags[ii].flag) {
1390             if (buf1_used)
1391                 buf1[buf1_used++] = ',';
1392             len = strlen(flags[ii].name);
1393             memcpy(buf1 + buf1_used, flags[ii].name, len);
1394             buf1_used += len;
1395         } else if (target->effective_flags & flags[ii].flag) {
1396             if (buf2_used)
1397                 buf2[buf2_used++] = ',';
1398             len = strlen(flags[ii].name);
1399             memcpy(buf2 + buf2_used, flags[ii].name, len);
1400             buf2_used += len;
1401         }
1402     }
1403     if (buf1_used)
1404         buf1[buf1_used] = '\0';
1405     else
1406         strcpy(buf1, user_find_message(user, "MSG_NONE"));
1407     if (buf2_used)
1408         buf2[buf2_used] = '\0';
1409     else
1410         strcpy(buf2, user_find_message(user, "MSG_NONE"));
1411     reply("MCMSG_COMMAND_FLAGS", buf1, buf2);
1412     for (ii = buf1_used = buf2_used = 0; handle_flags[ii]; ++ii) {
1413         if (target->req_account_flags & (1 << ii))
1414             buf1[buf1_used++] = handle_flags[ii];
1415         else if (target->deny_account_flags & (1 << ii))
1416             buf2[buf2_used++] = handle_flags[ii];
1417     }
1418     buf1[buf1_used] = buf2[buf2_used] = '\0';
1419     reply("MCMSG_COMMAND_ACCOUNT_FLAGS", buf1, buf2);
1420     reply("MCMSG_COMMAND_ACCESS_LEVEL", target->min_channel_access, target->min_opserv_level);
1421     reply("MCMSG_COMMAND_USES", target->name, target->uses);
1422 }
1423
1424 static MODCMD_FUNC(cmd_modcmd) {
1425     struct svccmd *svccmd;
1426     unsigned int arg, changed;
1427     char cmdname[MAXLEN];
1428
1429     assert(argc >= 2);
1430     arg = collapse_cmdname(argv+1, argc-1, cmdname) + 1;
1431     if (!arg) {
1432         reply("MSG_MISSING_PARAMS", cmd->name);
1433         return 0;
1434     }
1435     if (!(svccmd = svccmd_resolve_name(cmd, cmdname))) {
1436         reply("MCMSG_UNKNOWN_COMMAND_2", cmdname, cmd->parent->bot->nick);
1437         return 0;
1438     }
1439     for (changed = 0; arg+1 < argc; arg += 2) {
1440         if (svccmd_configure(svccmd, user, cmd->parent->bot, argv[arg], argv[arg+1])) {
1441             reply("MCMSG_COMMAND_MODIFIED", argv[arg], svccmd->name);
1442             changed = 1;
1443         }
1444     }
1445     if (changed)
1446         modcmd_set_effective_flags(svccmd);
1447     modcmd_describe_command(user, cmd, svccmd);
1448     return changed;
1449 }
1450
1451 static MODCMD_FUNC(cmd_god) {
1452     int helping;
1453
1454     if (argc > 1) {
1455         if (enabled_string(argv[1])) {
1456             if (HANDLE_FLAGGED(user->handle_info, HELPING)) {
1457                 reply("MCMSG_ALREADY_HELPING");
1458                 return 0;
1459             }
1460             helping = 1;
1461         } else if (disabled_string(argv[1])) {
1462             if (!HANDLE_FLAGGED(user->handle_info, HELPING)) {
1463                 reply("MCMSG_ALREADY_NOT_HELPING");
1464                 return 0;
1465             }
1466             helping = 0;
1467         } else {
1468             reply("MSG_INVALID_BINARY", argv[1]);
1469             return 0;
1470         }
1471     } else {
1472         helping = !IsHelping(user);
1473     }
1474
1475     if (helping) {
1476         HANDLE_SET_FLAG(user->handle_info, HELPING);
1477         reply("MCMSG_NOW_HELPING");
1478     } else {
1479         HANDLE_CLEAR_FLAG(user->handle_info, HELPING);
1480         reply("MCMSG_NOW_NOT_HELPING");
1481     }
1482
1483     return 1;
1484 }
1485
1486 static MODCMD_FUNC(cmd_joiner) {
1487     char cmdname[MAXLEN];
1488
1489     if (argc < 2) {
1490         int len = sprintf(cmdname, "%s ", cmd->name);
1491         dict_iterator_t it;
1492         struct string_buffer sbuf;
1493
1494         string_buffer_init(&sbuf);
1495         for (it = dict_first(cmd->parent->commands); it; it = iter_next(it)) {
1496             if (!ircncasecmp(iter_key(it), cmdname, len)) {
1497                 if (sbuf.used) string_buffer_append_string(&sbuf, ", ");
1498                 string_buffer_append_string(&sbuf, iter_key(it));
1499             }
1500         }
1501         if (!sbuf.used) string_buffer_append(&sbuf, 0);
1502         reply("MCMSG_JOINER_CHOICES", cmd->name, sbuf.list);
1503         string_buffer_clean(&sbuf);
1504         return 1;
1505     }
1506     sprintf(cmdname, "%s %s", cmd->name, argv[1]);
1507     argv[1] = cmdname;
1508     svccmd_invoke_argv(user, cmd->parent, channel, argc-1, argv+1, 0);
1509     return 0; /* never try to log this; the recursive one logs it */
1510 }
1511
1512 static MODCMD_FUNC(cmd_stats_modules) {
1513     struct helpfile_table tbl;
1514     dict_iterator_t it;
1515     unsigned int ii;
1516     struct module *mod;
1517     struct modcmd *modcmd;
1518
1519     if (argc < 2) {
1520         tbl.length = dict_size(modules) + 1;
1521         tbl.width = 3;
1522         tbl.flags = TABLE_PAD_LEFT;
1523         tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
1524         tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1525         tbl.contents[0][0] = "Module";
1526         tbl.contents[0][1] = "Commands";
1527         tbl.contents[0][2] = "Helpfile";
1528         for (ii=1, it=dict_first(modules); it; it=iter_next(it), ii++) {
1529             mod = iter_data(it);
1530             tbl.contents[ii] = calloc(tbl.width, sizeof(tbl.contents[ii][0]));
1531             tbl.contents[ii][0] = mod->name;
1532             tbl.contents[ii][1] = strtab(dict_size(mod->commands));
1533             tbl.contents[ii][2] = mod->helpfile_name ? mod->helpfile_name : "(none)";
1534         }
1535     } else if (!(mod = dict_find(modules, argv[1], NULL))) {
1536         reply("MCMSG_UNKNOWN_MODULE", argv[1]);
1537         return 0;
1538     } else {
1539         reply("MCMSG_MODULE_INFO", mod->name);
1540         tbl.length = dict_size(mod->commands) + 1;
1541         tbl.width = 3;
1542         tbl.flags = TABLE_PAD_LEFT;
1543         tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
1544         tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1545         tbl.contents[0][0] = "Command";
1546         tbl.contents[0][1] = "Min. Args";
1547         tbl.contents[0][2] = "Bind Count";
1548         for (ii=1, it=dict_first(mod->commands); it; it=iter_next(it), ii++) {
1549             modcmd = iter_data(it);
1550             tbl.contents[ii] = calloc(tbl.width, sizeof(tbl.contents[ii][0]));
1551             tbl.contents[ii][0] = modcmd->name;
1552             tbl.contents[ii][1] = strtab(modcmd->min_argc);
1553             tbl.contents[ii][2] = strtab(modcmd->bind_count);
1554         }
1555     }
1556     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1557     return 0;
1558 }
1559
1560 static MODCMD_FUNC(cmd_stats_services) {
1561     struct helpfile_table tbl;
1562     dict_iterator_t it;
1563     unsigned int ii;
1564     struct service *service;
1565     struct svccmd *svccmd;
1566     char *extra;
1567
1568     if (argc < 2) {
1569         tbl.length = dict_size(services) + 1;
1570         tbl.width = 4;
1571         tbl.flags = TABLE_PAD_LEFT;
1572         tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
1573         tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1574         tbl.contents[0][0] = "Service";
1575         tbl.contents[0][1] = "Commands";
1576         tbl.contents[0][2] = "Priv'd?";
1577         tbl.contents[0][3] = "Trigger";
1578         extra = calloc(2, tbl.length);
1579         for (ii=1, it=dict_first(services); it; it=iter_next(it), ii++) {
1580             service = iter_data(it);
1581             tbl.contents[ii] = calloc(tbl.width, sizeof(tbl.contents[ii][0]));
1582             tbl.contents[ii][0] = service->bot->nick;
1583             tbl.contents[ii][1] = strtab(dict_size(service->commands));
1584             tbl.contents[ii][2] = service->privileged ? "yes" : "no";
1585             extra[ii*2] = service->trigger;
1586             tbl.contents[ii][3] = extra+ii*2;
1587         }
1588         table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1589         free(extra);
1590         return 0;
1591     } else if (!(service = dict_find(services, argv[1], NULL))) {
1592         reply("MCMSG_UNKNOWN_SERVICE", argv[1]);
1593         return 0;
1594     } else {
1595         tbl.length = dict_size(service->commands) + 1;
1596         tbl.width = 5;
1597         tbl.flags = TABLE_PAD_LEFT | TABLE_NO_FREE;
1598         tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
1599         tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1600         tbl.contents[0][0] = "Command";
1601         tbl.contents[0][1] = "Module";
1602         tbl.contents[0][2] = "ModCmd";
1603         tbl.contents[0][3] = "Alias?";
1604         tbl.contents[0][4] = strdup("Uses");
1605         for (ii=1, it=dict_first(service->commands); it; it=iter_next(it), ii++) {
1606             svccmd = iter_data(it);
1607             tbl.contents[ii] = calloc(tbl.width, sizeof(tbl.contents[ii][0]));
1608             tbl.contents[ii][0] = svccmd->name;
1609             tbl.contents[ii][1] = svccmd->command->parent->name;
1610             tbl.contents[ii][2] = svccmd->command->name;
1611             tbl.contents[ii][3] = svccmd->alias.used ? "yes" : "no";
1612             tbl.contents[ii][4] = extra = malloc(12);
1613             sprintf(extra, "%u", svccmd->uses);
1614         }
1615         reply("MCMSG_SERVICE_INFO", service->bot->nick);
1616         table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1617         for (ii=0; ii<tbl.length; ii++) {
1618             free((char*)tbl.contents[ii][4]);
1619             free(tbl.contents[ii]);
1620         }
1621         free(tbl.contents);
1622         return 0;
1623     }
1624 }
1625
1626 static MODCMD_FUNC(cmd_showcommands) {
1627     struct svccmd_list commands;
1628     struct helpfile_table tbl;
1629     struct svccmd *svccmd;
1630     dict_iterator_t it;
1631     unsigned int ii, ignore_flags = 0;
1632     unsigned int max_opserv_level = 1000;
1633     unsigned short max_chanserv_level = 500;
1634     char show_opserv_level = 0, show_channel_access = 0;
1635
1636     /* Check to see what the max access they want to see is. */
1637     for (ii=1; ii<argc; ++ii) {
1638         if (isdigit(argv[ii][0]))
1639             max_opserv_level = atoi(argv[ii]);
1640         else
1641             max_chanserv_level = user_level_from_name(argv[ii], UL_OWNER);
1642     }
1643
1644     /* Find the matching commands. */
1645     svccmd_list_init(&commands);
1646     if (cmd->parent->privileged)
1647         ignore_flags = MODCMD_REQUIRE_OPER;
1648     for (it = dict_first(cmd->parent->commands); it; it = iter_next(it)) {
1649         svccmd = iter_data(it);
1650         if (strchr(svccmd->name, ' '))
1651             continue;
1652         if (!svccmd_can_invoke(user, svccmd->parent->bot, svccmd, channel, SVCCMD_QUALIFIED))
1653             continue;
1654         if (svccmd->min_opserv_level > max_opserv_level)
1655             continue;
1656         if (svccmd->min_channel_access > max_chanserv_level)
1657             continue;
1658         if (svccmd->min_opserv_level > 0)
1659             show_opserv_level = 1;
1660         if (svccmd->min_channel_access > 0)
1661             show_channel_access = 1;
1662         if (svccmd->effective_flags
1663             & (MODCMD_REQUIRE_STAFF|MODCMD_REQUIRE_HELPING)
1664             & ~ignore_flags) {
1665             show_channel_access = 1;
1666         }
1667         svccmd_list_append(&commands, svccmd);
1668     }
1669
1670     /* Build the table. */
1671     tbl.length = commands.used + 1;
1672     tbl.width = 1 + show_opserv_level + show_channel_access;
1673     tbl.flags = TABLE_REPEAT_ROWS;
1674     tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
1675     tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1676     tbl.contents[0][ii = 0] = "Command";
1677     if (show_opserv_level)
1678         tbl.contents[0][++ii] = "OpServ Level";
1679     if (show_channel_access)
1680         tbl.contents[0][++ii] = "ChanServ Access";
1681     for (ii=0; ii<commands.used; ++ii) {
1682         svccmd = commands.list[ii];
1683         tbl.contents[ii+1] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
1684         tbl.contents[ii+1][0] = svccmd->name;
1685         if (show_opserv_level)
1686             tbl.contents[ii+1][1] = strtab(svccmd->min_opserv_level);
1687         if (show_channel_access) {
1688             const char *access;
1689             int flags = svccmd->effective_flags;
1690             if (flags & MODCMD_REQUIRE_HELPING)
1691                 access = "helping";
1692             else if (flags & MODCMD_REQUIRE_STAFF) {
1693                 if (flags & MODCMD_REQUIRE_OPER)
1694                     access = "oper";
1695                 else if (flags & MODCMD_REQUIRE_NETWORK_HELPER)
1696                     access = "net.helper";
1697                 else
1698                     access = "staff";
1699             } else
1700                 access = strtab(svccmd->min_channel_access);
1701             tbl.contents[ii+1][1+show_opserv_level] = access;
1702         }
1703     }
1704     svccmd_list_clean(&commands);
1705     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1706     return 0;
1707 }
1708
1709 static MODCMD_FUNC(cmd_helpfiles) {
1710     struct service *service;
1711     unsigned int ii;
1712
1713     if (!(service = dict_find(services, argv[1], NULL))) {
1714         reply("MCMSG_UNKNOWN_SERVICE", argv[1]);
1715         return 0;
1716     }
1717
1718     if (argc < 3) {
1719         for (ii=0; ii<service->modules.used; ++ii)
1720             reply("MCMSG_HELPFILE_SEQUENCE", ii+1, service->modules.list[ii]->name);
1721         return 0;
1722     }
1723
1724     service->modules.used = 0;
1725     for (ii=0; ii<argc-2; ii++) {
1726         struct module *module = dict_find(modules, argv[ii+2], NULL);
1727         if (!module) {
1728             reply("MCMSG_UNKNOWN_MODULE", argv[ii+2]);
1729             continue;
1730         }
1731         module_list_append(&service->modules, module);
1732     }
1733     reply("MCMSG_HELPFILE_SEQUENCE_SET", service->bot->nick);
1734     return 1;
1735 }
1736
1737 static MODCMD_FUNC(cmd_service_add) {
1738     const char *nick, *hostname, *desc;
1739     struct userNode *bot;
1740
1741     nick = argv[1];
1742     if (!is_valid_nick(nick)) {
1743         reply("MCMSG_BAD_SERVICE_NICK", nick);
1744         return 0;
1745     }
1746     hostname = argv[2];
1747     desc = unsplit_string(argv+3, argc-3, NULL);
1748     bot = GetUserH(nick);
1749     if (bot && IsService(bot)) {
1750         reply("MCMSG_ALREADY_SERVICE", bot->nick);
1751         return 0;
1752     }
1753     bot = AddLocalUser(nick, nick, hostname, desc, NULL);
1754     service_register(bot);
1755     reply("MCMSG_NEW_SERVICE", bot->nick);
1756     return 1;
1757 }
1758
1759 static MODCMD_FUNC(cmd_service_rename) {
1760     struct service *service;
1761
1762     if (!(service = service_find(argv[1]))) {
1763         reply("MCMSG_UNKNOWN_SERVICE", argv[1]);
1764         return 0;
1765     }
1766     NickChange(service->bot, argv[2], 0);
1767     reply("MCMSG_SERVICE_RENAMED", service->bot->nick);
1768     return 1;
1769 }
1770
1771 static MODCMD_FUNC(cmd_service_trigger) {
1772     struct userNode *bogon;
1773     struct service *service;
1774
1775     if (!(service = service_find(argv[1]))) {
1776         reply("MCMSG_UNKNOWN_SERVICE", argv[1]);
1777         return 0;
1778     }
1779     if (argc < 3) {
1780         if (service->trigger)
1781             reply("MCMSG_CURRENT_TRIGGER", service->bot->nick, service->trigger);
1782         else
1783             reply("MCMSG_NO_TRIGGER", service->bot->nick);
1784         return 1;
1785     }
1786     if (service->trigger)
1787         reg_chanmsg_func(service->trigger, NULL, NULL);
1788     if (!irccasecmp(argv[2], "none") || !irccasecmp(argv[2], "remove")) {
1789         service->trigger = 0;
1790         reply("MCMSG_REMOVED_TRIGGER", service->bot->nick);
1791     } else if ((bogon = get_chanmsg_bot(argv[2][0]))) {
1792         reply("MCMSG_DUPLICATE_TRIGGER", bogon->nick, argv[2][0]);
1793         return 1;
1794     } else {
1795         service->trigger = argv[2][0];
1796         reg_chanmsg_func(service->trigger, service->bot, modcmd_chanmsg);
1797         reply("MCMSG_NEW_TRIGGER", service->bot->nick, service->trigger);
1798     }
1799     return 1;
1800 }
1801
1802 static MODCMD_FUNC(cmd_service_privileged) {
1803     struct service *service;
1804     const char *newval;
1805
1806     if (!(service = service_find(argv[1]))) {
1807         reply("MCMSG_UNKNOWN_SERVICE", argv[1]);
1808         return 0;
1809     }
1810     if (argc >= 3)
1811         service->privileged = true_string(argv[2]) || enabled_string(argv[2]);
1812     newval = user_find_message(user, service->privileged ? "MSG_ON" : "MSG_OFF");
1813     reply("MCMSG_SERVICE_PRIVILEGED", service->bot->nick, newval);
1814     return 1;
1815 }
1816
1817 static MODCMD_FUNC(cmd_service_remove) {
1818     char *name, *reason;
1819     struct service *service;
1820
1821     name = argv[1];
1822     if (argc > 2)
1823         reason = unsplit_string(argv+2, argc-2, NULL);
1824     else
1825         reason = "Removing bot";
1826     if (!(service = service_find(name))) {
1827         reply("MCMSG_UNKNOWN_SERVICE", name);
1828         return 0;
1829     }
1830     DelUser(service->bot, NULL, 1, reason);
1831     reply("MCMSG_SERVICE_REMOVED", name);
1832     dict_remove(services, name);
1833     return 1;
1834 }
1835
1836 static MODCMD_FUNC(cmd_dump_messages) {
1837     const char *fname = "strings.db";
1838     struct saxdb_context *ctx;
1839     dict_iterator_t it;
1840     FILE *pf;
1841     int res;
1842
1843     if (!(pf = fopen(fname, "w"))) {
1844         reply("MCMSG_FILE_NOT_OPENED", fname);
1845         return 0;
1846     }
1847     if (!(ctx = saxdb_open_context(pf))) {
1848         reply("MSG_INTERNAL_FAILURE");
1849         return 0;
1850     }
1851     if ((res = setjmp(*saxdb_jmp_buf(ctx))) != 0) {
1852         saxdb_close_context(ctx, 1);
1853         reply("MCMSG_MESSAGE_DUMP_FAILED", strerror(res));
1854         return 0;
1855     } else {
1856         for (it = dict_first(lang_C->messages); it; it = iter_next(it))
1857             saxdb_write_string(ctx, iter_key(it), iter_data(it));
1858         saxdb_close_context(ctx, 1);
1859         reply("MCMSG_MESSAGES_DUMPED", fname);
1860         return 1;
1861     }
1862 }
1863
1864 static MODCMD_FUNC(cmd_version) {
1865     /* This function provides copyright management information to end
1866      * users of srvx. You should not alter, disable or remove this
1867      * command or its accessibility to normal IRC users, except to add
1868      * copyright information pertaining to changes you make to srvx.
1869      */
1870     send_message_type(4, user, cmd->parent->bot, "$b"PACKAGE_STRING"$b ("CODENAME"), Built: "__DATE__", "__TIME__".  Copyright 2000-2008 srvx Development Team.");
1871     if (argc > 1)
1872         send_message_type(4, user, cmd->parent->bot, "%s", git_version);
1873     else
1874         send_message_type(12, user, cmd->parent->bot, "The srvx Development Team includes Paul Chang, Adrian Dewhurst, Miles Peterson, Michael Poole and others.\nThe srvx Development Team can be reached at http://sf.net/projects/srvx/ or in #srvx on irc.gamesurge.net.");
1875     return 1;
1876 }
1877
1878 static MODCMD_FUNC(cmd_tell) {
1879     struct userNode *target;
1880     char *msg;
1881
1882     target = GetUserH(argv[1]);
1883     msg = unsplit_string(argv + 2, argc - 2, NULL);
1884     if (!target) {
1885         reply("MSG_NOT_TARGET_NAME");
1886         return 0;
1887     }
1888     send_message_type(MSG_TYPE_NOXLATE, target, cmd->parent->bot, "%s", msg);
1889     return 1;
1890 }
1891
1892 void
1893 modcmd_nick_change(struct userNode *user, const char *old_nick) {
1894     struct service *svc;
1895     if (!(svc = dict_find(services, old_nick, NULL)))
1896         return;
1897     dict_remove2(services, old_nick, 1);
1898     dict_insert(services, user->nick, svc);
1899 }
1900
1901 void
1902 modcmd_cleanup(void) {
1903     dict_delete(services);
1904     dict_delete(modules);
1905     if (suf_list)
1906         free(suf_list);
1907 }
1908
1909 static void
1910 modcmd_saxdb_write_command(struct saxdb_context *ctx, struct svccmd *cmd) {
1911     char buf[MAXLEN];
1912     unsigned int nn, len, pos;
1913     struct svccmd *template = cmd->command->defaults;
1914
1915     saxdb_start_record(ctx, cmd->name, 0);
1916     sprintf(buf, "%s.%s", cmd->command->parent->name, cmd->command->name);
1917     saxdb_write_string(ctx, "command", buf);
1918     if (cmd->alias.used)
1919         saxdb_write_string_list(ctx, "aliased", &cmd->alias);
1920     if (cmd->min_opserv_level != template->min_opserv_level)
1921         saxdb_write_int(ctx, "oper_access", cmd->min_opserv_level);
1922     if (cmd->min_channel_access != template->min_channel_access)
1923         saxdb_write_int(ctx, "channel_access", cmd->min_channel_access);
1924     if (cmd->flags != template->flags) {
1925         if (cmd->flags) {
1926             for (nn=pos=0; flags[nn].name; ++nn) {
1927                 if (cmd->flags & flags[nn].flag) {
1928                     buf[pos++] = '+';
1929                     len = strlen(flags[nn].name);
1930                     memcpy(buf+pos, flags[nn].name, len);
1931                     pos += len;
1932                     buf[pos++] = ',';
1933                 }
1934             }
1935         } else {
1936             pos = 1;
1937         }
1938         buf[--pos] = 0;
1939         saxdb_write_string(ctx, "flags", buf);
1940     }
1941     if ((cmd->req_account_flags != template->req_account_flags)
1942         || (cmd->deny_account_flags != template->req_account_flags)) {
1943         pos = 0;
1944         if (cmd->req_account_flags) {
1945             buf[pos++] = '+';
1946             for (nn=0; nn<32; nn++)
1947                 if (cmd->req_account_flags & (1 << nn))
1948                     buf[pos++] = handle_flags[nn];
1949         }
1950         if (cmd->deny_account_flags) {
1951             buf[pos++] = '-';
1952             for (nn=0; nn<32; nn++)
1953                 if (cmd->deny_account_flags & (1 << nn))
1954                     buf[pos++] = handle_flags[nn];
1955         }
1956         buf[pos] = 0;
1957         saxdb_write_string(ctx, "account_flags", buf);
1958     }
1959     saxdb_end_record(ctx);
1960 }
1961
1962 static int
1963 modcmd_saxdb_write(struct saxdb_context *ctx) {
1964     struct string_list slist;
1965     dict_iterator_t it, it2;
1966     struct service *service;
1967     unsigned int ii;
1968
1969     saxdb_start_record(ctx, "bots", 1);
1970     for (it = dict_first(services); it; it = iter_next(it)) {
1971         char buff[16];
1972         service = iter_data(it);
1973         saxdb_start_record(ctx, service->bot->nick, 1);
1974         if (service->trigger) {
1975             buff[0] = service->trigger;
1976             buff[1] = '\0';
1977             saxdb_write_string(ctx, "trigger", buff);
1978         }
1979         saxdb_write_string(ctx, "description", service->bot->info);
1980         saxdb_write_string(ctx, "hostname", service->bot->hostname);
1981         if (service->privileged)
1982             saxdb_write_string(ctx, "privileged", "1");
1983         saxdb_end_record(ctx);
1984     }
1985     saxdb_end_record(ctx);
1986
1987     saxdb_start_record(ctx, "services", 1);
1988     for (it = dict_first(services); it; it = iter_next(it)) {
1989         service = iter_data(it);
1990         saxdb_start_record(ctx, service->bot->nick, 1);
1991         for (it2 = dict_first(service->commands); it2; it2 = iter_next(it2))
1992             modcmd_saxdb_write_command(ctx, iter_data(it2));
1993         saxdb_end_record(ctx);
1994     }
1995     saxdb_end_record(ctx);
1996
1997     saxdb_start_record(ctx, "helpfiles", 1);
1998     slist.size = 0;
1999     for (it = dict_first(services); it; it = iter_next(it)) {
2000         service = iter_data(it);
2001         slist.used = 0;
2002         for (ii = 0; ii < service->modules.used; ++ii)
2003             string_list_append(&slist, service->modules.list[ii]->name);
2004         saxdb_write_string_list(ctx, iter_key(it), &slist);
2005     }
2006     if (slist.list)
2007         free(slist.list);
2008     saxdb_end_record(ctx);
2009
2010     return 0;
2011 }
2012
2013 static int
2014 append_entry(const char *key, UNUSED_ARG(void *data), void *extra) {
2015     struct helpfile_expansion *exp = extra;
2016     int row = exp->value.table.length++;
2017     exp->value.table.contents[row] = calloc(1, sizeof(char*));
2018     exp->value.table.contents[row][0] = key;
2019     return 0;
2020 }
2021
2022 static struct helpfile_expansion
2023 modcmd_expand(const char *variable) {
2024     struct helpfile_expansion exp;
2025     extern struct userNode *message_source;
2026     struct service *service;
2027
2028     service = dict_find(services, message_source->nick, NULL);
2029     if (!irccasecmp(variable, "index")) {
2030         exp.type = HF_TABLE;
2031         exp.value.table.length = 1;
2032         exp.value.table.width = 1;
2033         exp.value.table.flags = TABLE_REPEAT_ROWS;
2034         exp.value.table.contents = calloc(dict_size(service->commands)+1, sizeof(char**));
2035         exp.value.table.contents[0] = calloc(1, sizeof(char*));
2036         exp.value.table.contents[0][0] = "Commands:";
2037         dict_foreach(service->commands, append_entry, &exp);
2038         return exp;
2039     } else if (!irccasecmp(variable, "languages")) {
2040         struct string_buffer sbuf;
2041         dict_iterator_t it;
2042         sbuf.used = sbuf.size = 0;
2043         sbuf.list = NULL;
2044         for (it = dict_first(languages); it; it = iter_next(it)) {
2045             string_buffer_append_string(&sbuf, iter_key(it));
2046             string_buffer_append(&sbuf, ' ');
2047         }
2048         sbuf.list[--sbuf.used] = 0;
2049         exp.type = HF_STRING;
2050         exp.value.str = sbuf.list;
2051         return exp;
2052     }
2053     exp.type = HF_STRING;
2054     exp.value.str = NULL;
2055     return exp;
2056 }
2057
2058 static void
2059 modcmd_load_bots(struct dict *db, int default_nick) {
2060     dict_iterator_t it;
2061
2062     for (it = dict_first(db); it; it = iter_next(it)) {
2063         struct record_data *rd;
2064         struct service *svc;
2065         const char *nick, *desc, *hostname;
2066
2067         rd = iter_data(it);
2068         if (rd->type != RECDB_OBJECT) {
2069             log_module(MAIN_LOG, LOG_ERROR, "Bad type for 'bots/%s' in modcmd db (expected object).", iter_key(it));
2070             continue;
2071         }
2072         nick = database_get_data(rd->d.object, "nick", RECDB_QSTRING);
2073         if (!nick) {
2074             if (default_nick)
2075                 nick = iter_key(it);
2076             else
2077                 continue;
2078         }
2079         svc = service_find(nick);
2080         desc = database_get_data(rd->d.object, "description", RECDB_QSTRING);
2081         hostname = database_get_data(rd->d.object, "hostname", RECDB_QSTRING);
2082         if (desc) {
2083             if (!svc)
2084                 svc = service_register(AddLocalUser(nick, nick, hostname, desc, NULL));
2085             else if (hostname)
2086                 strcpy(svc->bot->hostname, hostname);
2087             desc = database_get_data(rd->d.object, "trigger", RECDB_QSTRING);
2088             if (desc)
2089                 svc->trigger = desc[0];
2090             desc = database_get_data(rd->d.object, "privileged", RECDB_QSTRING);
2091             if (desc && (true_string(desc) || enabled_string(desc)))
2092                 svc->privileged = 1;
2093         }
2094     }
2095 }
2096
2097 static void
2098 modcmd_conf_read(void) {
2099     modcmd_load_bots(conf_get_data("services", RECDB_OBJECT), 0);
2100 }
2101
2102 void
2103 modcmd_init(void) {
2104     qsort(flags, ArrayLength(flags)-1, sizeof(flags[0]), flags_qsort);
2105     modules = dict_new();
2106     dict_set_free_data(modules, free_module);
2107     services = dict_new();
2108     dict_set_free_data(services, free_service);
2109     reg_nick_change_func(modcmd_nick_change);
2110     reg_exit_func(modcmd_cleanup);
2111     conf_register_reload(modcmd_conf_read);
2112
2113     modcmd_module = module_register("modcmd", MAIN_LOG, "modcmd.help", modcmd_expand);
2114     bind_command = modcmd_register(modcmd_module, "bind", cmd_bind, 4, MODCMD_KEEP_BOUND, "oper_level", "800", NULL);
2115     help_command = modcmd_register(modcmd_module, "help", cmd_help, 1, 0, "flags", "+nolog", NULL);
2116     modcmd_register(modcmd_module, "command", cmd_command, 2, 0, "flags", "+nolog", NULL);
2117     modcmd_register(modcmd_module, "modcmd", cmd_modcmd, 2, MODCMD_KEEP_BOUND, "template", "bind", NULL);
2118     modcmd_register(modcmd_module, "god", cmd_god, 0, MODCMD_REQUIRE_AUTHED, "flags", "+oper,+networkhelper", NULL);
2119     modcmd_register(modcmd_module, "readhelp", cmd_readhelp, 2, 0, "oper_level", "650", NULL);
2120     modcmd_register(modcmd_module, "timecmd", cmd_timecmd, 2, 0, "oper_level", "1", NULL);
2121     modcmd_register(modcmd_module, "unbind", cmd_unbind, 3, 0, "template", "bind", NULL);
2122     modcmd_register(modcmd_module, "joiner", cmd_joiner, 1, 0, NULL);
2123     modcmd_register(modcmd_module, "stats modules", cmd_stats_modules, 1, 0, "flags", "+oper", NULL);
2124     modcmd_register(modcmd_module, "stats services", cmd_stats_services, 1, 0, "flags", "+oper", NULL);
2125     modcmd_register(modcmd_module, "showcommands", cmd_showcommands, 1, 0, "flags", "+acceptchan", NULL);
2126     modcmd_register(modcmd_module, "helpfiles", cmd_helpfiles, 2, 0, "template", "bind", NULL);
2127     modcmd_register(modcmd_module, "service add", cmd_service_add, 4, 0, "flags", "+oper", NULL);
2128     modcmd_register(modcmd_module, "service rename", cmd_service_rename, 3, 0, "flags", "+oper", NULL);
2129     modcmd_register(modcmd_module, "service trigger", cmd_service_trigger, 2, 0, "flags", "+oper", NULL);
2130     modcmd_register(modcmd_module, "service privileged", cmd_service_privileged, 2, 0, "flags", "+oper", NULL);
2131     modcmd_register(modcmd_module, "service remove", cmd_service_remove, 2, 0, "flags", "+oper", NULL);
2132     modcmd_register(modcmd_module, "dumpmessages", cmd_dump_messages, 1, 0, "oper_level", "1000", NULL);
2133     modcmd_register(modcmd_module, "tell", cmd_tell, 3, 0, "flags", "+oper", NULL);
2134     version_command = modcmd_register(modcmd_module, "version", cmd_version, 1, 0, NULL);
2135     message_register_table(msgtab);
2136 }
2137
2138 static void
2139 modcmd_db_load_command(struct service *service, const char *cmdname, struct dict *obj) {
2140     struct svccmd *svccmd;
2141     struct module *module;
2142     struct modcmd *modcmd;
2143     struct string_list *slist;
2144     const char *str, *sep;
2145     char buf[MAXLEN];
2146
2147     str = database_get_data(obj, "command", RECDB_QSTRING);
2148     if (!str) {
2149         log_module(MAIN_LOG, LOG_ERROR, "Missing command for service %s command %s in modcmd.db", service->bot->nick, cmdname);
2150         return;
2151     }
2152     sep = strchr(str, '.');
2153     if (!sep) {
2154         log_module(MAIN_LOG, LOG_ERROR, "Invalid command %s for service %s command %s in modcmd.db", str, service->bot->nick, cmdname);
2155         return;
2156     }
2157     memcpy(buf, str, sep-str);
2158     buf[sep-str] = 0;
2159     if (!(module = module_find(buf))) {
2160         log_module(MAIN_LOG, LOG_ERROR, "Unknown module %s for service %s command %s in modcmd.db", buf, service->bot->nick, cmdname);
2161         return;
2162     }
2163     if (!(modcmd = dict_find(module->commands, sep+1, NULL))) {
2164         log_module(MAIN_LOG, LOG_ERROR, "Unknown command %s in module %s for service %s command %s", sep+1, module->name, service->bot->nick, cmdname);
2165         return;
2166     }
2167     /* Now that we know we have a command to use, fill in the basics. */
2168     svccmd = calloc(1, sizeof(*svccmd));
2169     svccmd_insert(service, strdup(cmdname), svccmd, modcmd);
2170     if ((str = database_get_data(obj, "template", RECDB_QSTRING))) {
2171         add_pending_template(svccmd, str);
2172     } else {
2173         svccmd_copy_rules(svccmd, modcmd->defaults);
2174     }
2175     if ((str = database_get_data(obj, "account_flags", RECDB_QSTRING))) {
2176         svccmd->req_account_flags = svccmd->deny_account_flags = 0;
2177         svccmd_configure(svccmd, NULL, service->bot, "account_flags", str);
2178     }
2179     if ((str = database_get_data(obj, "flags", RECDB_QSTRING))) {
2180         svccmd->flags = 0;
2181         svccmd_configure(svccmd, NULL, service->bot, "flags", str);
2182     }
2183     if ((str = database_get_data(obj, "oper_access", RECDB_QSTRING))
2184         || (str = database_get_data(obj, "opserv_level", RECDB_QSTRING))) {
2185         svccmd_configure(svccmd, NULL, service->bot, "oper_access", str);
2186     }
2187     if ((str = database_get_data(obj, "channel_access", RECDB_QSTRING))
2188         || (str = database_get_data(obj, "chanserv_level", RECDB_QSTRING))) {
2189         svccmd_configure(svccmd, NULL, service->bot, "channel_access", str);
2190     }
2191     if ((slist = database_get_data(obj, "aliased", RECDB_STRING_LIST))) {
2192         unsigned int nn;
2193         svccmd->alias.used = svccmd->alias.size = slist->used;
2194         svccmd->alias.list = calloc(svccmd->alias.size, sizeof(svccmd->alias.list[0]));
2195         for (nn=0; nn<slist->used; ++nn)
2196             svccmd->alias.list[nn] = strdup(slist->list[nn]);
2197     }
2198     modcmd_set_effective_flags(svccmd);
2199 }
2200
2201 static struct svccmd *
2202 service_make_alias(struct service *service, const char *alias, ...) {
2203     char *arg, *argv[MAXNUMPARAMS];
2204     unsigned int nn, argc;
2205     struct svccmd *svccmd, *template;
2206     va_list args;
2207
2208     va_start(args, alias);
2209     argc = 0;
2210     while (1) {
2211         arg = va_arg(args, char*);
2212         if (!arg)
2213             break;
2214         argv[argc++] = arg;
2215     }
2216     va_end(args);
2217     svccmd = calloc(1, sizeof(*svccmd));
2218     if (!(template = svccmd_resolve_name(svccmd, argv[0]))) {
2219         log_module(MAIN_LOG, LOG_ERROR, "Invalid base command %s for alias %s in service %s", argv[0], alias, service->bot->nick);
2220         free(svccmd->name);
2221         free(svccmd);
2222         return NULL;
2223     }
2224     if (argc > 1) {
2225         svccmd->alias.used = svccmd->alias.size = argc;
2226         svccmd->alias.list = calloc(svccmd->alias.size, sizeof(svccmd->alias.list[0]));
2227         for (nn=0; nn<argc; nn++)
2228             svccmd->alias.list[nn] = strdup(argv[nn]);
2229     }
2230     svccmd_insert(service, strdup(alias), svccmd, template->command);
2231     svccmd_copy_rules(svccmd, template);
2232     return svccmd;
2233 }
2234
2235 static int saxdb_present;
2236
2237 static int
2238 modcmd_saxdb_read(struct dict *db) {
2239     struct dict *db2;
2240     dict_iterator_t it, it2;
2241     struct record_data *rd, *rd2;
2242     struct service *service;
2243
2244     modcmd_load_bots(database_get_data(db, "bots", RECDB_OBJECT), 1);
2245     db2 = database_get_data(db, "services", RECDB_OBJECT);
2246     if (!db2) {
2247         log_module(MAIN_LOG, LOG_ERROR, "Missing section 'services' in modcmd db.");
2248         return 1;
2249     }
2250     for (it = dict_first(db2); it; it = iter_next(it)) {
2251         rd = iter_data(it);
2252         if (rd->type != RECDB_OBJECT) {
2253             log_module(MAIN_LOG, LOG_ERROR, "Bad type for 'services/%s' in modcmd db (expected object).", iter_key(it));
2254             continue;
2255         }
2256         if (!(service = service_find(iter_key(it)))) {
2257             log_module(MAIN_LOG, LOG_ERROR, "Unknown service '%s' listed in modcmd db.", iter_key(it));
2258             continue;
2259         }
2260         for (it2 = dict_first(rd->d.object); it2; it2 = iter_next(it2)) {
2261             rd2 = iter_data(it2);
2262             if (rd2->type != RECDB_OBJECT) {
2263                 log_module(MAIN_LOG, LOG_ERROR, "Bad type for 'services/%s/%s' in modcmd db (expected object).", iter_key(it), iter_key(it2));
2264                 continue;
2265             }
2266             modcmd_db_load_command(service, iter_key(it2), rd2->d.object);
2267         }
2268     }
2269     db2 = database_get_data(db, "helpfiles", RECDB_OBJECT);
2270     for (it = dict_first(db2); it; it = iter_next(it)) {
2271         struct module *module;
2272         struct string_list *slist;
2273         unsigned int ii;
2274
2275         rd = iter_data(it);
2276         if (rd->type != RECDB_STRING_LIST) {
2277             log_module(MAIN_LOG, LOG_ERROR, "Bad type for 'helpfiles/%s' in modcmd db (expected string list).", iter_key(it));
2278             continue;
2279         }
2280         slist = rd->d.slist;
2281         if (!(service = service_find(iter_key(it)))) {
2282             /* We probably whined about the service being missing above. */
2283             continue;
2284         }
2285         service->modules.used = 0;
2286         for (ii=0; ii<slist->used; ++ii) {
2287             if (!(module = dict_find(modules, slist->list[ii], NULL))) {
2288                 log_module(MAIN_LOG, LOG_ERROR, "Unknown module '%s' listed in modcmd 'helpfiles/%s'.", slist->list[ii], iter_key(it));
2289                 continue;
2290             }
2291             module_list_append(&service->modules, module);
2292         }
2293     }
2294     saxdb_present = 1;
2295     return 0;
2296 }
2297
2298 static void
2299 create_default_binds(void) {
2300     /* Which services should import which modules by default? */
2301     struct {
2302         const char *svcname;
2303         /* C is lame and requires a fixed size for this array.
2304          * Be sure you NULL-terminate each array and increment the
2305          * size here if you add more default modules to any
2306          * service. */
2307         const char *modnames[8];
2308     } def_binds[] = {
2309         { "ChanServ", { "ChanServ", NULL } },
2310         { "Global", { "Global", NULL } },
2311         { "NickServ", { "NickServ", NULL } },
2312         { "OpServ", { "OpServ", "modcmd", "sendmail", "saxdb", "proxycheck", NULL } },
2313         { NULL, { NULL } }
2314     };
2315     unsigned int ii, jj;
2316     char buf[128], *nick;
2317     struct service *service;
2318     struct module *module;
2319
2320     for (ii = 0; def_binds[ii].svcname; ++ii) {
2321         sprintf(buf, "services/%s/nick", def_binds[ii].svcname);
2322         if (!(nick = conf_get_data(buf, RECDB_QSTRING)))
2323             continue;
2324         if (!(service = service_find(nick)))
2325             continue;
2326         if (dict_size(service->commands) > 0)
2327             continue;
2328
2329         /* Bind the default modules for this service to it */
2330         for (jj = 0; def_binds[ii].modnames[jj]; ++jj) {
2331             if (!(module = module_find(def_binds[ii].modnames[jj])))
2332                 continue;
2333             service_bind_module(service, module);
2334         }
2335
2336         /* Bind the help and version commands to this service */
2337         service_bind_modcmd(service, help_command, help_command->name);
2338         service_bind_modcmd(service, version_command, version_command->name);
2339
2340         /* Now some silly hax.. (aliases that most people want) */
2341         if (!irccasecmp(def_binds[ii].svcname, "ChanServ")) {
2342             service_make_alias(service, "addowner", "*chanserv.adduser", "$1", "owner", NULL);
2343             service_make_alias(service, "addcoowner", "*chanserv.adduser", "$1", "coowner", NULL);
2344             service_make_alias(service, "addmaster", "*chanserv.adduser", "$1", "master", NULL);
2345             service_make_alias(service, "addop", "*chanserv.adduser", "$1", "op", NULL);
2346             service_make_alias(service, "addpeon", "*chanserv.adduser", "$1", "peon", NULL);
2347             service_make_alias(service, "delowner", "*chanserv.deluser", "owner", "$1", NULL);
2348             service_make_alias(service, "delcoowner", "*chanserv.deluser", "coowner", "$1", NULL);
2349             service_make_alias(service, "delmaster", "*chanserv.deluser", "master", "$1", NULL);
2350             service_make_alias(service, "delop", "*chanserv.deluser", "op", "$1", NULL);
2351             service_make_alias(service, "delpeon", "*chanserv.deluser", "peon", "$1", NULL);
2352             service_make_alias(service, "command", "*modcmd.command", NULL);
2353             service_make_alias(service, "god", "*modcmd.god", NULL);
2354         } else if (!irccasecmp(def_binds[ii].svcname, "OpServ")) {
2355             struct svccmd *svccmd;
2356             svccmd = service_make_alias(service, "stats", "*modcmd.joiner", NULL);
2357             svccmd->min_opserv_level = 101;
2358             svccmd = service_make_alias(service, "service", "*modcmd.joiner", NULL);
2359             svccmd->min_opserv_level = 900;
2360         }
2361     }
2362 }
2363
2364 static void
2365 import_aliases_db() {
2366     struct dict *db;
2367     dict_iterator_t it, it2;
2368     struct record_data *rd, *rd2;
2369     struct service *service;
2370     struct module *module;
2371
2372     if (!(db = parse_database("aliases.db")))
2373         return;
2374     for (it = dict_first(db); it; it = iter_next(it)) {
2375         service = service_find(iter_key(it));
2376         if (!service)
2377             continue;
2378         module = module_find(service->bot->nick);
2379         rd = iter_data(it);
2380         if (rd->type != RECDB_OBJECT)
2381             continue;
2382         for (it2 = dict_first(rd->d.object); it2; it2 = iter_next(it2)) {
2383             struct modcmd *command;
2384             rd2 = iter_data(it2);
2385             if (rd2->type != RECDB_QSTRING)
2386                 continue;
2387             command = dict_find(module->commands, rd2->d.qstring, NULL);
2388             if (!command)
2389                 continue;
2390             service_bind_modcmd(service, command, iter_key(it2));
2391         }
2392     }
2393 }
2394
2395 void
2396 modcmd_finalize(void) {
2397     dict_iterator_t it;
2398
2399     /* Check databases. */
2400     saxdb_register("modcmd", modcmd_saxdb_read, modcmd_saxdb_write);
2401     create_default_binds();
2402     if (!saxdb_present)
2403         import_aliases_db();
2404
2405     /* Register services for their triggers. */
2406     for (it = dict_first(services); it; it = iter_next(it)) {
2407         struct service *svc = iter_data(it);
2408         if (svc->trigger)
2409             reg_chanmsg_func(svc->trigger, svc->bot, modcmd_chanmsg);
2410     }
2411
2412     /* Resolve command rule-templates. */
2413     while (pending_templates) {
2414         struct pending_template *ptempl = pending_templates;
2415         struct svccmd *svccmd;
2416
2417         pending_templates = ptempl->next;
2418         /* Only overwrite the current template if we have a valid template. */
2419         if (!strcmp(ptempl->base, "*")) {
2420             /* Do nothing. */
2421         } else if ((svccmd = svccmd_resolve_name(ptempl->cmd, ptempl->base))) {
2422             svccmd_copy_rules(ptempl->cmd, svccmd);
2423         } else {
2424             assert(ptempl->cmd->parent);
2425             log_module(MAIN_LOG, LOG_ERROR, "Unable to resolve template name %s for command %s in service %s.", ptempl->base, ptempl->cmd->name, ptempl->cmd->parent->bot->nick);
2426         }
2427         free(ptempl->base);
2428         free(ptempl);
2429     }
2430 }