typo fix in alloc-srvx.c; avoid dereferencing free()'d bans
[srvx.git] / src / opserv.c
1 /* opserv.c - IRC Operator assistance service
2  * Copyright 2000-2004 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 "conf.h"
22 #include "gline.h"
23 #include "global.h"
24 #include "nickserv.h"
25 #include "modcmd.h"
26 #include "opserv.h"
27 #include "timeq.h"
28 #include "saxdb.h"
29
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
32 #endif
33 #ifdef HAVE_NETINET_IN_H
34 #include <netinet/in.h>
35 #endif
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #endif
39
40 #define OPSERV_CONF_NAME "services/opserv"
41
42 #define KEY_ALERT_CHANNEL "alert_channel"
43 #define KEY_ALERT_CHANNEL_MODES "alert_channel_modes"
44 #define KEY_DEBUG_CHANNEL "debug_channel"
45 #define KEY_DEBUG_CHANNEL_MODES "debug_channel_modes"
46 #define KEY_UNTRUSTED_MAX "untrusted_max"
47 #define KEY_PURGE_LOCK_DELAY "purge_lock_delay"
48 #define KEY_JOIN_FLOOD_MODERATE "join_flood_moderate"
49 #define KEY_JOIN_FLOOD_MODERATE_THRESH "join_flood_moderate_threshold"
50 #define KEY_NICK "nick"
51 #define KEY_JOIN_POLICER "join_policer"
52 #define KEY_NEW_USER_POLICER "new_user_policer"
53 #define KEY_REASON "reason"
54 #define KEY_RESERVES "reserves"
55 #define KEY_IDENT "username" /* for compatibility with 1.0 DBs */
56 #define KEY_HOSTNAME "hostname"
57 #define KEY_DESC "description"
58 #define KEY_BAD_WORDS "bad"
59 #define KEY_EXEMPT_CHANNELS "exempt"
60 #define KEY_SECRET_WORDS "secret"
61 #define KEY_TRUSTED_HOSTS "trusted"
62 #define KEY_OWNER "owner"
63 #define KEY_GAGS "gags"
64 #define KEY_ALERTS "alerts"
65 #define KEY_REACTION "reaction"
66 #define KEY_DISCRIM "discrim"
67 #define KEY_WARN "chanwarn"
68 #define KEY_MAX "max"
69 #define KEY_TIME "time"
70 #define KEY_MAX_CLIENTS "max_clients"
71 #define KEY_LIMIT "limit"
72 #define KEY_EXPIRES "expires"
73 #define KEY_STAFF_AUTH_CHANNEL "staff_auth_channel"
74 #define KEY_STAFF_AUTH_CHANNEL_MODES "staff_auth_channel_modes"
75 #define KEY_CLONE_GLINE_DURATION "clone_gline_duration"
76 #define KEY_BLOCK_GLINE_DURATION "block_gline_duration"
77 #define KEY_ISSUER "issuer"
78 #define KEY_ISSUED "issued"
79
80 #define IDENT_FORMAT            "%s [%s@%s/%s]"
81 #define IDENT_DATA(user)        user->nick, user->ident, user->hostname, inet_ntoa(user->ip)
82 #define MAX_CHANNELS_WHOIS      50
83 #define OSMSG_PART_REASON       "%s has no reason."
84 #define OSMSG_KICK_REQUESTED    "Kick requested by %s."
85 #define OSMSG_KILL_REQUESTED    "Kill requested by %s."
86 #define OSMSG_GAG_REQUESTED     "Gag requested by %s."
87
88 static const struct message_entry msgtab[] = {
89     { "OSMSG_USER_ACCESS_IS", "$b%s$b (account $b%s$b) has %d access." },
90     { "OSMSG_LEVEL_TOO_LOW", "You lack sufficient access to use this command." },
91     { "OSMSG_NEED_CHANNEL", "You must specify a channel for $b%s$b." },
92     { "OSMSG_INVALID_IRCMASK", "$b%s$b is an invalid IRC hostmask." },
93     { "OSMSG_ADDED_BAN", "I have banned $b%s$b from $b%s$b." },
94     { "OSMSG_GLINE_ISSUED", "G-line issued for $b%s$b." },
95     { "OSMSG_GLINE_REMOVED", "G-line removed for $b%s$b." },
96     { "OSMSG_GLINE_FORCE_REMOVED", "Unknown/expired G-line removed for $b%s$b." },
97     { "OSMSG_GLINES_ONE_REFRESHED", "All G-lines resent to $b%s$b." },
98     { "OSMSG_GLINES_REFRESHED", "All G-lines refreshed." },
99     { "OSMSG_CLEARBANS_DONE", "Cleared all bans from channel $b%s$b." },
100     { "OSMSG_CLEARMODES_DONE", "Cleared all modes from channel $b%s$b." },
101     { "OSMSG_NO_CHANNEL_MODES", "Channel $b%s$b had no modes to clear." },
102     { "OSMSG_DEOP_DONE", "Deopped the requested lusers." },
103     { "OSMSG_DEOPALL_DONE", "Deopped everyone on $b%s$b." },
104     { "OSMSG_NO_DEBUG_CHANNEL", "No debug channel has been configured." },
105     { "OSMSG_INVITE_DONE", "Invited $b%s$b to $b%s$b." },
106     { "OSMSG_ALREADY_THERE", "You are already in $b%s$b." },
107     { "OSMSG_JOIN_DONE", "I have joined $b%s$b." },
108     { "OSMSG_ALREADY_JOINED", "I am already in $b%s$b." },
109     { "OSMSG_NOT_ON_CHANNEL", "$b%s$b does not seem to be on $b%s$b." },
110     { "OSMSG_KICKALL_DONE", "I have cleared out %s." },
111     { "OSMSG_LEAVING", "Leaving $b%s$b." },
112     { "OSMSG_MODE_SET", "I have set the modes for $b%s$b." },
113     { "OSMSG_OP_DONE", "Opped the requested lusers." },
114     { "OSMSG_OPALL_DONE", "Opped everyone on $b%s$b." },
115     { "OSMSG_WHOIS_IDENT", "%s (%s@%s) from %d.%d.%d.%d" },
116     { "OSMSG_WHOIS_NICK", "Nick    : %s" },
117     { "OSMSG_WHOIS_HOST", "Host    : %s@%s" },
118     { "OSMSG_WHOIS_FAKEHOST", "Fakehost: %s" },
119     { "OSMSG_WHOIS_IP",   "Real IP : %s" },
120     { "OSMSG_WHOIS_MODES", "Modes   : +%s " },
121     { "OSMSG_WHOIS_INFO", "Info    : %s" },
122     { "OSMSG_WHOIS_NUMERIC", "Numnick : %s" },
123     { "OSMSG_WHOIS_SERVER", "Server  : %s" },
124     { "OSMSG_WHOIS_NICK_AGE", "Nick Age: %s" },
125     { "OSMSG_WHOIS_ACCOUNT", "Account : %s" },
126     { "OSMSG_WHOIS_CHANNELS", "Channels: %s" },
127     { "OSMSG_WHOIS_HIDECHANS", "Channel list omitted for your sanity." },
128     { "OSMSG_UNBAN_DONE", "Ban(s) removed from channel %s." },
129     { "OSMSG_CHANNEL_VOICED", "All users on %s voiced." },
130     { "OSMSG_CHANNEL_DEVOICED", "All voiced users on %s de-voiced." },
131     { "OSMSG_BAD_MODIFIER", "Unknown bad-word modifier $b%s$b." },
132     { "OSMSG_BAD_REDUNDANT", "$b%s$b is already covered by a bad word ($b%s$b)." },
133     { "OSMSG_BAD_GROWING", "Replacing bad word $b%s$b with shorter bad word $b%s$b." },
134     { "OSMSG_BAD_NUKING", " .. and removing redundant bad word $b%s$b." },
135     { "OSMSG_ADDED_BAD", "Added $b%s$b to the bad-word list." },
136     { "OSMSG_REMOVED_BAD", "Removed $b%s$b from the bad-word list." },
137     { "OSMSG_NOT_BAD_WORD", "$b%s$b is not a bad word." },
138     { "OSMSG_ADDED_EXEMPTION", "Added $b%s$b to the bad-word exemption list." },
139     { "OSMSG_ADDED_EXEMPTIONS", "Added %d exception(s) to the bad word list." },
140     { "OSMSG_REMOVED_EXEMPTION", "Removed $b%s$b from the exemption list." },
141     { "OSMSG_NOT_EXEMPT", "$b%s$b is not on the exempt list." },
142     { "OSMSG_ALREADY_TRUSTED", "Host $b%s$b is already trusted (use $bdeltrust$b and then $baddtrust$b to adjust)." },
143     { "OSMSG_NOT_TRUSTED", "Host $b%s$b is not trusted." },
144     { "OSMSG_BAD_IP", "$b%s$b is not a valid IP address" },
145     { "OSMSG_BAD_NUMBER", "$b%s$b is not a number" },
146     { "OSMSG_ADDED_TRUSTED", "Added trusted hosts to the trusted-hosts list." },
147     { "OSMSG_UPDATED_TRUSTED", "Updated trusted host $b%s$b." },
148     { "OSMSG_REMOVED_TRUSTED", "Removed trusted hosts from the trusted-hosts list." },
149     { "OSMSG_CLONE_EXISTS", "Nick $b%s$b is already in use." },
150     { "OSMSG_NOT_A_HOSTMASK", "The hostmask must be in user@host form." },
151     { "OSMSG_BADWORD_LIST", "Bad words: %s" },
152     { "OSMSG_EXEMPTED_LIST", "Exempted channels: %s" },
153     { "OSMSG_GLINE_COUNT", "There are %d glines active on the network." },
154     { "OSMSG_LINKS_SERVER", "%s%s (%u clients; %s)" },
155     { "OSMSG_MAX_CLIENTS", "Max clients: %d at %s" },
156     { "OSMSG_NETWORK_INFO", "Total users: %d (%d invisible, %d opers)" },
157     { "OSMSG_RESERVED_LIST", "List of reserved nicks:" },
158     { "OSMSG_TRUSTED_LIST", "List of trusted hosts:" },
159     { "OSMSG_HOST_IS_TRUSTED", "%s (%s; set %s ago by %s; expires %s: %s)" },
160     { "OSMSG_HOST_NOT_TRUSTED", "%s does not have a special trust." },
161     { "OSMSG_UPTIME_STATS", "Uptime: %s (%u lines processed, CPU time %.2fu/%.2fs)" },
162     { "OSMSG_LINE_DUMPED", "Raw line sent." },
163     { "OSMSG_RAW_PARSE_ERROR", "Error parsing raw line (not dumping to uplink)." },
164     { "OSMSG_COLLIDED_NICK", "Now temporarily holding nick $b%s$b." },
165     { "OSMSG_RESERVED_NICK", "Now reserving nick $b%s$b." },
166     { "OSMSG_NICK_UNRESERVED", "Nick $b%s$b is no longer reserved." },
167     { "OSMSG_NOT_RESERVED", "Nick $b%s$b is not reserved." },
168     { "OSMSG_ILLEGAL_REASON", "This channel is illegal." },
169     { "OSMSG_ILLEGAL_KILL_REASON", "Joined an illegal modeless channel - do not repeat." },
170     { "OSMSG_ILLEGAL_CHANNEL", "$b%s$b is an ILLEGAL channel. Do not re-join it." },
171     { "OSMSG_FLOOD_MODERATE", "This channel has been temporarily moderated due to a possible join flood attack detected in this channel; network staff have been notified and will investigate." },
172     { "OSMSG_CLONE_WARNING", "WARNING: You have connected the maximum permitted number of clients from one IP address (clones).  If you connect any more, your host will be temporarily banned from the network." },
173     { "OSMSG_CLONE_ADDED", "Added clone $b%s$b." },
174     { "OSMSG_CLONE_FAILED", "Unable to add user $b%s$b." },
175     { "OSMSG_NOT_A_CLONE", "Har har.  $b%s$b isn't a clone." },
176     { "OSMSG_CLONE_REMOVED", "Removed clone $b%s$b." },
177     { "OSMSG_CLONE_JOINED", "$b%s$b has joined $b%s$b." },
178     { "OSMSG_CLONE_PARTED", "$b%s$b has left $b%s$b." },
179     { "OSMSG_OPS_GIVEN", "I have given ops in $b%s$b to $b%s$b." },
180     { "OSMSG_CLONE_SAID", "$b%s$b has spoken to $b%s$b." },
181     { "OSMSG_UNKNOWN_SUBCOMMAND", "$b%s$b is not a valid subcommand of $b%s$b." },
182     { "OSMSG_UNKNOWN_OPTION", "$b%s$b has not been set." },
183     { "OSMSG_OPTION_IS", "$b%s$b is set to $b%s$b." },
184     { "OSMSG_OPTION_ROOT", "The following keys can be queried:" },
185     { "OSMSG_OPTION_LIST", "$b%s$b contains the following values:" },
186     { "OSMSG_OPTION_KEYS", "$b%s$b contains the following keys:" },
187     { "OSMSG_OPTION_LIST_EMPTY", "Empty list." },
188     { "OSMSG_SET_NOT_SET", "$b%s$b does not exist, and cannot be set." },
189     { "OSMSG_SET_BAD_TYPE", "$b%s$b is not a string, and cannot be set." },
190     { "OSMSG_SET_SUCCESS", "$b%s$b has been set to $b%s$b." },
191     { "OSMSG_SETTIME_SUCCESS", "Set time for servers named like $b%s$b." },
192     { "OSMSG_BAD_ACTION", "Unrecognized trace action $b%s$b." },
193     { "OSMSG_USER_SEARCH_RESULTS", "The following users were found:" },
194     { "OSMSG_CHANNEL_SEARCH_RESULTS", "The following channels were found:" },
195     { "OSMSG_GLINE_SEARCH_RESULTS", "The following glines were found:" },
196     { "OSMSG_LOG_SEARCH_RESULTS", "The following log entries were found:" },
197     { "OSMSG_GSYNC_RUNNING", "Synchronizing glines from %s." },
198     { "OSMSG_GTRACE_FORMAT", "%s (issued %s by %s, expires %s): %s" },
199     { "OSMSG_GAG_APPLIED", "Gagged $b%s$b, affecting %d users." },
200     { "OSMSG_GAG_ADDED", "Gagged $b%s$b." },
201     { "OSMSG_REDUNDANT_GAG", "Gag $b%s$b is redundant." },
202     { "OSMSG_GAG_NOT_FOUND", "Could not find gag $b%s$b." },
203     { "OSMSG_NO_GAGS", "No gags have been set." },
204     { "OSMSG_UNGAG_APPLIED", "Ungagged $b%s$b, affecting %d users." },
205     { "OSMSG_UNGAG_ADDED", "Ungagged $b%s$b." },
206     { "OSMSG_TIMEQ_INFO", "%u events in timeq; next in %lu seconds." },
207     { "OSMSG_ALERT_EXISTS", "An alert named $b%s$b already exists." },
208     { "OSMSG_UNKNOWN_REACTION", "Unknown alert reaction $b%s$b." },
209     { "OSMSG_ADDED_ALERT", "Added alert named $b%s$b." },
210     { "OSMSG_REMOVED_ALERT", "Removed alert named $b%s$b." },
211     { "OSMSG_NO_SUCH_ALERT", "No alert named $b%s$b could be found." },
212     { "OSMSG_ALERT_IS", "%s (by %s, reaction %s): %s" },
213     { "OSMSG_ALERTS_LIST", "Current $O alerts:" },
214     { "OSMSG_REHASH_COMPLETE", "Completed rehash of configuration database." },
215     { "OSMSG_REHASH_FAILED", "Rehash of configuration database failed, previous configuration is intact." },
216     { "OSMSG_REOPEN_COMPLETE", "Closed and reopened all log files." },
217     { "OSMSG_RECONNECTING", "Reconnecting to my uplink." },
218     { "OSMSG_NUMERIC_COLLIDE", "Numeric %d (%s) is already in use." },
219     { "OSMSG_NAME_COLLIDE", "That name is already in use." },
220     { "OSMSG_SRV_CREATE_FAILED", "Server creation failed -- check log files." },
221     { "OSMSG_SERVER_JUPED", "Added new jupe server %s." },
222     { "OSMSG_SERVER_NOT_JUPE", "That server is not a juped server." },
223     { "OSMSG_SERVER_UNJUPED", "Server jupe removed." },
224     { "OSMSG_WARN_ADDED", "Added channel activity warning for $b%s$b (%s)" },
225     { "OSMSG_WARN_EXISTS", "Channel activity warning for $b%s$b already exists." },
226     { "OSMSG_WARN_DELETED", "Removed channel activity warning for $b%s$b" },
227     { "OSMSG_WARN_NOEXIST", "Channel activity warning for $b%s$b does not exist." },
228     { "OSMSG_WARN_LISTSTART", "Channel activity warnings:" },
229     { "OSMSG_WARN_LISTENTRY", "%s (%s)" },
230     { "OSMSG_WARN_LISTEND", "End of activity warning list." },
231     { "OSMSG_STATS_MEMORY", "%u allocations totalling %u bytes." },
232     { "OSMSG_UPLINK_CONNECTING", "Establishing connection with %s (%s:%d)." },
233     { "OSMSG_CURRENT_UPLINK", "$b%s$b is already the current uplink." },
234     { "OSMSG_INVALID_UPLINK", "$b%s$b is not a valid uplink name." },
235     { "OSMSG_UPLINK_DISABLED", "$b%s$b is a disabled or unavailable uplink." },
236     { "OSMSG_UPLINK_START", "Uplink $b%s$b:" },
237     { "OSMSG_UPLINK_ADDRESS", "Address: %s:%d" },
238     { "OSMSG_STUPID_GLINE", "Gline %s?  Now $bthat$b would be smooth." },
239     { "OSMSG_ACCOUNTMASK_AUTHED", "Invalid criteria: it is impossible to match an account mask but not be authed" },
240     { "OSMSG_CHANINFO_HEADER", "%s Information" },
241     { "OSMSG_CHANINFO_TIMESTAMP", "Created on: %a %b %d %H:%M:%S %Y (%s)" },
242     { "OSMSG_CHANINFO_MODES", "Modes: %s" },
243     { "OSMSG_CHANINFO_MODES_BADWORD", "Modes: %s; bad-word channel" },
244     { "OSMSG_CHANINFO_TOPIC", "Topic (set by %%s, %a %b %d %H:%M:%S %Y): %%s" },
245     { "OSMSG_CHANINFO_TOPIC_UNKNOWN", "Topic: (none / not gathered)" },
246     { "OSMSG_CHANINFO_BAN_COUNT", "Bans (%d):" },
247     { "OSMSG_CHANINFO_BAN", "%%s by %%s (%a %b %d %H:%M:%S %Y)" },
248     { "OSMSG_CHANINFO_MANY_USERS", "%d users (\"/msg $S %s %s users\" for the list)" },
249     { "OSMSG_CHANINFO_USER_COUNT", "Users (%d):" },
250     { "OSMSG_CSEARCH_CHANNEL_INFO", "%s [%d users] %s %s" },
251     { NULL, NULL }
252 };
253
254 #define OPSERV_SYNTAX() svccmd_send_help(user, opserv, cmd)
255
256 typedef int (*discrim_search_func)(struct userNode *match, void *extra);
257
258 struct userNode *opserv;
259
260 static dict_t opserv_chan_warn; /* data is char* */
261 static dict_t opserv_reserved_nick_dict; /* data is struct userNode* */
262 static struct string_list *opserv_bad_words;
263 static dict_t opserv_exempt_channels; /* data is not used */
264 static dict_t opserv_trusted_hosts; /* data is struct trusted_host* */
265 static dict_t opserv_hostinfo_dict; /* data is struct opserv_hostinfo* */
266 static dict_t opserv_user_alerts; /* data is struct opserv_user_alert* */
267 static dict_t opserv_nick_based_alerts; /* data is struct opserv_user_alert* */
268 static dict_t opserv_channel_alerts; /* data is struct opserv_user_alert* */
269 static struct module *opserv_module;
270 static struct log_type *OS_LOG;
271 static unsigned int new_user_flood;
272 static char *level_strings[1001];
273
274 static struct {
275     struct chanNode *debug_channel;
276     struct chanNode *alert_channel;
277     struct chanNode *staff_auth_channel;
278     struct policer_params *join_policer_params;
279     struct policer new_user_policer;
280     unsigned long untrusted_max;
281     unsigned long clone_gline_duration;
282     unsigned long block_gline_duration;
283     unsigned long purge_lock_delay;
284     unsigned long join_flood_moderate;
285     unsigned long join_flood_moderate_threshold;
286 } opserv_conf;
287
288 struct trusted_host {
289     char *ipaddr;
290     char *issuer;
291     char *reason;
292     unsigned long limit;
293     time_t issued;
294     time_t expires;
295 };
296
297 struct gag_entry {
298     char *mask;
299     char *owner;
300     char *reason;
301     time_t expires;
302     struct gag_entry *next;
303 };
304
305 static struct gag_entry *gagList;
306
307 struct opserv_hostinfo {
308     struct userList clients;
309     struct trusted_host *trusted;
310 };
311
312 static void
313 opserv_free_hostinfo(void *data)
314 {
315     struct opserv_hostinfo *ohi = data;
316     userList_clean(&ohi->clients);
317     free(ohi);
318 }
319
320 typedef struct opservDiscrim {
321     struct chanNode *channel;
322     char *mask_nick, *mask_ident, *mask_host, *mask_info, *server, *ip_mask_str, *reason, *accountmask;
323     unsigned long limit, ip_mask;
324     struct in_addr ip_addr;
325     unsigned int min_level, max_level, domain_depth, duration, min_clones, min_channels, max_channels;
326     unsigned int match_opers : 1, option_log : 1;
327     unsigned int chan_req_modes : 2, chan_no_modes : 2;
328     int authed : 2, info_space : 2;
329     time_t min_ts, max_ts;
330 } *discrim_t;
331
332 struct discrim_and_source {
333     discrim_t discrim;
334     struct userNode *source;
335     dict_t dict;
336     unsigned int disp_limit;
337 };
338
339 static discrim_t opserv_discrim_create(struct userNode *user, unsigned int argc, char *argv[], int allow_channel);
340 static unsigned int opserv_discrim_search(discrim_t discrim, discrim_search_func dsf, void *data);
341 static int gag_helper_func(struct userNode *match, void *extra);
342 static int ungag_helper_func(struct userNode *match, void *extra);
343
344 typedef enum {
345     REACT_NOTICE,
346     REACT_KILL,
347     REACT_GLINE
348 } opserv_alert_reaction;
349
350 struct opserv_user_alert {
351     char *owner;
352     char *text_discrim, *split_discrim;
353     discrim_t discrim;
354     opserv_alert_reaction reaction;
355 };
356
357 /* funny type to make it acceptible to dict_set_free_data, far below */
358 static void
359 opserv_free_user_alert(void *data)
360 {
361     struct opserv_user_alert *alert = data;
362     if (alert->discrim->channel)
363         UnlockChannel(alert->discrim->channel);
364     free(alert->owner);
365     free(alert->text_discrim);
366     free(alert->split_discrim);
367     free(alert->discrim->reason);
368     free(alert->discrim);
369     free(alert);
370 }
371
372 #define opserv_debug(format...) do { if (opserv_conf.debug_channel) send_channel_notice(opserv_conf.debug_channel , opserv , ## format); } while (0)
373 #define opserv_alert(format...) do { if (opserv_conf.alert_channel) send_channel_notice(opserv_conf.alert_channel , opserv , ## format); } while (0)
374
375 /* A lot of these commands are very similar to what ChanServ can do,
376  * but OpServ can do them even on channels that aren't registered.
377  */
378
379 static MODCMD_FUNC(cmd_access)
380 {
381     struct handle_info *hi;
382     const char *target;
383     unsigned int res;
384
385     target = (argc > 1) ? (const char*)argv[1] : user->nick;
386     if (!irccasecmp(target, "*")) {
387         nickserv_show_oper_accounts(user, cmd);
388         return 1;
389     }
390     if (!(hi = modcmd_get_handle_info(user, target)))
391         return 0;
392     res = (argc > 2) ? oper_try_set_access(user, cmd->parent->bot, hi, strtoul(argv[2], NULL, 0)) : 0;
393     reply("OSMSG_USER_ACCESS_IS", target, hi->handle, hi->opserv_level);
394     return res;
395 }
396
397 static MODCMD_FUNC(cmd_ban)
398 {
399     struct mod_chanmode change;
400     struct userNode *victim;
401
402     mod_chanmode_init(&change);
403     change.argc = 1;
404     change.args[0].mode = MODE_BAN;
405     if (is_ircmask(argv[1]))
406         change.args[0].u.hostmask = strdup(argv[1]);
407     else if ((victim = GetUserH(argv[1])))
408         change.args[0].u.hostmask = generate_hostmask(victim, 0);
409     else {
410         reply("OSMSG_INVALID_IRCMASK", argv[1]);
411         return 0;
412     }
413     modcmd_chanmode_announce(&change);
414     reply("OSMSG_ADDED_BAN", change.args[0].u.hostmask, channel->name);
415     free((char*)change.args[0].u.hostmask);
416     return 1;
417 }
418
419 static MODCMD_FUNC(cmd_chaninfo)
420 {
421     char buffer[MAXLEN];
422     const char *fmt;
423     struct banNode *ban;
424     struct modeNode *moden;
425     unsigned int n;
426
427     reply("OSMSG_CHANINFO_HEADER", channel->name);
428     fmt = user_find_message(user, "OSMSG_CHANINFO_TIMESTAMP");
429     strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->timestamp));
430     send_message_type(4, user, cmd->parent->bot, "%s", buffer);
431     irc_make_chanmode(channel, buffer);
432     if (channel->bad_channel)
433         reply("OSMSG_CHANINFO_MODES_BADWORD", buffer);
434     else
435         reply("OSMSG_CHANINFO_MODES", buffer);
436     if (channel->topic_time) {
437         fmt = user_find_message(user, "OSMSG_CHANINFO_TOPIC");
438         strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->topic_time));
439         send_message_type(4, user, cmd->parent->bot, buffer, channel->topic_nick, channel->topic);
440     } else {
441         irc_fetchtopic(cmd->parent->bot, channel->name);
442         reply("OSMSG_CHANINFO_TOPIC_UNKNOWN");
443     }
444     if (channel->banlist.used) {
445         reply("OSMSG_CHANINFO_BAN_COUNT", channel->banlist.used);
446         fmt = user_find_message(user, "OSMSG_CHANINFO_BAN");
447         for (n = 0; n < channel->banlist.used; n++) {
448             ban = channel->banlist.list[n];
449             strftime(buffer, sizeof(buffer), fmt, localtime(&ban->set));
450             send_message_type(4, user, cmd->parent->bot, buffer, ban->ban, ban->who);
451         }
452     }
453     if ((argc < 2) && (channel->members.used >= 50)) {
454         /* early out unless they ask for users */
455         reply("OSMSG_CHANINFO_MANY_USERS", channel->members.used, argv[0], channel->name);
456         return 1;
457     }
458     reply("OSMSG_CHANINFO_USER_COUNT", channel->members.used);
459     for (n=0; n<channel->members.used; n++) {
460         moden = channel->members.list[n];
461         if (moden->modes & MODE_CHANOP)
462             send_message_type(4, user, cmd->parent->bot, " @%s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
463     }
464     for (n=0; n<channel->members.used; n++) {
465         moden = channel->members.list[n];
466         if ((moden->modes & (MODE_CHANOP|MODE_VOICE)) == MODE_VOICE)
467             send_message_type(4, user, cmd->parent->bot, " +%s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
468     }
469     for (n=0; n<channel->members.used; n++) {
470         moden = channel->members.list[n];
471         if ((moden->modes & (MODE_CHANOP|MODE_VOICE)) == 0)
472             send_message_type(4, user, cmd->parent->bot, "  %s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
473     }
474     return 1;
475 }
476
477 static MODCMD_FUNC(cmd_warn) 
478 {
479     char *reason, *message;
480
481     if (!IsChannelName(argv[1])) {
482         reply("OSMSG_NEED_CHANNEL", argv[0]);
483         return 0;
484     }
485     reason = dict_find(opserv_chan_warn, argv[1], NULL);
486     if (reason) {
487         reply("OSMSG_WARN_EXISTS", argv[1]);
488         return 0;
489     }
490     if (argv[2])
491         reason = strdup(unsplit_string(argv+2, argc-2, NULL));
492     else
493         reason = strdup("No reason");
494     dict_insert(opserv_chan_warn, strdup(argv[1]), reason);
495     reply("OSMSG_WARN_ADDED", argv[1], reason);
496     if (dict_find(channels, argv[1], NULL)) {
497         message = alloca(strlen(reason) + strlen(argv[1]) + 55);
498         sprintf(message, "Channel activity warning for channel %s: %s", argv[1], reason);
499         global_message(MESSAGE_RECIPIENT_OPERS, message);
500     }
501     return 1;
502 }
503
504 static MODCMD_FUNC(cmd_unwarn)
505 {
506     if ((argc < 2) || !IsChannelName(argv[1])) {
507         reply("OSMSG_NEED_CHANNEL", argv[0]);
508         return 0;
509     }
510     if (!dict_remove(opserv_chan_warn, argv[1])) {
511         reply("OSMSG_WARN_NOEXIST", argv[1]);
512         return 0;
513     }
514     reply("OSMSG_WARN_DELETED", argv[1]);
515     return 1;
516 }
517
518 static MODCMD_FUNC(cmd_clearbans)
519 {
520     struct mod_chanmode *change;
521     unsigned int ii;
522
523     change = mod_chanmode_alloc(channel->banlist.used);
524     for (ii=0; ii<channel->banlist.used; ii++) {
525         change->args[ii].mode = MODE_REMOVE | MODE_BAN;
526         change->args[ii].u.hostmask = strdup(channel->banlist.list[ii]->ban);
527     }
528     modcmd_chanmode_announce(change);
529     for (ii=0; ii<change->argc; ++ii)
530         free((char*)change->args[ii].u.hostmask);
531     mod_chanmode_free(change);
532     reply("OSMSG_CLEARBANS_DONE", channel->name);
533     return 1;
534 }
535
536 static MODCMD_FUNC(cmd_clearmodes)
537 {
538     struct mod_chanmode change;
539
540     if (!channel->modes) {
541         reply("OSMSG_NO_CHANNEL_MODES", channel->name);
542         return 0;
543     }
544     mod_chanmode_init(&change);
545     change.modes_clear = channel->modes;
546     modcmd_chanmode_announce(&change);
547     reply("OSMSG_CLEARMODES_DONE", channel->name);
548     return 1;
549 }
550
551 static MODCMD_FUNC(cmd_deop)
552 {
553     struct mod_chanmode *change;
554     unsigned int arg, count;
555
556     change = mod_chanmode_alloc(argc-1);
557     for (arg = 1, count = 0; arg < argc; ++arg) {
558         struct userNode *victim = GetUserH(argv[arg]);
559         struct modeNode *mn;
560         if (!victim || IsService(victim)
561             || !(mn = GetUserMode(channel, victim))
562             || !(mn->modes & MODE_CHANOP))
563             continue;
564         change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
565         change->args[count++].u.member = mn;
566     }
567     if (count) {
568         change->argc = count;
569         modcmd_chanmode_announce(change);
570     }
571     mod_chanmode_free(change);
572     reply("OSMSG_DEOP_DONE");
573     return 1;
574 }
575
576 static MODCMD_FUNC(cmd_deopall)
577 {
578     struct mod_chanmode *change;
579     unsigned int ii, count;
580
581     change = mod_chanmode_alloc(channel->members.used);
582     for (ii = count = 0; ii < channel->members.used; ++ii) {
583         struct modeNode *mn = channel->members.list[ii];
584         if (IsService(mn->user) || !(mn->modes & MODE_CHANOP))
585             continue;
586         change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
587         change->args[count++].u.member = mn;
588     }
589     if (count) {
590         change->argc = count;
591         modcmd_chanmode_announce(change);
592     }
593     mod_chanmode_free(change);
594     reply("OSMSG_DEOPALL_DONE", channel->name);
595     return 1;
596 }
597
598 static MODCMD_FUNC(cmd_rehash)
599 {
600     extern char *services_config;
601
602     if (conf_read(services_config))
603         reply("OSMSG_REHASH_COMPLETE");
604     else
605         reply("OSMSG_REHASH_FAILED");
606     return 1;
607 }
608
609 static MODCMD_FUNC(cmd_reopen)
610 {
611     log_reopen();
612     reply("OSMSG_REOPEN_COMPLETE");
613     return 1;
614 }
615
616 static MODCMD_FUNC(cmd_reconnect)
617 {
618     reply("OSMSG_RECONNECTING");
619     irc_squit(self, "Reconnecting.", NULL);
620     return 1;
621 }
622
623 static MODCMD_FUNC(cmd_jupe)
624 {
625     extern int force_n2k;
626     struct server *newsrv;
627     unsigned int num;
628     char numeric[COMBO_NUMERIC_LEN+1], srvdesc[SERVERDESCRIPTMAX+1];
629
630     num = atoi(argv[2]);
631     if ((num < 64) && !force_n2k) {
632         inttobase64(numeric, num, 1);
633         inttobase64(numeric+1, 64*64-1, 2);
634     } else {
635         inttobase64(numeric, num, 2);
636         inttobase64(numeric+2, 64*64*64-1, 3);
637     }
638 #ifdef WITH_PROTOCOL_P10
639     if (GetServerN(numeric)) {
640         reply("OSMSG_NUMERIC_COLLIDE", num, numeric);
641         return 0;
642     }
643 #endif
644     if (GetServerH(argv[1])) {
645         reply("OSMSG_NAME_COLLIDE");
646         return 0;
647     }
648     snprintf(srvdesc, sizeof(srvdesc), "JUPE %s", unsplit_string(argv+3, argc-3, NULL));
649     newsrv = AddServer(self, argv[1], 1, now, now, numeric, srvdesc);
650     if (!newsrv) {
651         reply("OSMSG_SRV_CREATE_FAILED");
652         return 0;
653     }
654     irc_server(newsrv);
655     reply("OSMSG_SERVER_JUPED", argv[1]);
656     return 1;
657 }
658
659 static MODCMD_FUNC(cmd_unjupe)
660 {
661     struct server *srv;
662     char *reason;
663
664     srv = GetServerH(argv[1]);
665     if (!srv) {
666         reply("MSG_SERVER_UNKNOWN", argv[1]);
667         return 0;
668     }
669     if (strncmp(srv->description, "JUPE", 4)) {
670         reply("OSMSG_SERVER_NOT_JUPE");
671         return 0;
672     }
673     reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : "Unjuping server";
674     DelServer(srv, 1, reason);
675     reply("OSMSG_SERVER_UNJUPED");
676     return 1;
677 }
678
679 static MODCMD_FUNC(cmd_jump)
680 {
681     extern struct cManagerNode cManager;
682     void uplink_select(char *name);
683     struct uplinkNode *uplink_find(char *name);
684     struct uplinkNode *uplink;
685     char *target;
686
687     target = unsplit_string(argv+1, argc-1, NULL);
688
689     if (!strcmp(cManager.uplink->name, target)) {
690         reply("OSMSG_CURRENT_UPLINK", cManager.uplink->name);
691         return 0;
692     }
693
694     uplink = uplink_find(target);
695     if (!uplink) {
696         reply("OSMSG_INVALID_UPLINK", target);
697         return 0;
698     }
699     if (uplink->flags & UPLINK_UNAVAILABLE) {
700         reply("OSMSG_UPLINK_DISABLED", uplink->name);
701         return 0;
702     }
703
704     reply("OSMSG_UPLINK_CONNECTING", uplink->name, uplink->host, uplink->port);
705     uplink_select(target);
706     irc_squit(self, "Reconnecting.", NULL);
707     return 1;
708 }
709
710 static MODCMD_FUNC(cmd_die)
711 {
712     char *reason, *text;
713
714     text = unsplit_string(argv+1, argc-1, NULL);
715     reason = alloca(strlen(text) + strlen(user->nick) + 20);
716     sprintf(reason, "Disconnected by %s [%s]", user->nick, text);
717     irc_squit(self, reason, text);
718     quit_services = 1;
719     return 1;
720 }
721
722 static MODCMD_FUNC(cmd_restart)
723 {
724     extern int services_argc;
725     extern char **services_argv;
726     char **restart_argv, *reason, *text;
727
728     text = unsplit_string(argv+1, argc-1, NULL);
729     reason = alloca(strlen(text) + strlen(user->nick) + 17);
730     sprintf(reason, "Restarted by %s [%s]", user->nick, text);
731     irc_squit(self, reason, text);
732
733     /* Append a NULL to the end of argv[]. */
734     restart_argv = (char **)alloca((services_argc + 1) * sizeof(char *));
735     memcpy(restart_argv, services_argv, services_argc * sizeof(char *));
736     restart_argv[services_argc] = NULL;
737
738     call_exit_funcs();
739
740     /* Don't blink. */
741     execv(services_argv[0], restart_argv);
742
743     /* If we're still here, that means something went wrong. Reconnect. */
744     return 1;
745 }
746
747 static struct gline *
748 opserv_block(struct userNode *target, char *src_handle, char *reason, unsigned long duration)
749 {
750     char *mask;
751     mask = alloca(MAXLEN);
752     snprintf(mask, MAXLEN, "*@%s", target->hostname);
753     if (!reason) {
754         reason = alloca(MAXLEN);
755         snprintf(reason, MAXLEN, "G-line requested by %s.", src_handle);
756     }
757     if (!duration) duration = opserv_conf.block_gline_duration;
758     return gline_add(src_handle, mask, duration, reason, now, 1);
759 }
760
761 static MODCMD_FUNC(cmd_block)
762 {
763     struct userNode *target;
764     struct gline *gline;
765     char *reason;
766
767     target = GetUserH(argv[1]);
768     if (!target) {
769         reply("MSG_NICK_UNKNOWN", argv[1]);
770         return 0;
771     }
772     if (IsService(target)) {
773         reply("MSG_SERVICE_IMMUNE", target->nick);
774         return 0;
775     }
776     reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : NULL;
777     gline = opserv_block(target, user->handle_info->handle, reason, 0);
778     reply("OSMSG_GLINE_ISSUED", gline->target);
779     return 1;
780 }
781
782 static MODCMD_FUNC(cmd_gline)
783 {
784     unsigned long duration;
785     char *reason;
786     struct gline *gline;
787
788     reason = unsplit_string(argv+3, argc-3, NULL);
789     if (!is_gline(argv[1]) && !IsChannelName(argv[1]) && (argv[1][0] != '&')) {
790         reply("MSG_INVALID_GLINE", argv[1]);
791         return 0;
792     }
793     if (!argv[1][strspn(argv[1], "#&*?@.")] && (strlen(argv[1]) < 10)) {
794         reply("OSMSG_STUPID_GLINE", argv[1]);
795         return 0;
796     }
797     duration = ParseInterval(argv[2]);
798     if (!duration) {
799         reply("MSG_INVALID_DURATION", argv[2]);
800         return 0;
801     }
802     gline = gline_add(user->handle_info->handle, argv[1], duration, reason, now, 1);
803     reply("OSMSG_GLINE_ISSUED", gline->target);
804     return 1;
805 }
806
807 static MODCMD_FUNC(cmd_ungline)
808 {
809     if (gline_remove(argv[1], 1))
810         reply("OSMSG_GLINE_REMOVED", argv[1]);
811     else
812         reply("OSMSG_GLINE_FORCE_REMOVED", argv[1]);
813     return 1;
814 }
815
816 static MODCMD_FUNC(cmd_refreshg)
817 {
818     if (argc > 1) {
819         unsigned int count;
820         dict_iterator_t it;
821         struct server *srv;
822
823         for (it=dict_first(servers), count=0; it; it=iter_next(it)) {
824             srv = iter_data(it);
825             if ((srv == self) || !match_ircglob(srv->name, argv[1]))
826                 continue;
827             gline_refresh_server(srv);
828             reply("OSMSG_GLINES_ONE_REFRESHED", srv->name);
829             count++;
830         }
831         if (!count) {
832             reply("MSG_SERVER_UNKNOWN", argv[1]);
833             return 0;
834         }
835     } else {
836         gline_refresh_all();
837         reply("OSMSG_GLINES_REFRESHED");
838     }
839     return 1;
840 }
841
842 static void
843 opserv_ison(struct userNode *tell, struct userNode *target, const char *message)
844 {
845     struct modeNode *mn;
846     unsigned int count, here_len, n, maxlen;
847     char buff[MAXLEN];
848
849     maxlen = tell->handle_info ? tell->handle_info->screen_width : 0;
850     if (!maxlen)
851         maxlen = MAX_LINE_SIZE;
852     for (n=count=0; n<target->channels.used; n++) {
853         mn = target->channels.list[n];
854         here_len = strlen(mn->channel->name);
855         if ((count + here_len + 4) > maxlen) {
856             buff[count] = 0;
857             send_message(tell, opserv, message, buff);
858             count = 0;
859         }
860         if (mn->modes & MODE_CHANOP)
861             buff[count++] = '@';
862         if (mn->modes & MODE_VOICE)
863             buff[count++] = '+';
864         memcpy(buff+count, mn->channel->name, here_len);
865         count += here_len;
866         buff[count++] = ' ';
867     }
868     if (count) {
869         buff[count] = 0;
870         send_message(tell, opserv, message, buff);
871     }
872 }
873
874 static MODCMD_FUNC(cmd_inviteme)
875 {
876     struct userNode *target;
877
878     if (argc < 2) {
879         target = user;
880     } else {
881         target = GetUserH(argv[1]);
882         if (!target) {
883             reply("MSG_NICK_UNKNOWN", argv[1]);
884             return 0;
885         }
886     }
887     if (opserv_conf.debug_channel == NULL) {
888         reply("OSMSG_NO_DEBUG_CHANNEL");
889         return 0;
890     }
891     if (GetUserMode(opserv_conf.debug_channel, user)) {
892         reply("OSMSG_ALREADY_THERE", opserv_conf.debug_channel->name);
893         return 0;
894     }
895     irc_invite(cmd->parent->bot, target, opserv_conf.debug_channel);
896     if (target != user)
897         reply("OSMSG_INVITE_DONE", target->nick, opserv_conf.debug_channel->name);
898     return 1;
899 }
900
901 static MODCMD_FUNC(cmd_invite)
902 {
903     if (GetUserMode(channel, user)) {
904         reply("OSMSG_ALREADY_THERE", channel->name);
905         return 0;
906     }
907     irc_invite(cmd->parent->bot, user, channel);
908     return 1;
909 }
910
911 static MODCMD_FUNC(cmd_join)
912 {
913     struct userNode *bot = cmd->parent->bot;
914
915     if (!IsChannelName(argv[1])) {
916         reply("MSG_NOT_CHANNEL_NAME");
917         return 0;
918     } else if (!(channel = GetChannel(argv[1]))) {
919         channel = AddChannel(argv[1], now, NULL, NULL);
920         AddChannelUser(bot, channel)->modes |= MODE_CHANOP;
921     } else if (GetUserMode(channel, bot)) {
922         reply("OSMSG_ALREADY_JOINED", channel->name);
923         return 0;
924     } else {
925         struct mod_chanmode change;
926         mod_chanmode_init(&change);
927         change.argc = 1;
928         change.args[0].mode = MODE_CHANOP;
929         change.args[0].u.member = AddChannelUser(bot, channel);
930         modcmd_chanmode_announce(&change);
931     }
932     irc_fetchtopic(bot, channel->name);
933     reply("OSMSG_JOIN_DONE", channel->name);
934     return 1;
935 }
936
937 static MODCMD_FUNC(cmd_kick)
938 {
939     struct userNode *target;
940     char *reason;
941
942     if (argc < 3) {
943         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
944         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
945     } else {
946         reason = unsplit_string(argv+2, argc-2, NULL);
947     }
948     target = GetUserH(argv[1]);
949     if (!target) {
950         reply("MSG_NICK_UNKNOWN", argv[1]);
951         return 0;
952     }
953     if (!GetUserMode(channel, target)) {
954         reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
955         return 0;
956     }
957     KickChannelUser(target, channel, cmd->parent->bot, reason);
958     return 1;
959 }
960
961 static MODCMD_FUNC(cmd_kickall)
962 {
963     unsigned int limit, n, inchan;
964     struct modeNode *mn;
965     char *reason;
966     struct userNode *bot = cmd->parent->bot;
967
968     /* ircu doesn't let servers KICK users, so if OpServ's not in the
969      * channel, we have to join it in temporarily. */
970     if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
971         struct mod_chanmode change;
972         mod_chanmode_init(&change);
973         change.args[0].mode = MODE_CHANOP;
974         change.args[0].u.member = AddChannelUser(bot, channel);
975         modcmd_chanmode_announce(&change);
976     }
977     if (argc < 2) {
978         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
979         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
980     } else {
981         reason = unsplit_string(argv+1, argc-1, NULL);
982     }
983     limit = user->handle_info->opserv_level;
984     for (n=channel->members.used; n>0;) {
985         mn = channel->members.list[--n];
986         if (IsService(mn->user)
987             || (mn->user->handle_info
988                 && (mn->user->handle_info->opserv_level >= limit))) {
989             continue;
990         }
991         KickChannelUser(mn->user, channel, bot, reason);
992     }
993     if (!inchan)
994         DelChannelUser(bot, channel, "My work here is done", 0);
995     reply("OSMSG_KICKALL_DONE", channel->name);
996     return 1;
997 }
998
999 static MODCMD_FUNC(cmd_kickban)
1000 {
1001     struct mod_chanmode change;
1002     struct userNode *target;
1003     char *reason;
1004     char *mask;
1005
1006     if (argc == 2) {
1007         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1008         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1009     } else {
1010         reason = unsplit_string(argv+2, argc-2, NULL);
1011     }
1012     target = GetUserH(argv[1]);
1013     if (!target) {
1014         reply("MSG_NICK_UNKNOWN", argv[1]);
1015         return 0;
1016     }
1017     if (!GetUserMode(channel, target)) {
1018         reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
1019         return 0;
1020     }
1021     mod_chanmode_init(&change);
1022     change.argc = 1;
1023     change.args[0].mode = MODE_BAN;
1024     change.args[0].u.hostmask = mask = generate_hostmask(target, 0);
1025     modcmd_chanmode_announce(&change);
1026     KickChannelUser(target, channel, cmd->parent->bot, reason);
1027     free(mask);
1028     return 1;
1029 }
1030
1031 static MODCMD_FUNC(cmd_kickbanall)
1032 {
1033     struct modeNode *mn;
1034     struct userNode *bot = cmd->parent->bot;
1035     struct mod_chanmode *change;
1036     char *reason;
1037     unsigned int limit, n, inchan;
1038
1039     /* ircu doesn't let servers KICK users, so if OpServ's not in the
1040      * channel, we have to join it in temporarily. */
1041     if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
1042         change = mod_chanmode_alloc(2);
1043         change->args[0].mode = MODE_CHANOP;
1044         change->args[0].u.member = AddChannelUser(bot, channel);
1045         change->args[1].mode = MODE_BAN;
1046         change->args[1].u.hostmask = "*!*@*";
1047     } else {
1048         change = mod_chanmode_alloc(1);
1049         change->args[0].mode = MODE_BAN;
1050         change->args[0].u.hostmask = "*!*@*";
1051     }
1052     modcmd_chanmode_announce(change);
1053     mod_chanmode_free(change);
1054     if (argc < 2) {
1055         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1056         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1057     } else {
1058         reason = unsplit_string(argv+1, argc-1, NULL);
1059     }
1060     /* now kick them */
1061     limit = user->handle_info->opserv_level;
1062     for (n=channel->members.used; n>0; ) {
1063         mn = channel->members.list[--n];
1064         if (IsService(mn->user)
1065             || (mn->user->handle_info
1066                 && (mn->user->handle_info->opserv_level >= limit))) {
1067             continue;
1068         }
1069         KickChannelUser(mn->user, channel, bot, reason);
1070     }
1071     if (!inchan)
1072         DelChannelUser(bot, channel, "My work here is done", 0);
1073     reply("OSMSG_KICKALL_DONE", channel->name);
1074     return 1;    
1075 }
1076
1077 static MODCMD_FUNC(cmd_part)
1078 {
1079     char *reason;
1080
1081     if (!IsChannelName(argv[1])) {
1082         reply("MSG_NOT_CHANNEL_NAME");
1083         return 0;
1084     }
1085     if ((channel = GetChannel(argv[1]))) {
1086         if (!GetUserMode(channel, cmd->parent->bot)) {
1087             reply("OSMSG_NOT_ON_CHANNEL", cmd->parent->bot->nick, channel->name);
1088             return 0;
1089         }
1090         reason = (argc < 3) ? "Leaving." : unsplit_string(argv+2, argc-2, NULL);
1091         reply("OSMSG_LEAVING", channel->name);
1092         DelChannelUser(cmd->parent->bot, channel, reason, 0);
1093     }
1094     return 1;
1095 }
1096
1097 static MODCMD_FUNC(cmd_mode)
1098 {
1099     if (!modcmd_chanmode(argv+1, argc-1, MCP_ALLOW_OVB|MCP_KEY_FREE|MC_ANNOUNCE)) {
1100         reply("MSG_INVALID_MODES", unsplit_string(argv+1, argc-1, NULL));
1101         return 0;
1102     }
1103     reply("OSMSG_MODE_SET", channel->name);
1104     return 1;
1105 }
1106
1107 static MODCMD_FUNC(cmd_op)
1108 {
1109     struct mod_chanmode *change;
1110     unsigned int arg, count;
1111
1112     change = mod_chanmode_alloc(argc-1);
1113     for (arg = 1, count = 0; arg < argc; ++arg) {
1114         struct userNode *victim;
1115         struct modeNode *mn;
1116         if (!(victim = GetUserH(argv[arg])))
1117             continue;
1118         if (!(mn =  GetUserMode(channel, victim)))
1119             continue;
1120         if (mn->modes & MODE_CHANOP)
1121             continue;
1122         change->args[count].mode = MODE_CHANOP;
1123         change->args[count++].u.member = mn;
1124     }
1125     if (count) {
1126         change->argc = count;
1127         modcmd_chanmode_announce(change);
1128     }
1129     mod_chanmode_free(change);
1130     reply("OSMSG_OP_DONE");
1131     return 1;
1132 }
1133
1134 static MODCMD_FUNC(cmd_opall)
1135 {
1136     struct mod_chanmode *change;
1137     unsigned int ii, count;
1138
1139     change = mod_chanmode_alloc(channel->members.used);
1140     for (ii = count = 0; ii < channel->members.used; ++ii) {
1141         struct modeNode *mn = channel->members.list[ii];
1142         if (mn->modes & MODE_CHANOP)
1143             continue;
1144         change->args[count].mode = MODE_CHANOP;
1145         change->args[count++].u.member = mn;
1146     }
1147     if (count) {
1148         change->argc = count;
1149         modcmd_chanmode_announce(change);
1150     }
1151     mod_chanmode_free(change);
1152     reply("OSMSG_OPALL_DONE", channel->name);
1153     return 1;
1154 }
1155
1156 static MODCMD_FUNC(cmd_whois)
1157 {
1158     struct userNode *target;
1159     char buffer[128];
1160     int bpos, herelen;
1161
1162 #ifdef WITH_PROTOCOL_P10
1163     if (argv[1][0] == '*')
1164         target = GetUserN(argv[1]+1);
1165     else
1166 #endif
1167     target = GetUserH(argv[1]);
1168     if (!target) {
1169         reply("MSG_NICK_UNKNOWN", argv[1]);
1170         return 0;
1171     }
1172     reply("OSMSG_WHOIS_NICK", target->nick);
1173     reply("OSMSG_WHOIS_HOST", target->ident, target->hostname);
1174     if (IsFakeHost(target))
1175         reply("OSMSG_WHOIS_FAKEHOST", target->fakehost);
1176     reply("OSMSG_WHOIS_IP", inet_ntoa(target->ip));
1177     if (target->modes) {
1178         bpos = 0;
1179 #define buffer_cat(str) (herelen = strlen(str), memcpy(buffer+bpos, str, herelen), bpos += herelen)
1180         if (IsInvisible(target)) buffer[bpos++] = 'i';
1181         if (IsWallOp(target)) buffer[bpos++] = 'w';
1182         if (IsOper(target)) buffer[bpos++] = 'o';
1183         if (IsGlobal(target)) buffer[bpos++] = 'g';
1184         if (IsServNotice(target)) buffer[bpos++] = 's';
1185         if (IsHelperIrcu(target)) buffer[bpos++] = 'h';
1186         if (IsService(target)) buffer[bpos++] = 'k';
1187         if (IsDeaf(target)) buffer[bpos++] = 'd';
1188         if (IsHiddenHost(target)) buffer[bpos++] = 'x';
1189         if (IsGagged(target)) buffer_cat(" (gagged)");
1190         if (IsRegistering(target)) buffer_cat(" (registered account)");
1191         buffer[bpos] = 0;
1192         if (bpos > 0)
1193             reply("OSMSG_WHOIS_MODES", buffer);
1194     }
1195     reply("OSMSG_WHOIS_INFO", target->info);
1196 #ifdef WITH_PROTOCOL_P10
1197     reply("OSMSG_WHOIS_NUMERIC", target->numeric);
1198 #endif
1199     reply("OSMSG_WHOIS_SERVER", target->uplink->name);
1200     reply("OSMSG_WHOIS_ACCOUNT", (target->handle_info ? target->handle_info->handle : "Not authenticated"));
1201     intervalString(buffer, now - target->timestamp, user->handle_info);
1202     reply("OSMSG_WHOIS_NICK_AGE", buffer);
1203     if (target->channels.used <= MAX_CHANNELS_WHOIS)
1204         opserv_ison(user, target, "OSMSG_WHOIS_CHANNELS");
1205     else
1206         reply("OSMSG_WHOIS_HIDECHANS");
1207     return 1;
1208 }
1209
1210 static MODCMD_FUNC(cmd_unban)
1211 {
1212     struct mod_chanmode change;
1213     mod_chanmode_init(&change);
1214     change.argc = 1;
1215     change.args[0].mode = MODE_REMOVE | MODE_BAN;
1216     change.args[0].u.hostmask = argv[1];
1217     modcmd_chanmode_announce(&change);
1218     reply("OSMSG_UNBAN_DONE", channel->name);
1219     return 1;
1220 }
1221
1222 static MODCMD_FUNC(cmd_voiceall)
1223 {
1224     struct mod_chanmode *change;
1225     unsigned int ii, count;
1226
1227     change = mod_chanmode_alloc(channel->members.used);
1228     for (ii = count = 0; ii < channel->members.used; ++ii) {
1229         struct modeNode *mn = channel->members.list[ii];
1230         if (mn->modes & (MODE_CHANOP|MODE_VOICE))
1231             continue;
1232         change->args[count].mode = MODE_VOICE;
1233         change->args[count++].u.member = mn;
1234     }
1235     if (count) {
1236         change->argc = count;
1237         modcmd_chanmode_announce(change);
1238     }
1239     mod_chanmode_free(change);
1240     reply("OSMSG_CHANNEL_VOICED", channel->name);
1241     return 1;
1242 }
1243
1244 static MODCMD_FUNC(cmd_devoiceall)
1245 {
1246     struct mod_chanmode *change;
1247     unsigned int ii, count;
1248
1249     change = mod_chanmode_alloc(channel->members.used);
1250     for (ii = count = 0; ii < channel->members.used; ++ii) {
1251         struct modeNode *mn = channel->members.list[ii];
1252         if (!(mn->modes & MODE_VOICE))
1253             continue;
1254         change->args[count].mode = MODE_REMOVE | MODE_VOICE;
1255         change->args[count++].u.member = mn;
1256     }
1257     if (count) {
1258         change->argc = count;
1259         modcmd_chanmode_announce(change);
1260     }
1261     mod_chanmode_free(change);
1262     reply("OSMSG_CHANNEL_DEVOICED", channel->name);
1263     return 1;
1264 }
1265
1266 static MODCMD_FUNC(cmd_stats_bad) {
1267     dict_iterator_t it;
1268     unsigned int ii, end, here_len;
1269     char buffer[400];
1270
1271     /* Show the bad word list.. */
1272     for (ii=end=0; ii<opserv_bad_words->used; ii++) {
1273         here_len = strlen(opserv_bad_words->list[ii]);
1274         if ((end + here_len + 2) > sizeof(buffer)) {
1275             buffer[end] = 0;
1276             reply("OSMSG_BADWORD_LIST", buffer);
1277             end = 0;
1278         }
1279         memcpy(buffer+end, opserv_bad_words->list[ii], here_len);
1280         end += here_len;
1281         buffer[end++] = ' ';
1282     }
1283     buffer[end] = 0;
1284     reply("OSMSG_BADWORD_LIST", buffer);
1285
1286     /* Show the exemption list.. */
1287     for (it=dict_first(opserv_exempt_channels), end=0; it; it=iter_next(it)) {
1288         here_len = strlen(iter_key(it));
1289         if ((end + here_len + 2) > sizeof(buffer)) {
1290             buffer[end] = 0;
1291             reply("OSMSG_EXEMPTED_LIST", buffer);
1292             end = 0;
1293         }
1294         memcpy(buffer+end, iter_key(it), here_len);
1295         end += here_len;
1296         buffer[end++] = ' ';
1297     }
1298     buffer[end] = 0;
1299     reply("OSMSG_EXEMPTED_LIST", buffer);
1300     return 1;
1301 }
1302
1303 static MODCMD_FUNC(cmd_stats_glines) {
1304     reply("OSMSG_GLINE_COUNT", gline_count());
1305     return 1;
1306 }
1307
1308 static void
1309 trace_links(struct userNode *bot, struct userNode *user, struct server *server, unsigned int depth) {
1310     unsigned int nn, pos;
1311     char buffer[400];
1312
1313     for (nn=1; nn<=depth; nn<<=1) ;
1314     for (pos=0, nn>>=1; nn>1; ) {
1315         nn >>= 1;
1316         buffer[pos++] = (depth & nn) ? ((nn == 1) ? '`' : ' ') : '|';
1317         buffer[pos++] = (nn == 1) ? '-': ' ';
1318     }
1319     buffer[pos] = 0;
1320     send_message(user, bot, "OSMSG_LINKS_SERVER", buffer, server->name, server->clients, server->description);
1321     if (!server->children.used)
1322         return;
1323     for (nn=0; nn<server->children.used-1; nn++) {
1324         trace_links(bot, user, server->children.list[nn], depth<<1);
1325     }
1326     trace_links(bot, user, server->children.list[nn], (depth<<1)|1);
1327 }
1328
1329 static MODCMD_FUNC(cmd_stats_links) {
1330     trace_links(cmd->parent->bot, user, self, 1);
1331     return 1;
1332 }
1333
1334
1335 static MODCMD_FUNC(cmd_stats_max) {
1336     reply("OSMSG_MAX_CLIENTS", max_clients, asctime(localtime(&max_clients_time)));
1337     return 1;
1338 }
1339
1340 static MODCMD_FUNC(cmd_stats_network) {
1341     struct helpfile_table tbl;
1342     unsigned int nn, tot_clients;
1343     dict_iterator_t it;
1344
1345     tot_clients = dict_size(clients);
1346     reply("OSMSG_NETWORK_INFO", tot_clients, invis_clients, curr_opers.used);
1347     tbl.length = dict_size(servers)+1;
1348     tbl.width = 3;
1349     tbl.flags = TABLE_NO_FREE;
1350     tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
1351     tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
1352     tbl.contents[0][0] = "Server Name";
1353     tbl.contents[0][1] = "Clients";
1354     tbl.contents[0][2] = "Load";
1355     for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
1356         struct server *server = iter_data(it);
1357         char *buffer = malloc(32);
1358         tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
1359         tbl.contents[nn][0] = server->name;
1360         tbl.contents[nn][1] = buffer;
1361         sprintf(buffer, "%u", server->clients);
1362         tbl.contents[nn][2] = buffer + 16;
1363         sprintf(buffer+16, "%3.3g%%", ((double)server->clients/tot_clients)*100);
1364         nn++;
1365     }
1366     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1367     for (nn=1; nn<tbl.length; nn++) {
1368         free((char*)tbl.contents[nn][1]);
1369         free(tbl.contents[nn]);
1370     }
1371     free(tbl.contents[0]);
1372     free(tbl.contents);
1373     return 1;
1374 }
1375
1376 static MODCMD_FUNC(cmd_stats_network2) {
1377     struct helpfile_table tbl;
1378     unsigned int nn;
1379     dict_iterator_t it;
1380
1381     tbl.length = dict_size(servers)+1;
1382     tbl.width = 3;
1383     tbl.flags = TABLE_NO_FREE;
1384     tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
1385     tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
1386     tbl.contents[0][0] = "Server Name";
1387     tbl.contents[0][1] = "Numeric";
1388     tbl.contents[0][2] = "Link Time";
1389     for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
1390         struct server *server = iter_data(it);
1391         char *buffer = malloc(64);
1392         int ofs;
1393
1394         tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
1395         tbl.contents[nn][0] = server->name;
1396 #ifdef WITH_PROTOCOL_P10
1397         sprintf(buffer, "%s (%ld)", server->numeric, base64toint(server->numeric, strlen(server->numeric)));
1398 #else
1399         buffer[0] = 0;
1400 #endif
1401         tbl.contents[nn][1] = buffer;
1402         ofs = strlen(buffer) + 1;
1403         intervalString(buffer + ofs, now - server->link, user->handle_info);
1404         if (server->self_burst)
1405             strcat(buffer + ofs, " Bursting");
1406         tbl.contents[nn][2] = buffer + ofs;
1407         nn++;
1408     }
1409     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1410     for (nn=1; nn<tbl.length; nn++) {
1411         free((char*)tbl.contents[nn][1]);
1412         free(tbl.contents[nn]);
1413     }
1414     free(tbl.contents[0]);
1415     free(tbl.contents);
1416     return 1;
1417 }
1418
1419 static MODCMD_FUNC(cmd_stats_reserved) {
1420     dict_iterator_t it;
1421
1422     reply("OSMSG_RESERVED_LIST");
1423     for (it = dict_first(opserv_reserved_nick_dict); it; it = iter_next(it))
1424         send_message_type(4, user, cmd->parent->bot, "%s", iter_key(it));
1425     return 1;
1426 }
1427
1428 static MODCMD_FUNC(cmd_stats_trusted) {
1429     dict_iterator_t it;
1430     struct trusted_host *th;
1431     char length[INTERVALLEN], issued[INTERVALLEN], limit[32];
1432
1433     if (argc > 1) {
1434         th = dict_find(opserv_trusted_hosts, argv[1], NULL);
1435         if (th) {
1436             if (th->issued)
1437                 intervalString(issued, now - th->issued, user->handle_info);
1438             if (th->expires)
1439                 intervalString(length, th->expires - now, user->handle_info);
1440             if (th->limit)
1441                 sprintf(limit, "limit %lu", th->limit);
1442             reply("OSMSG_HOST_IS_TRUSTED",
1443                   th->ipaddr,
1444                   (th->limit ? limit : "no limit"),
1445                   (th->issued ? issued : "some time"),
1446                   (th->issuer ? th->issuer : "<unknown>"),
1447                   (th->expires ? length : "never"),
1448                   (th->reason ? th->reason : "<unknown>"));
1449         } else {
1450             reply("OSMSG_HOST_NOT_TRUSTED", argv[1]);
1451         }
1452     } else {
1453         reply("OSMSG_TRUSTED_LIST");
1454         for (it = dict_first(opserv_trusted_hosts); it; it = iter_next(it)) {
1455             th = iter_data(it);
1456             if (th->issued)
1457                 intervalString(issued, now - th->issued, user->handle_info);
1458             if (th->expires)
1459                 intervalString(length, th->expires - now, user->handle_info);
1460             if (th->limit)
1461                 sprintf(limit, "limit %lu", th->limit);
1462             reply("OSMSG_HOST_IS_TRUSTED", iter_key(it),
1463                   (th->limit ? limit : "no limit"),
1464                   (th->issued ? issued : "some time"),
1465                   (th->issuer ? th->issuer : "<unknown>"),
1466                   (th->expires ? length : "never"),
1467                   (th->reason ? th->reason : "<unknown>"));
1468         }
1469     }
1470     return 1;
1471 }
1472
1473 static MODCMD_FUNC(cmd_stats_uplink) {
1474     extern struct cManagerNode cManager;
1475     struct uplinkNode *uplink;
1476
1477     uplink = cManager.uplink;
1478     reply("OSMSG_UPLINK_START", uplink->name);
1479     reply("OSMSG_UPLINK_ADDRESS", uplink->host, uplink->port);
1480     return 1;
1481 }
1482
1483 static MODCMD_FUNC(cmd_stats_uptime) {
1484     char uptime[INTERVALLEN];
1485     struct tms buf;
1486     extern time_t boot_time;
1487     extern int lines_processed;
1488     static long clocks_per_sec;
1489
1490     if (!clocks_per_sec) {
1491 #if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1492         clocks_per_sec = sysconf(_SC_CLK_TCK);
1493         if (clocks_per_sec <= 0)
1494 #endif
1495         {
1496             log_module(OS_LOG, LOG_ERROR, "Unable to query sysconf(_SC_CLK_TCK), output of 'stats uptime' will be wrong");
1497             clocks_per_sec = CLOCKS_PER_SEC;
1498         }
1499     }
1500     intervalString(uptime, time(NULL)-boot_time, user->handle_info);
1501     times(&buf);
1502     reply("OSMSG_UPTIME_STATS",
1503           uptime, lines_processed,
1504           buf.tms_utime/(double)clocks_per_sec,
1505           buf.tms_stime/(double)clocks_per_sec);
1506     return 1;
1507 }
1508
1509 static MODCMD_FUNC(cmd_stats_alerts) {
1510     dict_iterator_t it;
1511     struct opserv_user_alert *alert;
1512     const char *reaction;
1513
1514     reply("OSMSG_ALERTS_LIST");
1515     for (it = dict_first(opserv_user_alerts); it; it = iter_next(it)) {
1516         alert = iter_data(it);
1517         switch (alert->reaction) {
1518         case REACT_NOTICE: reaction = "notice"; break;
1519         case REACT_KILL: reaction = "kill"; break;
1520         case REACT_GLINE: reaction = "gline"; break;
1521         default: reaction = "<unknown>"; break;
1522         }
1523         reply("OSMSG_ALERT_IS", iter_key(it), alert->owner, reaction, alert->text_discrim);
1524     }
1525     return 1;
1526 }
1527
1528 static MODCMD_FUNC(cmd_stats_gags) {
1529     struct gag_entry *gag;
1530     struct helpfile_table table;
1531     unsigned int nn;
1532
1533     if (!gagList) {
1534         reply("OSMSG_NO_GAGS");
1535         return 1;
1536     }
1537     for (nn=0, gag=gagList; gag; nn++, gag=gag->next) ;
1538     table.length = nn+1;
1539     table.width = 4;
1540     table.flags = TABLE_NO_FREE;
1541     table.contents = calloc(table.length, sizeof(char**));
1542     table.contents[0] = calloc(table.width, sizeof(char*));
1543     table.contents[0][0] = "Mask";
1544     table.contents[0][1] = "Owner";
1545     table.contents[0][2] = "Expires";
1546     table.contents[0][3] = "Reason";
1547     for (nn=1, gag=gagList; gag; nn++, gag=gag->next) {
1548         char expstr[INTERVALLEN];
1549         if (gag->expires)
1550             intervalString(expstr, gag->expires - now, user->handle_info);
1551         else
1552             strcpy(expstr, "Never");
1553         table.contents[nn] = calloc(table.width, sizeof(char*));
1554         table.contents[nn][0] = gag->mask;
1555         table.contents[nn][1] = gag->owner;
1556         table.contents[nn][2] = strdup(expstr);
1557         table.contents[nn][3] = gag->reason;
1558     }
1559     table_send(cmd->parent->bot, user->nick, 0, NULL, table);
1560     for (nn=1; nn<table.length; nn++) {
1561         free((char*)table.contents[nn][2]);
1562         free(table.contents[nn]);
1563     }
1564     free(table.contents[0]);
1565     free(table.contents);
1566     return 1;
1567 }
1568
1569 static MODCMD_FUNC(cmd_stats_timeq) {
1570     reply("OSMSG_TIMEQ_INFO", timeq_size(), timeq_next()-now);
1571     return 1;
1572 }
1573
1574 static MODCMD_FUNC(cmd_stats_warn) {
1575     dict_iterator_t it;
1576
1577     reply("OSMSG_WARN_LISTSTART");
1578     for (it=dict_first(opserv_chan_warn); it; it=iter_next(it))
1579         reply("OSMSG_WARN_LISTENTRY", iter_key(it), (char*)iter_data(it));
1580     reply("OSMSG_WARN_LISTEND");
1581     return 1;
1582 }
1583
1584 #if defined(WITH_MALLOC_SRVX)
1585 static MODCMD_FUNC(cmd_stats_memory) {
1586     extern unsigned long alloc_count, alloc_size;
1587     reply("OSMSG_STATS_MEMORY", alloc_count, alloc_size);
1588     return 1;
1589 }
1590 #endif
1591
1592 static MODCMD_FUNC(cmd_dump)
1593 {
1594     char linedup[MAXLEN], *original;
1595
1596     original = unsplit_string(argv+1, argc-1, NULL);
1597     safestrncpy(linedup, original, sizeof(linedup));
1598     /* assume it's only valid IRC if we can parse it */
1599     if (parse_line(linedup, 1)) {
1600         irc_raw(original);
1601         reply("OSMSG_LINE_DUMPED");
1602     } else
1603         reply("OSMSG_RAW_PARSE_ERROR");
1604     return 1;
1605 }
1606
1607 static MODCMD_FUNC(cmd_raw)
1608 {
1609     char linedup[MAXLEN], *original;
1610
1611     original = unsplit_string(argv+1, argc-1, NULL);
1612     safestrncpy(linedup, original, sizeof(linedup));
1613     /* Try to parse the line before sending it; if it's too wrong,
1614      * maybe it will core us instead of our uplink. */
1615     parse_line(linedup, 1);
1616     irc_raw(original);
1617     reply("OSMSG_LINE_DUMPED");
1618     return 1;
1619 }
1620
1621 static struct userNode *
1622 opserv_add_reserve(struct svccmd *cmd, struct userNode *user, const char *nick, const char *ident, const char *host, const char *desc)
1623 {
1624     struct userNode *resv = GetUserH(nick);
1625     if (resv) {
1626         if (IsService(resv)) {
1627             reply("MSG_SERVICE_IMMUNE", resv->nick);
1628             return NULL;
1629         }
1630         if (resv->handle_info
1631             && resv->handle_info->opserv_level > user->handle_info->opserv_level) {
1632             reply("OSMSG_LEVEL_TOO_LOW");
1633             return NULL;
1634         }
1635     }
1636     if ((resv = AddClone(nick, ident, host, desc))) {
1637         dict_insert(opserv_reserved_nick_dict, resv->nick, resv);
1638     }
1639     return resv;
1640 }
1641
1642 static MODCMD_FUNC(cmd_collide)
1643 {
1644     struct userNode *resv;
1645
1646     resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
1647     if (resv) {
1648         reply("OSMSG_COLLIDED_NICK", resv->nick);
1649         return 1;
1650     } else {
1651         reply("OSMSG_CLONE_FAILED", argv[1]);
1652         return 0;
1653     }
1654 }
1655
1656 static MODCMD_FUNC(cmd_reserve)
1657 {
1658     struct userNode *resv;
1659
1660     resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
1661     if (resv) {
1662         resv->modes |= FLAGS_PERSISTENT;
1663         reply("OSMSG_RESERVED_NICK", resv->nick);
1664         return 1;
1665     } else {
1666         reply("OSMSG_CLONE_FAILED", argv[1]);
1667         return 0;
1668     }
1669 }
1670
1671 static int
1672 free_reserve(char *nick)
1673 {
1674     struct userNode *resv;
1675     unsigned int rlen;
1676     char *reason;
1677
1678     resv = dict_find(opserv_reserved_nick_dict, nick, NULL);
1679     if (!resv)
1680         return 0;
1681
1682     rlen = strlen(resv->nick)+strlen(OSMSG_PART_REASON);
1683     reason = alloca(rlen);
1684     snprintf(reason, rlen, OSMSG_PART_REASON, resv->nick);
1685     DelUser(resv, NULL, 1, reason);
1686     dict_remove(opserv_reserved_nick_dict, nick);
1687     return 1;
1688 }
1689
1690 static MODCMD_FUNC(cmd_unreserve)
1691 {
1692     if (free_reserve(argv[1]))
1693         reply("OSMSG_NICK_UNRESERVED", argv[1]);
1694     else
1695         reply("OSMSG_NOT_RESERVED", argv[1]);
1696     return 1;
1697 }
1698
1699 static void
1700 opserv_part_channel(void *data)
1701 {
1702     DelChannelUser(opserv, data, "Leaving.", 0);
1703 }
1704
1705 static int alert_check_user(const char *key, void *data, void *extra);
1706
1707 static int
1708 opserv_new_user_check(struct userNode *user)
1709 {
1710     struct opserv_hostinfo *ohi;
1711     struct gag_entry *gag;
1712
1713     /* Check to see if we should ignore them entirely. */
1714     if (IsLocal(user) || IsService(user))
1715         return 0;
1716
1717     /* Check for alerts, and stop if we find one that kills them. */
1718     if (dict_foreach(opserv_user_alerts, alert_check_user, user))
1719         return 1;
1720
1721     /* Gag them if appropriate. */
1722     for (gag = gagList; gag; gag = gag->next) {
1723         if (user_matches_glob(user, gag->mask, 1)) {
1724             gag_helper_func(user, NULL);
1725             break;
1726         }
1727     }
1728
1729     /* Add to host info struct */
1730     if (!(ohi = dict_find(opserv_hostinfo_dict, inet_ntoa(user->ip), NULL))) {
1731         ohi = calloc(1, sizeof(*ohi));
1732         dict_insert(opserv_hostinfo_dict, strdup(inet_ntoa(user->ip)), ohi);
1733         userList_init(&ohi->clients);
1734     }
1735     userList_append(&ohi->clients, user);
1736
1737     /* Only warn of new user floods outside of bursts. */
1738     if (!user->uplink->burst) {
1739         if (!policer_conforms(&opserv_conf.new_user_policer, now, 10)) {
1740             if (!new_user_flood) {
1741                 new_user_flood = 1;
1742                 opserv_alert("Warning: Possible new-user flood.");
1743             }
1744         } else {
1745             new_user_flood = 0;
1746         }
1747     }
1748
1749     /* Only warn or G-line if there's an untrusted max and their IP is sane. */
1750     if (opserv_conf.untrusted_max && user->ip.s_addr && (ntohl(user->ip.s_addr) != INADDR_LOOPBACK)) {
1751         struct trusted_host *th = dict_find(opserv_trusted_hosts, inet_ntoa(user->ip), NULL);
1752         unsigned int limit = th ? th->limit : opserv_conf.untrusted_max;
1753         if (!limit) {
1754             /* 0 means unlimited hosts */
1755         } else if (ohi->clients.used == limit) {
1756             unsigned int nn;
1757             for (nn=0; nn<ohi->clients.used; nn++)
1758                 send_message(ohi->clients.list[nn], opserv, "OSMSG_CLONE_WARNING");
1759         } else if (ohi->clients.used > limit) {
1760             char target[18];
1761             sprintf(target, "*@%s", inet_ntoa(user->ip));
1762             gline_add(opserv->nick, target, opserv_conf.clone_gline_duration, "AUTO Excessive connections from a single host.", now, 1);
1763         }
1764     }
1765
1766     return 0;
1767 }
1768
1769 static void
1770 opserv_user_cleanup(struct userNode *user, UNUSED_ARG(struct userNode *killer), UNUSED_ARG(const char *why))
1771 {
1772     struct opserv_hostinfo *ohi;
1773
1774     if (IsLocal(user)) {
1775         /* Try to remove it from the reserved nick dict without
1776          * calling free_reserve, because that would call DelUser(),
1777          * and we'd loop back to here. */
1778         dict_remove(opserv_reserved_nick_dict, user->nick);
1779         return;
1780     }
1781     if ((ohi = dict_find(opserv_hostinfo_dict, inet_ntoa(user->ip), NULL))) {
1782         userList_remove(&ohi->clients, user);
1783         if (ohi->clients.used == 0) dict_remove(opserv_hostinfo_dict, inet_ntoa(user->ip));
1784     }
1785 }
1786
1787 int
1788 opserv_bad_channel(const char *name)
1789 {
1790     unsigned int found;
1791
1792     dict_find(opserv_exempt_channels, name, &found);
1793     if (found)
1794         return 0;
1795
1796     if (gline_find(name))
1797         return 1;
1798
1799     for (found=0; found<opserv_bad_words->used; ++found)
1800         if (irccasestr(name, opserv_bad_words->list[found]))
1801             return 1;
1802
1803     return 0;
1804 }
1805
1806 static void
1807 opserv_shutdown_channel(struct chanNode *channel, const char *reason)
1808 {
1809     struct mod_chanmode *change;
1810     unsigned int nn;
1811
1812     change = mod_chanmode_alloc(2);
1813     change->modes_set = MODE_SECRET | MODE_INVITEONLY;
1814     change->args[0].mode = MODE_CHANOP;
1815     change->args[0].u.member = AddChannelUser(opserv, channel);
1816     change->args[1].mode = MODE_BAN;
1817     change->args[1].u.hostmask = "*!*@*";
1818     mod_chanmode_announce(opserv, channel, change);
1819     mod_chanmode_free(change);
1820     for (nn=channel->members.used; nn>0; ) {
1821         struct modeNode *mNode = channel->members.list[--nn];
1822         if (IsService(mNode->user))
1823             continue;
1824         KickChannelUser(mNode->user, channel, opserv, user_find_message(mNode->user, reason));
1825     }
1826     timeq_add(now + opserv_conf.purge_lock_delay, opserv_part_channel, channel);
1827 }
1828
1829 static void
1830 opserv_channel_check(struct chanNode *newchan)
1831 {
1832     char *warning;
1833
1834     if (!newchan->join_policer.params) {
1835         newchan->join_policer.last_req = now;
1836         newchan->join_policer.params = opserv_conf.join_policer_params;
1837     }
1838     if ((warning = dict_find(opserv_chan_warn, newchan->name, NULL))) {
1839         char message[MAXLEN];
1840         snprintf(message, sizeof(message), "Channel activity warning for channel %s: %s", newchan->name, warning);
1841         global_message(MESSAGE_RECIPIENT_OPERS, message);
1842     }
1843
1844     /* Wait until the join check to shut channels down. */
1845     newchan->bad_channel = opserv_bad_channel(newchan->name);
1846 }
1847
1848 static void
1849 opserv_channel_delete(struct chanNode *chan)
1850 {
1851     timeq_del(0, opserv_part_channel, chan, TIMEQ_IGNORE_WHEN);
1852 }
1853
1854 static int
1855 opserv_join_check(struct modeNode *mNode)
1856 {
1857     struct userNode *user = mNode->user;
1858     struct chanNode *channel = mNode->channel;
1859     const char *msg;
1860
1861     if (IsService(user))
1862         return 0;
1863
1864     dict_foreach(opserv_channel_alerts, alert_check_user, user);
1865
1866     if (channel->bad_channel) {
1867         opserv_debug("Found $b%s$b in bad-word channel $b%s$b; removing the user.", user->nick, channel->name);
1868         if (channel->name[0] != '#')
1869             DelUser(user, opserv, 1, "OSMSG_ILLEGAL_KILL_REASON");
1870         else if (!GetUserMode(channel, opserv))
1871             opserv_shutdown_channel(channel, "OSMSG_ILLEGAL_REASON");
1872         else {
1873             send_message(user, opserv, "OSMSG_ILLEGAL_CHANNEL", channel->name);
1874             msg = user_find_message(user, "OSMSG_ILLEGAL_REASON");
1875             KickChannelUser(user, channel, opserv, msg);
1876         }
1877         return 1;
1878     }
1879
1880     if (user->uplink->burst)
1881         return 0;
1882     if (policer_conforms(&channel->join_policer, now, 1.0)) {
1883         channel->join_flooded = 0;
1884         return 0;
1885     }
1886     if (!channel->join_flooded) {
1887         /* Don't moderate the channel unless it is activated and
1888            the number of users in the channel is over the threshold. */
1889         struct mod_chanmode change;
1890         mod_chanmode_init(&change);
1891         channel->join_flooded = 1;
1892         if (opserv_conf.join_flood_moderate && (channel->members.used > opserv_conf.join_flood_moderate_threshold)) {
1893             if (!GetUserMode(channel, opserv)) {
1894                 /* If we aren't in the channel, join it. */
1895                 change.args[0].mode = MODE_CHANOP;
1896                 change.args[0].u.member = AddChannelUser(opserv, channel);
1897                 change.argc++;
1898             }
1899             if (!(channel->modes & MODE_MODERATED))
1900                 change.modes_set |= MODE_MODERATED;
1901             if (change.modes_set || change.argc)
1902                 mod_chanmode_announce(opserv, channel, &change);
1903             send_target_message(0, channel->name, opserv, "OSMSG_FLOOD_MODERATE");
1904             opserv_alert("Warning: Possible join flood in %s (currently %d users; channel moderated).", channel->name, channel->members.used);
1905         } else {
1906             opserv_alert("Warning: Possible join flood in %s (currently %d users).", channel->name, channel->members.used);
1907         }
1908     }
1909     log_module(OS_LOG, LOG_INFO, "Join to %s during flood: "IDENT_FORMAT, channel->name, IDENT_DATA(user));
1910     return 0;
1911 }
1912
1913 static int
1914 opserv_add_bad_word(struct svccmd *cmd, struct userNode *user, const char *new_bad) {
1915     unsigned int bad_idx;
1916
1917     for (bad_idx = 0; bad_idx < opserv_bad_words->used; ++bad_idx) {
1918         char *orig_bad = opserv_bad_words->list[bad_idx];
1919         if (irccasestr(new_bad, orig_bad)) {
1920             if (user)
1921                 reply("OSMSG_BAD_REDUNDANT", new_bad, orig_bad);
1922             return 0;
1923         } else if (irccasestr(orig_bad, new_bad)) {
1924             if (user)
1925                 reply("OSMSG_BAD_GROWING", orig_bad, new_bad);
1926             free(orig_bad);
1927             opserv_bad_words->list[bad_idx] = strdup(new_bad);
1928             for (bad_idx++; bad_idx < opserv_bad_words->used; bad_idx++) {
1929                 orig_bad = opserv_bad_words->list[bad_idx];
1930                 if (!irccasestr(orig_bad, new_bad))
1931                     continue;
1932                 if (user)
1933                     reply("OSMSG_BAD_NUKING", orig_bad);
1934                 string_list_delete(opserv_bad_words, bad_idx);
1935                 bad_idx--;
1936                 free(orig_bad);
1937             }
1938             return 1;
1939         }
1940     }
1941     string_list_append(opserv_bad_words, strdup(new_bad));
1942     if (user)
1943         reply("OSMSG_ADDED_BAD", new_bad);
1944     return 1;
1945 }
1946
1947 static MODCMD_FUNC(cmd_addbad)
1948 {
1949     unsigned int arg, count;
1950     dict_iterator_t it;
1951     int bad_found, exempt_found;
1952
1953     /* Create the bad word if it doesn't exist. */
1954     bad_found = !opserv_add_bad_word(cmd, user, argv[1]);
1955
1956     /* Look for exception modifiers. */
1957     for (arg=2; arg<argc; arg++) {
1958         if (!irccasecmp(argv[arg], "except")) {
1959             reply("MSG_DEPRECATED_COMMAND", "addbad ... except", "addexempt");
1960             if (++arg > argc) {
1961                 reply("MSG_MISSING_PARAMS", "except");
1962                 break;
1963             }
1964             for (count = 0; (arg < argc) && IsChannelName(argv[arg]); arg++) {
1965                 dict_find(opserv_exempt_channels, argv[arg], &exempt_found);
1966                 if (!exempt_found) {
1967                     dict_insert(opserv_exempt_channels, strdup(argv[arg]), NULL);
1968                     count++;
1969                 }
1970             }
1971             reply("OSMSG_ADDED_EXEMPTIONS", count);
1972         } else {
1973             reply("MSG_DEPRECATED_COMMAND", "addbad (with modifiers)", "addbad");
1974             reply("OSMSG_BAD_MODIFIER", argv[arg]);
1975         }
1976     }
1977
1978     /* Scan for existing channels that match the new bad word. */
1979     if (!bad_found) {
1980         for (it = dict_first(channels); it; it = iter_next(it)) {
1981             struct chanNode *channel = iter_data(it);
1982
1983             if (!opserv_bad_channel(channel->name))
1984                 continue;
1985             channel->bad_channel = 1;
1986             if (channel->name[0] == '#')
1987                 opserv_shutdown_channel(channel, "OSMSG_ILLEGAL_REASON");
1988             else {
1989                 unsigned int nn;
1990                 for (nn=0; nn<channel->members.used; nn++) {
1991                     struct userNode *user = channel->members.list[nn]->user;
1992                     DelUser(user, cmd->parent->bot, 1, "OSMSG_ILLEGAL_KILL_REASON");
1993                 }
1994             }
1995         }
1996     }
1997
1998     return 1;
1999 }
2000
2001 static MODCMD_FUNC(cmd_delbad)
2002 {
2003     dict_iterator_t it;
2004     unsigned int nn;
2005
2006     for (nn=0; nn<opserv_bad_words->used; nn++) {
2007         if (!irccasecmp(opserv_bad_words->list[nn], argv[1])) {
2008             string_list_delete(opserv_bad_words, nn);
2009             for (it = dict_first(channels); it; it = iter_next(it)) {
2010                 channel = iter_data(it);
2011                 if (irccasestr(channel->name, argv[1])
2012                     && !opserv_bad_channel(channel->name)) {
2013                     DelChannelUser(cmd->parent->bot, channel, "Channel name no longer contains a bad word.", 1);
2014                     timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
2015                     channel->bad_channel = 0;
2016                 }
2017             }
2018             reply("OSMSG_REMOVED_BAD", argv[1]);
2019             return 1;
2020         }
2021     }
2022     reply("OSMSG_NOT_BAD_WORD", argv[1]);
2023     return 0;
2024 }
2025
2026 static MODCMD_FUNC(cmd_addexempt)
2027 {
2028     const char *chanName;
2029
2030     if ((argc > 1) && IsChannelName(argv[1])) {
2031         chanName = argv[1];
2032     } else {
2033         reply("MSG_NOT_CHANNEL_NAME");
2034         OPSERV_SYNTAX();
2035         return 0;
2036     }
2037     dict_insert(opserv_exempt_channels, strdup(chanName), NULL);
2038     channel = GetChannel(chanName);
2039     if (channel) {
2040         if (channel->bad_channel) {
2041             DelChannelUser(cmd->parent->bot, channel, "Channel is now exempt from bad-word checking.", 1);
2042             timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
2043         }
2044         channel->bad_channel = 0;
2045     }
2046     reply("OSMSG_ADDED_EXEMPTION", chanName);
2047     return 1;
2048 }
2049
2050 static MODCMD_FUNC(cmd_delexempt)
2051 {
2052     const char *chanName;
2053
2054     if ((argc > 1) && IsChannelName(argv[1])) {
2055         chanName = argv[1];
2056     } else {
2057         reply("MSG_NOT_CHANNEL_NAME");
2058         OPSERV_SYNTAX();
2059         return 0;
2060     }
2061     if (!dict_remove(opserv_exempt_channels, chanName)) {
2062         reply("OSMSG_NOT_EXEMPT", chanName);
2063         return 0;
2064     }
2065     reply("OSMSG_REMOVED_EXEMPTION", chanName);
2066     return 1;
2067 }
2068
2069 static void
2070 opserv_expire_trusted_host(void *data)
2071 {
2072     struct trusted_host *th = data;
2073     dict_remove(opserv_trusted_hosts, th->ipaddr);
2074 }
2075
2076 static void
2077 opserv_add_trusted_host(const char *ipaddr, unsigned int limit, const char *issuer, time_t issued, time_t expires, const char *reason)
2078 {
2079     struct trusted_host *th;
2080     th = calloc(1, sizeof(*th));
2081     if (!th)
2082         return;
2083     th->ipaddr = strdup(ipaddr);
2084     th->reason = reason ? strdup(reason) : NULL;
2085     th->issuer = issuer ? strdup(issuer) : NULL;
2086     th->issued = issued;
2087     th->limit = limit;
2088     th->expires = expires;
2089     dict_insert(opserv_trusted_hosts, th->ipaddr, th);
2090     if (th->expires)
2091         timeq_add(th->expires, opserv_expire_trusted_host, th);
2092 }
2093
2094 static void
2095 free_trusted_host(void *data)
2096 {
2097     struct trusted_host *th = data;
2098     free(th->ipaddr);
2099     free(th->reason);
2100     free(th->issuer);
2101     free(th);
2102 }
2103
2104 static MODCMD_FUNC(cmd_addtrust)
2105 {
2106     unsigned long interval;
2107     char *reason, *tmp;
2108     struct in_addr tmpaddr;
2109     unsigned int count;
2110
2111     if (dict_find(opserv_trusted_hosts, argv[1], NULL)) {
2112         reply("OSMSG_ALREADY_TRUSTED", argv[1]);
2113         return 0;
2114     }
2115
2116     if (!inet_aton(argv[1], &tmpaddr)) {
2117         reply("OSMSG_BAD_IP", argv[1]);
2118         return 0;
2119     }
2120
2121     count = strtoul(argv[2], &tmp, 10);
2122     if (*tmp != '\0') {
2123         reply("OSMSG_BAD_NUMBER", argv[2]);
2124         return 0;
2125     }
2126
2127     interval = ParseInterval(argv[3]);
2128     if (!interval && strcmp(argv[3], "0")) {
2129         reply("MSG_INVALID_DURATION", argv[3]);
2130         return 0;
2131     }
2132
2133     reason = unsplit_string(argv+4, argc-4, NULL);
2134     opserv_add_trusted_host(argv[1], count, user->handle_info->handle, now, interval ? (now + interval) : 0, reason);
2135     reply("OSMSG_ADDED_TRUSTED");
2136     return 1;
2137 }
2138
2139 static MODCMD_FUNC(cmd_edittrust)
2140 {
2141     unsigned long interval;
2142     struct trusted_host *th;
2143     char *reason, *tmp;
2144     unsigned int count;
2145
2146     th = dict_find(opserv_trusted_hosts, argv[1], NULL);
2147     if (!th) {
2148         reply("OSMSG_NOT_TRUSTED", argv[1]);
2149         return 0;
2150     }
2151     count = strtoul(argv[2], &tmp, 10);
2152     if (!count || *tmp) {
2153         reply("OSMSG_BAD_NUMBER", argv[2]);
2154         return 0;
2155     }
2156     interval = ParseInterval(argv[3]);
2157     if (!interval && strcmp(argv[3], "0")) {
2158         reply("MSG_INVALID_DURATION", argv[3]);
2159         return 0;
2160     }
2161     reason = unsplit_string(argv+4, argc-4, NULL);
2162     if (th->expires)
2163         timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
2164
2165     free(th->reason);
2166     th->reason = strdup(reason);
2167     free(th->issuer);
2168     th->issuer = strdup(user->handle_info->handle);
2169     th->issued = now;
2170     th->limit = count;
2171     if (interval) {
2172         th->expires = now + interval;
2173         timeq_add(th->expires, opserv_expire_trusted_host, th);
2174     } else
2175         th->expires = 0;
2176     reply("OSMSG_UPDATED_TRUSTED", th->ipaddr);
2177     return 1;
2178 }
2179
2180 static MODCMD_FUNC(cmd_deltrust)
2181 {
2182     unsigned int n;
2183
2184     for (n=1; n<argc; n++) {
2185         struct trusted_host *th = dict_find(opserv_trusted_hosts, argv[n], NULL);
2186         if (!th)
2187             continue;
2188         if (th->expires)
2189             timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
2190         dict_remove(opserv_trusted_hosts, argv[n]);
2191     }
2192     reply("OSMSG_REMOVED_TRUSTED");
2193     return 1;
2194 }
2195
2196 /* This doesn't use dict_t because it's a little simpler to open-code the
2197  * comparisons (and simpler arg-passing for the ADD subcommand).
2198  */
2199 static MODCMD_FUNC(cmd_clone)
2200 {
2201     int i;
2202     struct userNode *clone;
2203
2204     clone = GetUserH(argv[2]);
2205     if (!irccasecmp(argv[1], "ADD")) {
2206         char *userinfo;
2207         char ident[USERLEN+1];
2208
2209         if (argc < 5) {
2210             reply("MSG_MISSING_PARAMS", argv[1]);
2211             OPSERV_SYNTAX();
2212             return 0;
2213         }
2214         if (clone) {
2215             reply("OSMSG_CLONE_EXISTS", argv[2]);
2216             return 0;
2217         }
2218         userinfo = unsplit_string(argv+4, argc-4, NULL);
2219         for (i=0; argv[3][i] && (i<USERLEN); i++) {
2220             if (argv[3][i] == '@') {
2221                 ident[i++] = 0;
2222                 break;
2223             } else {
2224                 ident[i] = argv[3][i];
2225             }
2226         }
2227         if (!argv[3][i] || (i==USERLEN)) {
2228             reply("OSMSG_NOT_A_HOSTMASK");
2229             return 0;
2230         }
2231         if (!(clone = AddClone(argv[2], ident, argv[3]+i, userinfo))) {
2232             reply("OSMSG_CLONE_FAILED", argv[2]);
2233             return 0;
2234         }
2235         reply("OSMSG_CLONE_ADDED", clone->nick);
2236         return 1;
2237     }
2238     if (!clone) {
2239         reply("MSG_NICK_UNKNOWN", argv[2]);
2240         return 0;
2241     }
2242     if (clone->uplink != self || IsService(clone)) {
2243         reply("OSMSG_NOT_A_CLONE", clone->nick);
2244         return 0;
2245     }
2246     if (!irccasecmp(argv[1], "REMOVE")) {
2247         const char *reason;
2248         if (argc > 3) {
2249             reason = unsplit_string(argv+3, argc-3, NULL);
2250         } else {
2251             char *tmp;
2252             tmp = alloca(strlen(clone->nick) + strlen(OSMSG_PART_REASON));
2253             sprintf(tmp, OSMSG_PART_REASON, clone->nick);
2254             reason = tmp;
2255         }
2256         DelUser(clone, NULL, 1, reason);
2257         reply("OSMSG_CLONE_REMOVED", argv[2]);
2258         return 1;
2259     }
2260     if (argc < 4) {
2261         reply("MSG_MISSING_PARAMS", argv[1]);
2262         OPSERV_SYNTAX();
2263         return 0;
2264     }
2265     channel = GetChannel(argv[3]);
2266     if (!irccasecmp(argv[1], "JOIN")) {
2267         if (!channel
2268             && !(channel = AddChannel(argv[3], now, NULL, NULL))) {
2269             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2270             return 0;
2271         }
2272         AddChannelUser(clone, channel);
2273         reply("OSMSG_CLONE_JOINED", clone->nick, channel->name);
2274         return 1;
2275     }
2276     if (!irccasecmp(argv[1], "PART")) {
2277         if (!channel) {
2278             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2279             return 0;
2280         }
2281         if (!GetUserMode(channel, clone)) {
2282             reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
2283             return 0;
2284         }
2285         reply("OSMSG_CLONE_PARTED", clone->nick, channel->name);
2286         DelChannelUser(clone, channel, "Leaving.", 0);
2287         return 1;
2288     }
2289     if (!irccasecmp(argv[1], "OP")) {
2290         struct mod_chanmode change;
2291         if (!channel) {
2292             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2293             return 0;
2294         }
2295         mod_chanmode_init(&change);
2296         change.argc = 1;
2297         change.args[0].mode = MODE_CHANOP;
2298         change.args[0].u.member = GetUserMode(channel, clone);
2299         if (!change.args[0].u.member) {
2300             reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
2301             return 0;
2302         }
2303         modcmd_chanmode_announce(&change);
2304         reply("OSMSG_OPS_GIVEN", channel->name, clone->nick);
2305         return 1;
2306     }
2307     if (argc < 5) {
2308         reply("MSG_MISSING_PARAMS", argv[1]);
2309         OPSERV_SYNTAX();
2310         return 0;
2311     }
2312     if (!irccasecmp(argv[1], "SAY")) {
2313         char *text = unsplit_string(argv+4, argc-4, NULL);
2314         irc_privmsg(clone, argv[3], text);
2315         reply("OSMSG_CLONE_SAID", clone->nick, argv[3]);
2316         return 1;
2317     }
2318     reply("OSMSG_UNKNOWN_SUBCOMMAND", argv[1], argv[0]);
2319     return 0;
2320 }
2321
2322 static struct helpfile_expansion
2323 opserv_help_expand(const char *variable)
2324 {
2325     extern struct userNode *message_source;
2326     struct helpfile_expansion exp;
2327     struct service *service;
2328     struct svccmd *cmd;
2329     dict_iterator_t it;
2330     int row;
2331     unsigned int level;
2332
2333     if (!(service = service_find(message_source->nick))) {
2334         exp.type = HF_STRING;
2335         exp.value.str = NULL;
2336     } else if (!irccasecmp(variable, "index")) {
2337         exp.type = HF_TABLE;
2338         exp.value.table.length = 1;
2339         exp.value.table.width = 2;
2340         exp.value.table.flags = TABLE_REPEAT_HEADERS | TABLE_REPEAT_ROWS;
2341         exp.value.table.contents = calloc(dict_size(service->commands)+1, sizeof(char**));
2342         exp.value.table.contents[0] = calloc(exp.value.table.width, sizeof(char*));
2343         exp.value.table.contents[0][0] = "Command";
2344         exp.value.table.contents[0][1] = "Level";
2345         for (it=dict_first(service->commands); it; it=iter_next(it)) {
2346             cmd = iter_data(it);
2347             row = exp.value.table.length++;
2348             exp.value.table.contents[row] = calloc(exp.value.table.width, sizeof(char*));
2349             exp.value.table.contents[row][0] = iter_key(it);
2350             level = cmd->min_opserv_level;
2351             if (!level_strings[level]) {
2352                 level_strings[level] = malloc(16);
2353                 snprintf(level_strings[level], 16, "%3d", level);
2354             }
2355             exp.value.table.contents[row][1] = level_strings[level];
2356         }
2357     } else if (!strncasecmp(variable, "level", 5)) {
2358         cmd = dict_find(service->commands, variable+6, NULL);
2359         exp.type = HF_STRING;
2360         if (cmd) {
2361             level = cmd->min_opserv_level;
2362             exp.value.str = malloc(16);
2363             snprintf(exp.value.str, 16, "%3d", level);
2364         } else {
2365             exp.value.str = NULL;
2366         }
2367     } else {
2368         exp.type = HF_STRING;
2369         exp.value.str = NULL;
2370     }
2371     return exp;
2372 }
2373
2374 struct modcmd *
2375 opserv_define_func(const char *name, modcmd_func_t *func, int min_level, int reqchan, int min_argc)
2376 {
2377     char buf[16], *flags = NULL;
2378     unsigned int iflags = 0;
2379     sprintf(buf, "%d", min_level);
2380     switch (reqchan) {
2381     case 1: flags = "+acceptchan"; break;
2382     case 3: flags = "+acceptpluschan"; /* fall through */
2383     case 2: iflags = MODCMD_REQUIRE_CHANNEL; break;
2384     }
2385     if (flags) {
2386         return modcmd_register(opserv_module, name, func, min_argc, iflags, "level", buf, "flags", flags, "flags", "+oper", NULL);
2387     } else {
2388         return modcmd_register(opserv_module, name, func, min_argc, iflags, "level", buf, "flags", "+oper", NULL);
2389     }
2390 }
2391
2392 int add_reserved(const char *key, void *data, void *extra)
2393 {
2394     struct record_data *rd = data;
2395     const char *ident, *hostname, *desc;
2396     struct userNode *reserve;
2397     ident = database_get_data(rd->d.object, KEY_IDENT, RECDB_QSTRING);
2398     if (!ident) {
2399         log_module(OS_LOG, LOG_ERROR, "Missing ident for reserve of %s", key);
2400         return 0;
2401     }
2402     hostname = database_get_data(rd->d.object, KEY_HOSTNAME, RECDB_QSTRING);
2403     if (!hostname) {
2404         log_module(OS_LOG, LOG_ERROR, "Missing hostname for reserve of %s", key);
2405         return 0;
2406     }
2407     desc = database_get_data(rd->d.object, KEY_DESC, RECDB_QSTRING);
2408     if (!desc) {
2409         log_module(OS_LOG, LOG_ERROR, "Missing description for reserve of %s", key);
2410         return 0;
2411     }
2412     if ((reserve = AddClone(key, ident, hostname, desc))) {
2413         reserve->modes |= FLAGS_PERSISTENT;
2414         dict_insert(extra, reserve->nick, reserve);
2415     }
2416     return 0;
2417 }
2418
2419 static unsigned int
2420 foreach_matching_user(const char *hostmask, discrim_search_func func, void *extra)
2421 {
2422     discrim_t discrim;
2423     char *dupmask;
2424     unsigned int matched;
2425
2426     if (!self->uplink) return 0;
2427     discrim = calloc(1, sizeof(*discrim));
2428     discrim->limit = dict_size(clients);
2429     discrim->max_level = ~0;
2430     discrim->max_ts = now;
2431     discrim->max_channels = INT_MAX;
2432     discrim->authed = -1;
2433     discrim->info_space = -1;
2434     dupmask = strdup(hostmask);
2435     if (split_ircmask(dupmask, &discrim->mask_nick, &discrim->mask_ident, &discrim->mask_host)) {
2436         if (discrim->mask_host && !discrim->mask_host[strspn(discrim->mask_host, "0123456789.?*")]) {
2437             if (!parse_ipmask(discrim->mask_host, &discrim->ip_addr, &discrim->ip_mask)) {
2438                 log_module(OS_LOG, LOG_ERROR, "Couldn't parse %s as an IP mask!", discrim->mask_host);
2439                 free(discrim);
2440                 free(dupmask);
2441                 return 0;
2442             }
2443             discrim->mask_host = 0;
2444         }
2445         matched = opserv_discrim_search(discrim, func, extra);
2446     } else {
2447         log_module(OS_LOG, LOG_ERROR, "Couldn't split IRC mask for gag %s!", hostmask);
2448         matched = 0;
2449     }
2450     free(discrim);
2451     free(dupmask);
2452     return matched;
2453 }
2454
2455 static unsigned int
2456 gag_free(struct gag_entry *gag)
2457 {
2458     unsigned int ungagged;
2459
2460     /* Remove from gag list */
2461     if (gagList == gag) {
2462         gagList = gag->next;
2463     } else {
2464         struct gag_entry *prev;
2465         for (prev = gagList; prev->next != gag; prev = prev->next) ;
2466         prev->next = gag->next;
2467     }
2468
2469     ungagged = foreach_matching_user(gag->mask, ungag_helper_func, NULL);
2470
2471     /* Deallocate storage */
2472     free(gag->reason);
2473     free(gag->owner);
2474     free(gag->mask);
2475     free(gag);
2476
2477     return ungagged;
2478 }
2479
2480 static void
2481 gag_expire(void *data)
2482 {
2483     gag_free(data);
2484 }
2485
2486 unsigned int
2487 gag_create(const char *mask, const char *owner, const char *reason, time_t expires)
2488 {
2489     struct gag_entry *gag;
2490
2491     /* Create gag and put it into linked list */
2492     gag = calloc(1, sizeof(*gag));
2493     gag->mask = strdup(mask);
2494     gag->owner = strdup(owner ? owner : "<unknown>");
2495     gag->reason = strdup(reason ? reason : "<unknown>");
2496     gag->expires = expires;
2497     if (gag->expires)
2498         timeq_add(gag->expires, gag_expire, gag);
2499     gag->next = gagList;
2500     gagList = gag;
2501
2502     /* If we're linked, see if who the gag applies to */
2503     return foreach_matching_user(mask, gag_helper_func, gag);
2504 }
2505
2506 static int
2507 add_gag_helper(const char *key, void *data, UNUSED_ARG(void *extra))
2508 {
2509     struct record_data *rd = data;
2510     char *owner, *reason, *expstr;
2511     time_t expires;
2512
2513     owner = database_get_data(rd->d.object, KEY_OWNER, RECDB_QSTRING);
2514     reason = database_get_data(rd->d.object, KEY_REASON, RECDB_QSTRING);
2515     expstr = database_get_data(rd->d.object, KEY_EXPIRES, RECDB_QSTRING);
2516     expires = expstr ? strtoul(expstr, NULL, 0) : 0;
2517     gag_create(key, owner, reason, expires);
2518
2519     return 0;
2520 }
2521
2522 static struct opserv_user_alert *
2523 opserv_add_user_alert(struct userNode *req, const char *name, opserv_alert_reaction reaction, const char *text_discrim)
2524 {
2525     unsigned int wordc;
2526     char *wordv[MAXNUMPARAMS], *discrim_copy;
2527     struct opserv_user_alert *alert;
2528     char *name_dup;
2529
2530     if (dict_find(opserv_user_alerts, name, NULL)) {
2531         send_message(req, opserv, "OSMSG_ALERT_EXISTS", name);
2532         return NULL;
2533     }
2534     alert = malloc(sizeof(*alert));
2535     alert->owner = strdup(req->handle_info ? req->handle_info->handle : req->nick);
2536     alert->text_discrim = strdup(text_discrim);
2537     discrim_copy = strdup(text_discrim); /* save a copy of the discrim */
2538     wordc = split_line(discrim_copy, false, ArrayLength(wordv), wordv);
2539     alert->discrim = opserv_discrim_create(req, wordc, wordv, 0);
2540     if (!alert->discrim) {
2541         free(alert->text_discrim);
2542         free(discrim_copy);
2543         free(alert);
2544         return NULL;
2545     }
2546     alert->split_discrim = discrim_copy;
2547     name_dup = strdup(name);
2548     if (!alert->discrim->reason)
2549         alert->discrim->reason = strdup(name);
2550     alert->reaction = reaction;
2551     dict_insert(opserv_user_alerts, name_dup, alert);
2552     if (alert->discrim->channel)
2553         dict_insert(opserv_channel_alerts, name_dup, alert);
2554     else if (alert->discrim->mask_nick)
2555         dict_insert(opserv_nick_based_alerts, name_dup, alert);
2556     return alert;
2557 }
2558
2559 static int
2560 add_chan_warn(const char *key, void *data, UNUSED_ARG(void *extra))
2561 {
2562     struct record_data *rd = data;
2563     char *reason = GET_RECORD_QSTRING(rd);
2564
2565     /* i hope this can't happen */
2566     if (!reason)
2567         reason = "No Reason";
2568
2569     dict_insert(opserv_chan_warn, strdup(key), strdup(reason));
2570     return 0;
2571 }
2572
2573 static int
2574 add_user_alert(const char *key, void *data, UNUSED_ARG(void *extra))
2575 {
2576     dict_t alert_dict;
2577     const char *discrim, *react, *owner;
2578     opserv_alert_reaction reaction;
2579     struct opserv_user_alert *alert;
2580
2581     if (!(alert_dict = GET_RECORD_OBJECT((struct record_data *)data))) {
2582         log_module(OS_LOG, LOG_ERROR, "Bad type (not a record) for alert %s.", key);
2583         return 1;
2584     }
2585     discrim = database_get_data(alert_dict, KEY_DISCRIM, RECDB_QSTRING);
2586     react = database_get_data(alert_dict, KEY_REACTION, RECDB_QSTRING);
2587     if (!react || !irccasecmp(react, "notice"))
2588         reaction = REACT_NOTICE;
2589     else if (!irccasecmp(react, "kill"))
2590         reaction = REACT_KILL;
2591     else if (!irccasecmp(react, "gline"))
2592         reaction = REACT_GLINE;
2593     else {
2594         log_module(OS_LOG, LOG_ERROR, "Invalid reaction %s for alert %s.", react, key);
2595         return 0;
2596     }
2597     alert = opserv_add_user_alert(opserv, key, reaction, discrim);
2598     if (!alert) {
2599         log_module(OS_LOG, LOG_ERROR, "Unable to create alert %s from database.", key);
2600         return 0;
2601     }
2602     owner = database_get_data(alert_dict, KEY_OWNER, RECDB_QSTRING);
2603     free(alert->owner);
2604     alert->owner = strdup(owner ? owner : "<unknown>");
2605     return 0;
2606 }
2607
2608 static int
2609 trusted_host_read(const char *host, void *data, UNUSED_ARG(void *extra))
2610 {
2611     struct record_data *rd = data;
2612     const char *limit, *str, *reason, *issuer;
2613     time_t issued, expires;
2614
2615     if (rd->type == RECDB_QSTRING) {
2616         /* old style host by itself */
2617         limit = GET_RECORD_QSTRING(rd);
2618         issued = 0;
2619         issuer = NULL;
2620         expires = 0;
2621         reason = NULL;
2622     } else if (rd->type == RECDB_OBJECT) {
2623         dict_t obj = GET_RECORD_OBJECT(rd);
2624         /* new style structure */
2625         limit = database_get_data(obj, KEY_LIMIT, RECDB_QSTRING);
2626         str = database_get_data(obj, KEY_EXPIRES, RECDB_QSTRING);
2627         expires = str ? ParseInterval(str) : 0;
2628         reason = database_get_data(obj, KEY_REASON, RECDB_QSTRING);
2629         issuer = database_get_data(obj, KEY_ISSUER, RECDB_QSTRING);
2630         str = database_get_data(obj, KEY_ISSUED, RECDB_QSTRING);
2631         issued = str ? ParseInterval(str) : 0;
2632     } else
2633         return 0;
2634
2635     if (expires && (expires < now))
2636         return 0;
2637     opserv_add_trusted_host(host, (limit ? strtoul(limit, NULL, 0) : 0), issuer, issued, expires, reason);
2638     return 0;
2639 }
2640
2641 static int
2642 opserv_saxdb_read(struct dict *conf_db)
2643 {
2644     dict_t object;
2645     struct record_data *rd;
2646     dict_iterator_t it;
2647     unsigned int nn;
2648
2649     if ((object = database_get_data(conf_db, KEY_RESERVES, RECDB_OBJECT)))
2650         dict_foreach(object, add_reserved, opserv_reserved_nick_dict);
2651     if ((rd = database_get_path(conf_db, KEY_BAD_WORDS))) {
2652         switch (rd->type) {
2653         case RECDB_STRING_LIST:
2654             /* Add words one by one just in case there are overlaps from an old DB. */
2655             for (nn=0; nn<rd->d.slist->used; ++nn)
2656                 opserv_add_bad_word(NULL, NULL, rd->d.slist->list[nn]);
2657             break;
2658         case RECDB_OBJECT:
2659             for (it=dict_first(rd->d.object); it; it=iter_next(it)) {
2660                 opserv_add_bad_word(NULL, NULL, iter_key(it));
2661                 rd = iter_data(it);
2662                 if (rd->type == RECDB_STRING_LIST)
2663                     for (nn=0; nn<rd->d.slist->used; nn++)
2664                         dict_insert(opserv_exempt_channels, strdup(rd->d.slist->list[nn]), NULL);
2665             }
2666             break;
2667         default:
2668             /* do nothing */;
2669         }
2670     }
2671     if ((rd = database_get_path(conf_db, KEY_EXEMPT_CHANNELS))
2672         && (rd->type == RECDB_STRING_LIST)) {
2673         for (nn=0; nn<rd->d.slist->used; ++nn)
2674             dict_insert(opserv_exempt_channels, strdup(rd->d.slist->list[nn]), NULL);
2675     }
2676     if ((object = database_get_data(conf_db, KEY_MAX_CLIENTS, RECDB_OBJECT))) {
2677         char *str;
2678         if ((str = database_get_data(object, KEY_MAX, RECDB_QSTRING)))
2679             max_clients = atoi(str);
2680         if ((str = database_get_data(object, KEY_TIME, RECDB_QSTRING)))
2681             max_clients_time = atoi(str);
2682     }
2683     if ((object = database_get_data(conf_db, KEY_TRUSTED_HOSTS, RECDB_OBJECT)))
2684         dict_foreach(object, trusted_host_read, opserv_trusted_hosts);
2685     if ((object = database_get_data(conf_db, KEY_GAGS, RECDB_OBJECT)))
2686         dict_foreach(object, add_gag_helper, NULL);
2687     if ((object = database_get_data(conf_db, KEY_ALERTS, RECDB_OBJECT)))
2688         dict_foreach(object, add_user_alert, NULL);
2689     if ((object = database_get_data(conf_db, KEY_WARN, RECDB_OBJECT)))
2690         dict_foreach(object, add_chan_warn, NULL);
2691     return 0;
2692 }
2693
2694 static int
2695 opserv_saxdb_write(struct saxdb_context *ctx)
2696 {
2697     struct string_list *slist;
2698     dict_iterator_t it;
2699
2700     /* reserved nicks */
2701     if (dict_size(opserv_reserved_nick_dict)) {
2702         saxdb_start_record(ctx, KEY_RESERVES, 1);
2703         for (it = dict_first(opserv_reserved_nick_dict); it; it = iter_next(it)) {
2704             struct userNode *user = iter_data(it);
2705             if (!IsPersistent(user)) continue;
2706             saxdb_start_record(ctx, iter_key(it), 0);
2707             saxdb_write_string(ctx, KEY_IDENT, user->ident);
2708             saxdb_write_string(ctx, KEY_HOSTNAME, user->hostname);
2709             saxdb_write_string(ctx, KEY_DESC, user->info);
2710             saxdb_end_record(ctx);
2711         }
2712         saxdb_end_record(ctx);
2713     }
2714     /* bad word set */
2715     if (opserv_bad_words->used) {
2716         saxdb_write_string_list(ctx, KEY_BAD_WORDS, opserv_bad_words);
2717     }
2718     /* insert exempt channel names */
2719     if (dict_size(opserv_exempt_channels)) {
2720         slist = alloc_string_list(dict_size(opserv_exempt_channels));
2721         for (it=dict_first(opserv_exempt_channels); it; it=iter_next(it)) {
2722             string_list_append(slist, strdup(iter_key(it)));
2723         }
2724         saxdb_write_string_list(ctx, KEY_EXEMPT_CHANNELS, slist);
2725         free_string_list(slist);
2726     }
2727     /* trusted hosts takes a little more work */
2728     if (dict_size(opserv_trusted_hosts)) {
2729         saxdb_start_record(ctx, KEY_TRUSTED_HOSTS, 1);
2730         for (it = dict_first(opserv_trusted_hosts); it; it = iter_next(it)) {
2731             struct trusted_host *th = iter_data(it);
2732             saxdb_start_record(ctx, iter_key(it), 0);
2733             if (th->limit) saxdb_write_int(ctx, KEY_LIMIT, th->limit);
2734             if (th->expires) saxdb_write_int(ctx, KEY_EXPIRES, th->expires);
2735             if (th->issued) saxdb_write_int(ctx, KEY_ISSUED, th->issued);
2736             if (th->issuer) saxdb_write_string(ctx, KEY_ISSUER, th->issuer);
2737             if (th->reason) saxdb_write_string(ctx, KEY_REASON, th->reason);
2738             saxdb_end_record(ctx);
2739         }
2740         saxdb_end_record(ctx);
2741     }
2742     /* gags */
2743     if (gagList) {
2744         struct gag_entry *gag;
2745         saxdb_start_record(ctx, KEY_GAGS, 1);
2746         for (gag = gagList; gag; gag = gag->next) {
2747             saxdb_start_record(ctx, gag->mask, 0);
2748             saxdb_write_string(ctx, KEY_OWNER, gag->owner);
2749             saxdb_write_string(ctx, KEY_REASON, gag->reason);
2750             if (gag->expires) saxdb_write_int(ctx, KEY_EXPIRES, gag->expires);
2751             saxdb_end_record(ctx);
2752         }
2753         saxdb_end_record(ctx);
2754     }
2755     /* channel warnings */
2756     if (dict_size(opserv_chan_warn)) {
2757         saxdb_start_record(ctx, KEY_WARN, 0);
2758         for (it = dict_first(opserv_chan_warn); it; it = iter_next(it)) {
2759             saxdb_write_string(ctx, iter_key(it), iter_data(it));
2760         }
2761         saxdb_end_record(ctx);
2762     }
2763     /* alerts */
2764     if (dict_size(opserv_user_alerts)) {
2765         saxdb_start_record(ctx, KEY_ALERTS, 1);
2766         for (it = dict_first(opserv_user_alerts); it; it = iter_next(it)) {
2767             struct opserv_user_alert *alert = iter_data(it);
2768             const char *reaction;
2769             saxdb_start_record(ctx, iter_key(it), 0);
2770             saxdb_write_string(ctx, KEY_DISCRIM, alert->text_discrim);
2771             saxdb_write_string(ctx, KEY_OWNER, alert->owner);
2772             switch (alert->reaction) {
2773             case REACT_NOTICE: reaction = "notice"; break;
2774             case REACT_KILL: reaction = "kill"; break;
2775             case REACT_GLINE: reaction = "gline"; break;
2776             default:
2777                 reaction = NULL;
2778                 log_module(OS_LOG, LOG_ERROR, "Invalid reaction type %d for alert %s (while writing database).", alert->reaction, iter_key(it));
2779                 break;
2780             }
2781             if (reaction) saxdb_write_string(ctx, KEY_REACTION, reaction);
2782             saxdb_end_record(ctx);
2783         }
2784         saxdb_end_record(ctx);
2785     }
2786     /* max clients */
2787     saxdb_start_record(ctx, KEY_MAX_CLIENTS, 0);
2788     saxdb_write_int(ctx, KEY_MAX, max_clients);
2789     saxdb_write_int(ctx, KEY_TIME, max_clients_time);
2790     saxdb_end_record(ctx);
2791     return 0;
2792 }
2793
2794 static int
2795 query_keys_helper(const char *key, UNUSED_ARG(void *data), void *extra)
2796 {
2797     send_message_type(4, extra, opserv, "$b%s$b", key);
2798     return 0;
2799 }
2800
2801 static MODCMD_FUNC(cmd_query)
2802 {
2803     struct record_data *rd;
2804     unsigned int i;
2805     char *nodename;
2806
2807     if (argc < 2) {
2808         reply("OSMSG_OPTION_ROOT");
2809         conf_enum_root(query_keys_helper, user);
2810         return 1;
2811     }
2812
2813     nodename = unsplit_string(argv+1, argc-1, NULL);
2814     if (!(rd = conf_get_node(nodename))) {
2815         reply("OSMSG_UNKNOWN_OPTION", nodename);
2816         return 0;
2817     }
2818
2819     if (rd->type == RECDB_QSTRING)
2820         reply("OSMSG_OPTION_IS", nodename, rd->d.qstring);
2821     else if (rd->type == RECDB_STRING_LIST) {
2822         reply("OSMSG_OPTION_LIST", nodename);
2823         if (rd->d.slist->used)
2824             for (i=0; i<rd->d.slist->used; i++)
2825                 send_message_type(4, user, cmd->parent->bot, "$b%s$b", rd->d.slist->list[i]);
2826         else
2827             reply("OSMSG_OPTION_LIST_EMPTY");
2828     } else if (rd->type == RECDB_OBJECT) {
2829         reply("OSMSG_OPTION_KEYS", nodename);
2830         dict_foreach(rd->d.object, query_keys_helper, user);
2831     }
2832
2833     return 1;
2834 }
2835
2836 static MODCMD_FUNC(cmd_set)
2837 {
2838     struct record_data *rd;
2839
2840     /* I originally wanted to be able to fully manipulate the config
2841        db with this, but i wussed out. feel free to fix this - you'll
2842        need to handle quoted strings which have been split, and likely
2843        invent a syntax for it. -Zoot */
2844
2845     if (!(rd = conf_get_node(argv[1]))) {
2846         reply("OSMSG_SET_NOT_SET", argv[1]);
2847         return 0;
2848     }
2849
2850     if (rd->type != RECDB_QSTRING) {
2851         reply("OSMSG_SET_BAD_TYPE", argv[1]);
2852         return 0;
2853     }
2854
2855     free(rd->d.qstring);
2856     rd->d.qstring = strdup(argv[2]);
2857     conf_call_reload_funcs();
2858     reply("OSMSG_SET_SUCCESS", argv[1], argv[2]);
2859     return 1;
2860 }
2861
2862 static MODCMD_FUNC(cmd_settime)
2863 {
2864     const char *srv_name_mask = "*";
2865     time_t new_time = now;
2866
2867     if (argc > 1)
2868         srv_name_mask = argv[1];
2869     if (argc > 2)
2870         new_time = time(NULL);
2871     irc_settime(srv_name_mask, new_time);
2872     reply("OSMSG_SETTIME_SUCCESS", srv_name_mask);
2873     return 1;
2874 }
2875
2876 static discrim_t
2877 opserv_discrim_create(struct userNode *user, unsigned int argc, char *argv[], int allow_channel)
2878 {
2879     unsigned int i, j;
2880     discrim_t discrim;
2881
2882     discrim = calloc(1, sizeof(*discrim));
2883     discrim->limit = 250;
2884     discrim->max_level = ~0;
2885     discrim->max_ts = INT_MAX;
2886     discrim->domain_depth = 2;
2887     discrim->max_channels = INT_MAX;
2888     discrim->authed = -1;
2889     discrim->info_space = -1;
2890
2891     for (i=0; i<argc; i++) {
2892         if (irccasecmp(argv[i], "log") == 0) {
2893             discrim->option_log = 1;
2894             continue;
2895         }
2896         /* Assume all other criteria require arguments. */
2897         if (i == argc - 1) {
2898             send_message(user, opserv, "MSG_MISSING_PARAMS", argv[i]);
2899             goto fail;
2900         }
2901         if (irccasecmp(argv[i], "mask") == 0) {
2902             if (!is_ircmask(argv[++i])) {
2903                 send_message(user, opserv, "OSMSG_INVALID_IRCMASK", argv[i]);
2904                 goto fail;
2905             }
2906             if (!split_ircmask(argv[i],
2907                                &discrim->mask_nick,
2908                                &discrim->mask_ident,
2909                                &discrim->mask_host)) {
2910                 send_message(user, opserv, "OSMSG_INVALID_IRCMASK", argv[i]);
2911                 goto fail;
2912             }
2913         } else if (irccasecmp(argv[i], "nick") == 0) {
2914             discrim->mask_nick = argv[++i];
2915         } else if (irccasecmp(argv[i], "ident") == 0) {
2916             discrim->mask_ident = argv[++i];
2917         } else if (irccasecmp(argv[i], "host") == 0) {
2918             discrim->mask_host = argv[++i];
2919         } else if (irccasecmp(argv[i], "info") == 0) {
2920             discrim->mask_info = argv[++i];
2921         } else if (irccasecmp(argv[i], "server") == 0) {
2922             discrim->server = argv[++i];
2923         } else if (irccasecmp(argv[i], "ip") == 0) {
2924             j = parse_ipmask(argv[++i], &discrim->ip_addr, &discrim->ip_mask);
2925             if (!j) discrim->ip_mask_str = argv[i];
2926     } else if (irccasecmp(argv[i], "account") == 0) {
2927         if (discrim->authed == 0) {
2928             send_message(user, opserv, "OSMSG_ACCOUNTMASK_AUTHED");
2929             goto fail;
2930         }
2931         discrim->accountmask = argv[++i];
2932         discrim->authed = 1;
2933     } else if (irccasecmp(argv[i], "authed") == 0) {
2934         i++; /* true_string and false_string are macros! */
2935         if (true_string(argv[i])) {
2936             discrim->authed = 1;
2937         } else if (false_string(argv[i])) {
2938             if (discrim->accountmask) {
2939                 send_message(user, opserv, "OSMSG_ACCOUNTMASK_AUTHED");
2940                 goto fail;
2941             }
2942             discrim->authed = 0;
2943         } else {
2944             send_message(user, opserv, "MSG_INVALID_BINARY", argv[i]);
2945             goto fail;
2946         }
2947     } else if (irccasecmp(argv[i], "info_space") == 0) {
2948         /* XXX: A hack because you can't check explicitly for a space through
2949          * any other means */
2950         i++;
2951         if (true_string(argv[i])) {
2952             discrim->info_space = 1;
2953         } else if (false_string(argv[i])) {
2954             discrim->info_space = 0;
2955         } else {
2956             send_message(user, opserv, "MSG_INVALID_BINARY", argv[i]);
2957             goto fail;
2958         }
2959     } else if (irccasecmp(argv[i], "duration") == 0) {
2960         discrim->duration = ParseInterval(argv[++i]);
2961         } else if (irccasecmp(argv[i], "channel") == 0) {
2962             for (j=0, i++; ; j++) {
2963                 switch (argv[i][j]) {
2964                 case '#':
2965                     goto find_channel;
2966                 case '-':
2967                     discrim->chan_no_modes  |= MODE_CHANOP | MODE_VOICE;
2968                     break;
2969                 case '+':
2970                     discrim->chan_req_modes |= MODE_VOICE;
2971                     discrim->chan_no_modes  |= MODE_CHANOP;
2972                     break;
2973                 case '@':
2974                     discrim->chan_req_modes |= MODE_CHANOP;
2975                     break;
2976                 case '\0':
2977                     send_message(user, opserv, "MSG_NOT_CHANNEL_NAME");
2978                     goto fail;
2979                 }
2980             }
2981           find_channel:
2982             discrim->chan_no_modes &= ~discrim->chan_req_modes;
2983             if (!(discrim->channel = GetChannel(argv[i]+j))) {
2984                 /* secretly "allow_channel" now means "if a channel name is
2985                  * specified, require that it currently exist" */
2986                 if (allow_channel) {
2987                     send_message(user, opserv, "MSG_CHANNEL_UNKNOWN", argv[i]);
2988                     goto fail;
2989                 } else {
2990                     discrim->channel = AddChannel(argv[i]+j, now, NULL, NULL);
2991                 }
2992             }
2993             LockChannel(discrim->channel);
2994         } else if (irccasecmp(argv[i], "numchannels") == 0) {
2995             discrim->min_channels = discrim->max_channels = strtoul(argv[++i], NULL, 10);
2996         } else if (irccasecmp(argv[i], "limit") == 0) {
2997             discrim->limit = strtoul(argv[++i], NULL, 10);
2998         } else if (irccasecmp(argv[i], "reason") == 0) {
2999             discrim->reason = strdup(unsplit_string(argv+i+1, argc-i-1, NULL));
3000             i = argc;
3001         } else if (irccasecmp(argv[i], "last") == 0) {
3002             discrim->min_ts = now - ParseInterval(argv[++i]);
3003         } else if ((irccasecmp(argv[i], "linked") == 0)
3004                    || (irccasecmp(argv[i], "nickage") == 0)) {
3005             const char *cmp = argv[++i];
3006             if (cmp[0] == '<') {
3007                 if (cmp[1] == '=') {
3008                     discrim->min_ts = now - ParseInterval(cmp+2);
3009                 } else {
3010                     discrim->min_ts = now - (ParseInterval(cmp+1) - 1);
3011                 }
3012             } else if (cmp[0] == '>') {
3013                 if (cmp[1] == '=') {
3014                     discrim->max_ts = now - ParseInterval(cmp+2);
3015                 } else {
3016                     discrim->max_ts = now - (ParseInterval(cmp+1) - 1);
3017                 }
3018             } else {
3019                 discrim->min_ts = now - ParseInterval(cmp+2);
3020             }
3021         } else if (irccasecmp(argv[i], "access") == 0) {
3022             const char *cmp = argv[++i];
3023             if (cmp[0] == '<') {
3024                 if (discrim->min_level == 0) discrim->min_level = 1;
3025                 if (cmp[1] == '=') {
3026                     discrim->max_level = strtoul(cmp+2, NULL, 0);
3027                 } else {
3028                     discrim->max_level = strtoul(cmp+1, NULL, 0) - 1;
3029                 }
3030             } else if (cmp[0] == '=') {
3031                 discrim->min_level = discrim->max_level = strtoul(cmp+1, NULL, 0);
3032             } else if (cmp[0] == '>') {
3033                 if (cmp[1] == '=') {
3034                     discrim->min_level = strtoul(cmp+2, NULL, 0);
3035                 } else {
3036                     discrim->min_level = strtoul(cmp+1, NULL, 0) + 1;
3037                 }
3038             } else {
3039                 discrim->min_level = strtoul(cmp+2, NULL, 0);
3040             }
3041         } else if ((irccasecmp(argv[i], "abuse") == 0)
3042                    && (irccasecmp(argv[++i], "opers") == 0)) {
3043             discrim->match_opers = 1;
3044         } else if (irccasecmp(argv[i], "depth") == 0) {
3045             discrim->domain_depth = strtoul(argv[++i], NULL, 0);
3046         } else if (irccasecmp(argv[i], "clones") == 0) {
3047             discrim->min_clones = strtoul(argv[++i], NULL, 0);
3048         } else {
3049             send_message(user, opserv, "MSG_INVALID_CRITERIA", argv[i]);
3050             goto fail;
3051         }
3052     }
3053
3054     if (discrim->mask_nick && !strcmp(discrim->mask_nick, "*")) {
3055         discrim->mask_nick = 0;
3056     }
3057     if (discrim->mask_ident && !strcmp(discrim->mask_ident, "*")) {
3058         discrim->mask_ident = 0;
3059     }
3060     if (discrim->mask_info && !strcmp(discrim->mask_info, "*")) {
3061         discrim->mask_info = 0;
3062     }
3063     if (discrim->mask_host && !discrim->mask_host[strspn(discrim->mask_host, "*.")]) {
3064         discrim->mask_host = 0;
3065     }
3066     return discrim;
3067   fail:
3068     free(discrim);
3069     return NULL;
3070 }
3071
3072 static int
3073 discrim_match(discrim_t discrim, struct userNode *user)
3074 {
3075     unsigned int access;
3076
3077     if ((user->timestamp < discrim->min_ts)
3078         || (user->timestamp > discrim->max_ts)
3079         || (user->channels.used < discrim->min_channels)
3080         || (user->channels.used > discrim->max_channels)
3081         || (discrim->authed == 0 && user->handle_info)
3082         || (discrim->authed == 1 && !user->handle_info)
3083         || (discrim->info_space == 0 && user->info[0] == ' ')
3084         || (discrim->info_space == 1 && user->info[0] != ' ')
3085         || (discrim->mask_nick && !match_ircglob(user->nick, discrim->mask_nick))
3086         || (discrim->mask_ident && !match_ircglob(user->ident, discrim->mask_ident))
3087         || (discrim->mask_host && !match_ircglob(user->hostname, discrim->mask_host))
3088         || (discrim->mask_info && !match_ircglob(user->info, discrim->mask_info))
3089         || (discrim->server && !match_ircglob(user->uplink->name, discrim->server))
3090         || (discrim->accountmask && (!user->handle_info || !match_ircglob(user->handle_info->handle, discrim->accountmask)))
3091         || (discrim->ip_mask && !MATCH_IPMASK(user->ip, discrim->ip_addr, discrim->ip_mask))) {
3092         return 0;
3093     }
3094     if (discrim->channel && !GetUserMode(discrim->channel, user)) return 0;
3095     access = user->handle_info ? user->handle_info->opserv_level : 0;
3096     if ((access < discrim->min_level)
3097         || (access > discrim->max_level)) {
3098         return 0;
3099     }
3100     if (discrim->ip_mask_str) {
3101         if (!match_ircglob(inet_ntoa(user->ip), discrim->ip_mask_str)) return 0;
3102     }
3103     if (discrim->min_clones > 1) {
3104         struct opserv_hostinfo *ohi = dict_find(opserv_hostinfo_dict, inet_ntoa(user->ip), NULL);
3105         if (!ohi || (ohi->clients.used < discrim->min_clones)) return 0;
3106     }
3107     return 1;
3108 }
3109
3110 static unsigned int
3111 opserv_discrim_search(discrim_t discrim, discrim_search_func dsf, void *data)
3112 {
3113     unsigned int nn, count;
3114     struct userList matched;
3115
3116     userList_init(&matched);
3117     /* Try most optimized search methods first */
3118     if (discrim->channel) {
3119         for (nn=0;
3120                 (nn < discrim->channel->members.used)
3121                 && (matched.used < discrim->limit);
3122                 nn++) {
3123             struct modeNode *mn = discrim->channel->members.list[nn];
3124             if (((mn->modes & discrim->chan_req_modes) != discrim->chan_req_modes)
3125                     || ((mn->modes & discrim->chan_no_modes) != 0)) {
3126                 continue;
3127             }
3128             if (discrim_match(discrim, mn->user)) {
3129                 userList_append(&matched, mn->user);
3130             }
3131         }
3132     } else if (discrim->ip_mask_str && !discrim->ip_mask_str[strcspn(discrim->ip_mask_str, "?*")]) {
3133         struct opserv_hostinfo *ohi = dict_find(opserv_hostinfo_dict, discrim->ip_mask_str, NULL);
3134         if (!ohi) {
3135             userList_clean(&matched);
3136             return 0;
3137         }
3138         for (nn=0; (nn<ohi->clients.used) && (matched.used < discrim->limit); nn++) {
3139             if (discrim_match(discrim, ohi->clients.list[nn])) {
3140                 userList_append(&matched, ohi->clients.list[nn]);
3141             }
3142         }
3143     } else {
3144         dict_iterator_t it;
3145         for (it=dict_first(clients); it && (matched.used < discrim->limit); it=iter_next(it)) {
3146             if (discrim_match(discrim, iter_data(it))) {
3147                 userList_append(&matched, iter_data(it));
3148             }
3149         }
3150     }
3151
3152     if (!matched.used) {
3153         userList_clean(&matched);
3154         return 0;
3155     }
3156
3157     if (discrim->option_log) {
3158         log_module(OS_LOG, LOG_INFO, "Logging matches for search:");
3159     }
3160     for (nn=0; nn<matched.used; nn++) {
3161         struct userNode *user = matched.list[nn];
3162         if (discrim->option_log) {
3163             log_module(OS_LOG, LOG_INFO, "  %s!%s@%s", user->nick, user->ident, user->hostname);
3164         }
3165         if (dsf(user, data)) {
3166             /* If a search function returns true, it ran into a
3167                problem. Stop going through the list. */
3168             break;
3169         }
3170     }
3171     if (discrim->option_log) {
3172         log_module(OS_LOG, LOG_INFO, "End of matching users.");
3173     }
3174     count = matched.used;
3175     userList_clean(&matched);
3176     return count;
3177 }
3178
3179 static int
3180 trace_print_func(struct userNode *match, void *extra)
3181 {
3182     struct discrim_and_source *das = extra;
3183     if (match->handle_info) {
3184         send_message_type(4, das->source, opserv, "%s!%s@%s %s", match->nick, match->ident, match->hostname, match->handle_info->handle);
3185     } else {
3186         send_message_type(4, das->source, opserv, "%s!%s@%s", match->nick, match->ident, match->hostname);
3187     }
3188     return 0;
3189 }
3190
3191 static int
3192 trace_count_func(UNUSED_ARG(struct userNode *match), UNUSED_ARG(void *extra))
3193 {
3194     return 0;
3195 }
3196
3197 static int
3198 is_oper_victim(struct userNode *user, struct userNode *target, int match_opers)
3199 {
3200     return !(IsService(target)
3201              || (!match_opers && IsOper(target))
3202              || (target->handle_info
3203                  && target->handle_info->opserv_level > user->handle_info->opserv_level));
3204 }
3205
3206 static int
3207 trace_gline_func(struct userNode *match, void *extra)
3208 {
3209     struct discrim_and_source *das = extra;
3210
3211     if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
3212         opserv_block(match, das->source->handle_info->handle, das->discrim->reason, das->discrim->duration);
3213     }
3214
3215     return 0;
3216 }
3217
3218 static int
3219 trace_kill_func(struct userNode *match, void *extra)
3220 {
3221     struct discrim_and_source *das = extra;
3222
3223     if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
3224         char *reason;
3225         if (das->discrim->reason) {
3226             reason = das->discrim->reason;
3227         } else {
3228             reason = alloca(strlen(OSMSG_KILL_REQUESTED)+strlen(das->source->nick)+1);
3229             sprintf(reason, OSMSG_KILL_REQUESTED, das->source->nick);
3230         }
3231         DelUser(match, opserv, 1, reason);
3232     }
3233
3234     return 0;
3235 }
3236
3237 static int
3238 is_gagged(char *mask)
3239 {
3240     struct gag_entry *gag;
3241
3242     for (gag = gagList; gag; gag = gag->next) {
3243         if (match_ircglobs(gag->mask, mask)) return 1;
3244     }
3245     return 0;
3246 }
3247
3248 static int
3249 trace_gag_func(struct userNode *match, void *extra)
3250 {
3251     struct discrim_and_source *das = extra;
3252
3253     if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
3254         char *reason, *mask;
3255         int masksize;
3256         if (das->discrim->reason) {
3257             reason = das->discrim->reason;
3258         } else {
3259             reason = alloca(strlen(OSMSG_GAG_REQUESTED)+strlen(das->source->nick)+1);
3260             sprintf(reason, OSMSG_GAG_REQUESTED, das->source->nick);
3261         }
3262         masksize = 5+strlen(match->hostname);
3263         mask = alloca(masksize);
3264         snprintf(mask, masksize, "*!*@%s", match->hostname);
3265         if (!is_gagged(mask)) {
3266             gag_create(mask, das->source->handle_info->handle, reason,
3267                        das->discrim->duration ? (now + das->discrim->duration) : 0);
3268         }
3269     }
3270
3271     return 0;
3272 }
3273
3274 static int
3275 trace_domains_func(struct userNode *match, void *extra)
3276 {
3277     struct discrim_and_source *das = extra;
3278     unsigned long *count;
3279     unsigned int depth;
3280     char *hostname;
3281
3282     if (!match->hostname[strspn(match->hostname, "0123456789.")]) {
3283         char ipmask[16];
3284         unsigned long matchip = ntohl(match->ip.s_addr);
3285         /* raw IP address.. use up to first three octets of IP */
3286         switch (das->discrim->domain_depth) {
3287         default:
3288             snprintf(ipmask, sizeof(ipmask), "%lu.%lu.%lu.*", (matchip>>24)&255, (matchip>>16)&255, (matchip>>8)&255);
3289             break;
3290         case 2:
3291             snprintf(ipmask, sizeof(ipmask), "%lu.%lu.*", (matchip>>24)&255, (matchip>>16)&255);
3292             break;
3293         case 1:
3294             snprintf(ipmask, sizeof(ipmask), "%lu.*", (matchip>>24)&255);
3295             break;
3296         }
3297         hostname = ipmask;
3298     } else {
3299         hostname = match->hostname + strlen(match->hostname);
3300         for (depth=das->discrim->domain_depth; 
3301              depth && (hostname > match->hostname);
3302              depth--) {
3303             hostname--;
3304             while ((hostname > match->hostname) && (*hostname != '.')) hostname--;
3305         }
3306         if (*hostname == '.') hostname++; /* advance past last dot we saw */
3307     }
3308     if (!(count = dict_find(das->dict, hostname, NULL))) {
3309         count = calloc(1, sizeof(*count));
3310         dict_insert(das->dict, strdup(hostname), count);
3311     }
3312     (*count)++;
3313     return 0;
3314 }
3315
3316 static int
3317 opserv_show_hostinfo(const char *key, void *data, void *extra)
3318 {
3319     unsigned long *count = data;
3320     struct discrim_and_source *das = extra;
3321
3322     send_message_type(4, das->source, opserv, "%s %lu", key, *count);
3323     return !--das->disp_limit;
3324 }
3325
3326 static MODCMD_FUNC(cmd_trace)
3327 {
3328     struct discrim_and_source das;
3329     discrim_search_func action;
3330     unsigned int matches;
3331     struct svccmd *subcmd;
3332     char buf[MAXLEN];
3333
3334     sprintf(buf, "trace %s", argv[1]);
3335     if (!(subcmd = dict_find(cmd->parent->commands, buf, NULL))) {
3336         reply("OSMSG_BAD_ACTION", argv[1]);
3337         return 0;
3338     }
3339     if (!svccmd_can_invoke(user, cmd->parent->bot, subcmd, channel, SVCCMD_NOISY))
3340         return 0;
3341     if (!irccasecmp(argv[1], "print"))
3342         action = trace_print_func;
3343     else if (!irccasecmp(argv[1], "count"))
3344         action = trace_count_func;
3345     else if (!irccasecmp(argv[1], "domains"))
3346         action = trace_domains_func;
3347     else if (!irccasecmp(argv[1], "gline"))
3348         action = trace_gline_func;
3349     else if (!irccasecmp(argv[1], "kill"))
3350         action = trace_kill_func;
3351     else if (!irccasecmp(argv[1], "gag"))
3352         action = trace_gag_func;
3353     else {
3354         reply("OSMSG_BAD_ACTION", argv[1]);
3355         return 0;
3356     }
3357
3358     if (user->handle_info->opserv_level < subcmd->min_opserv_level) {
3359         reply("OSMSG_LEVEL_TOO_LOW");
3360         return 0;
3361     }
3362
3363     das.dict = NULL;
3364     das.source = user;
3365     das.discrim = opserv_discrim_create(user, argc-2, argv+2, 1);
3366     if (!das.discrim)
3367         return 0;
3368
3369     if (action == trace_print_func)
3370         reply("OSMSG_USER_SEARCH_RESULTS");
3371     else if (action == trace_count_func)
3372         das.discrim->limit = INT_MAX;
3373     else if ((action == trace_gline_func) && !das.discrim->duration)
3374         das.discrim->duration = opserv_conf.block_gline_duration;
3375     else if (action == trace_domains_func) {
3376         das.dict = dict_new();
3377         dict_set_free_data(das.dict, free);
3378         dict_set_free_keys(das.dict, free);
3379         das.disp_limit = das.discrim->limit;
3380         das.discrim->limit = INT_MAX;
3381     }
3382     matches = opserv_discrim_search(das.discrim, action, &das);
3383
3384     if (action == trace_domains_func)
3385         dict_foreach(das.dict, opserv_show_hostinfo, &das);
3386
3387     if (matches)
3388         reply("MSG_MATCH_COUNT", matches);
3389     else
3390         reply("MSG_NO_MATCHES");
3391
3392     if (das.discrim->channel)
3393         UnlockChannel(das.discrim->channel);
3394     free(das.discrim->reason);
3395     free(das.discrim);
3396     dict_delete(das.dict);
3397     return 1;
3398 }
3399
3400 typedef void (*cdiscrim_search_func)(struct chanNode *match, void *data);
3401
3402 typedef struct channel_discrim {
3403     char *name, *topic;
3404
3405     unsigned int min_users, max_users;
3406     time_t min_ts, max_ts;
3407     unsigned int limit;
3408 } *cdiscrim_t;
3409
3410 static cdiscrim_t opserv_cdiscrim_create(struct userNode *user, unsigned int argc, char *argv[]);
3411 static unsigned int opserv_cdiscrim_search(cdiscrim_t discrim, cdiscrim_search_func dsf, void *data);
3412
3413 static time_t
3414 smart_parse_time(const char *str) {
3415     /* If an interval-style string is given, treat as time before now.
3416      * If it's all digits, treat directly as a Unix timestamp. */
3417     return str[strspn(str, "0123456789")] ? (time_t)(now - ParseInterval(str)) : (time_t)atoi(str);
3418 }
3419
3420 static cdiscrim_t
3421 opserv_cdiscrim_create(struct userNode *user, unsigned int argc, char *argv[])
3422 {
3423     cdiscrim_t discrim;
3424     unsigned int i;
3425
3426     discrim = calloc(1, sizeof(*discrim));
3427     discrim->limit = 25;
3428
3429     for (i = 0; i < argc; i++) {
3430         /* Assume all criteria require arguments. */
3431         if (i == (argc - 1)) {
3432             send_message(user, opserv, "MSG_MISSING_PARAMS", argv[i]);
3433             return NULL;
3434         }
3435
3436         if (!irccasecmp(argv[i], "name"))
3437             discrim->name = argv[++i];
3438         else if (!irccasecmp(argv[i], "topic"))
3439             discrim->topic = argv[++i];
3440         else if (!irccasecmp(argv[i], "users")) {
3441             const char *cmp = argv[++i];
3442             if (cmp[0] == '<') {
3443                 if (cmp[1] == '=')
3444                     discrim->max_users = strtoul(cmp+2, NULL, 0);
3445                 else
3446                     discrim->max_users = strtoul(cmp+1, NULL, 0) - 1;
3447             } else if (cmp[0] == '=') {
3448                 discrim->min_users = discrim->max_users = strtoul(cmp+1, NULL, 0);
3449             } else if (cmp[0] == '>') {
3450                 if (cmp[1] == '=')
3451                     discrim->min_users = strtoul(cmp+2, NULL, 0);
3452                 else
3453                     discrim->min_users = strtoul(cmp+1, NULL, 0) + 1;
3454             } else {
3455                 discrim->min_users = strtoul(cmp+2, NULL, 0);
3456             }
3457         } else if (!irccasecmp(argv[i], "timestamp")) {
3458             const char *cmp = argv[++i];
3459             if (cmp[0] == '<') {
3460                 if (cmp[1] == '=')
3461                     discrim->max_ts = smart_parse_time(cmp+2);
3462                 else
3463                     discrim->max_ts = smart_parse_time(cmp+1)-1;
3464             } else if (cmp[0] == '=') {
3465                 discrim->min_ts = discrim->max_ts = smart_parse_time(cmp+1);
3466             } else if (cmp[0] == '>') {
3467                 if (cmp[1] == '=')
3468                     discrim->min_ts = smart_parse_time(cmp+2);
3469                 else
3470                     discrim->min_ts = smart_parse_time(cmp+1)+1;
3471             } else {
3472                 discrim->min_ts = smart_parse_time(cmp);
3473             }
3474         } else if (!irccasecmp(argv[i], "limit")) {
3475             discrim->limit = strtoul(argv[++i], NULL, 10);
3476         } else {
3477             send_message(user, opserv, "MSG_INVALID_CRITERIA", argv[i]);
3478             goto fail;
3479         }
3480     }
3481
3482     if (discrim->name && !strcmp(discrim->name, "*"))
3483         discrim->name = 0;
3484     if (discrim->topic && !strcmp(discrim->topic, "*"))
3485         discrim->topic = 0;
3486
3487     return discrim;
3488   fail:
3489     free(discrim);
3490     return NULL;
3491 }
3492
3493 static int
3494 cdiscrim_match(cdiscrim_t discrim, struct chanNode *chan)
3495 {
3496     if ((discrim->name && !match_ircglob(chan->name, discrim->name)) ||
3497         (discrim->topic && !match_ircglob(chan->topic, discrim->topic)) ||
3498         (discrim->min_users && chan->members.used < discrim->min_users) ||
3499         (discrim->max_users && chan->members.used > discrim->max_users) ||
3500         (discrim->min_ts && chan->timestamp < discrim->min_ts) ||
3501             (discrim->max_ts && chan->timestamp > discrim->max_ts)) {
3502         return 0;
3503     }
3504     return 1;
3505 }
3506
3507 static unsigned int opserv_cdiscrim_search(cdiscrim_t discrim, cdiscrim_search_func dsf, void *data)
3508 {
3509     unsigned int count = 0;
3510     dict_iterator_t it, next;
3511
3512     for (it = dict_first(channels); it && count < discrim->limit ; it = next) {
3513         struct chanNode *chan = iter_data(it);
3514
3515         /* Hold on to the next channel in case we decide to
3516            add actions that destructively modify the channel. */
3517         next = iter_next(it);
3518         if ((chan->members.used > 0) && cdiscrim_match(discrim, chan)) {
3519             dsf(chan, data);
3520             count++;
3521         }
3522     }
3523
3524     return count;
3525 }
3526
3527 void channel_count(UNUSED_ARG(struct chanNode *channel), UNUSED_ARG(void *data))
3528 {
3529 }
3530
3531 void channel_print(struct chanNode *channel, void *data)
3532 {
3533     char modes[MAXLEN];
3534     irc_make_chanmode(channel, modes);
3535     send_message(data, opserv, "OSMSG_CSEARCH_CHANNEL_INFO", channel->name, channel->members.used, modes, channel->topic);
3536 }
3537
3538 static MODCMD_FUNC(cmd_csearch)
3539 {
3540     cdiscrim_t discrim;
3541     unsigned int matches;
3542     cdiscrim_search_func action;
3543     struct svccmd *subcmd;
3544     char buf[MAXLEN];
3545
3546     if (!irccasecmp(argv[1], "count"))
3547         action = channel_count;
3548     else if (!irccasecmp(argv[1], "print"))
3549         action = channel_print;
3550     else {
3551         reply("OSMSG_BAD_ACTION", argv[1]);
3552         return 0;
3553     }
3554
3555     sprintf(buf, "%s %s", argv[0], argv[0]);
3556     if ((subcmd = dict_find(cmd->parent->commands, buf, NULL))
3557         && !svccmd_can_invoke(user, cmd->parent->bot, subcmd, channel, SVCCMD_NOISY)) {
3558         return 0;
3559     }
3560
3561     discrim = opserv_cdiscrim_create(user, argc - 2, argv + 2);
3562     if (!discrim)
3563         return 0;
3564
3565     if (action == channel_print)
3566         reply("OSMSG_CHANNEL_SEARCH_RESULTS");
3567     else if (action == channel_count)
3568         discrim->limit = INT_MAX;
3569
3570     matches = opserv_cdiscrim_search(discrim, action, user);
3571
3572     if (matches)
3573         reply("MSG_MATCH_COUNT", matches);
3574     else
3575         reply("MSG_NO_MATCHES");
3576
3577     free(discrim);
3578     return 1;
3579 }
3580
3581 static MODCMD_FUNC(cmd_gsync)
3582 {
3583     struct server *src;
3584     if (argc > 1) {
3585         src = GetServerH(argv[1]);
3586         if (!src) {
3587             reply("MSG_SERVER_UNKNOWN", argv[1]);
3588             return 0;
3589         }
3590     } else {
3591         src = self->uplink;
3592     }
3593     irc_stats(cmd->parent->bot, src, 'G');
3594     reply("OSMSG_GSYNC_RUNNING", src->name);
3595     return 1;
3596 }
3597
3598 struct gline_extra {
3599     struct userNode *user;
3600     struct string_list *glines;
3601 };
3602
3603 static void
3604 gtrace_print_func(struct gline *gline, void *extra)
3605 {
3606     struct gline_extra *xtra = extra;
3607     char *when_text, set_text[20];
3608     strftime(set_text, sizeof(set_text), "%Y-%m-%d", localtime(&gline->issued));
3609     when_text = asctime(localtime(&gline->expires));
3610     when_text[strlen(when_text)-1] = 0; /* strip lame \n */
3611     send_message(xtra->user, opserv, "OSMSG_GTRACE_FORMAT", gline->target, set_text, gline->issuer, when_text, gline->reason);
3612 }
3613
3614 static void
3615 gtrace_count_func(UNUSED_ARG(struct gline *gline), UNUSED_ARG(void *extra))
3616 {
3617 }
3618
3619 static void
3620 gtrace_ungline_func(struct gline *gline, void *extra)
3621 {
3622     struct gline_extra *xtra = extra;
3623     string_list_append(xtra->glines, strdup(gline->target));
3624 }
3625
3626 static MODCMD_FUNC(cmd_gtrace)
3627 {
3628     struct gline_discrim *discrim;
3629     gline_search_func action;
3630     unsigned int matches, nn;
3631     struct gline_extra extra;
3632     struct svccmd *subcmd;
3633     char buf[MAXLEN];
3634
3635     if (!irccasecmp(argv[1], "print"))
3636         action = gtrace_print_func;
3637     else if (!irccasecmp(argv[1], "count"))
3638         action = gtrace_count_func;
3639     else if (!irccasecmp(argv[1], "ungline"))
3640         action = gtrace_ungline_func;
3641     else {
3642         reply("OSMSG_BAD_ACTION", argv[1]);
3643         return 0;
3644     }
3645     sprintf(buf, "%s %s", argv[0], argv[0]);
3646     if ((subcmd = dict_find(cmd->parent->commands, buf, NULL))
3647         && !svccmd_can_invoke(user, cmd->parent->bot, subcmd, channel, SVCCMD_NOISY)) {
3648         return 0;
3649     }
3650
3651     discrim = gline_discrim_create(user, cmd->parent->bot, argc-2, argv+2);
3652     if (!discrim)
3653         return 0;
3654
3655     if (action == gtrace_print_func)
3656         reply("OSMSG_GLINE_SEARCH_RESULTS");
3657     else if (action == gtrace_count_func)
3658         discrim->limit = INT_MAX;
3659
3660     extra.user = user;
3661     extra.glines = alloc_string_list(4);
3662     matches = gline_discrim_search(discrim, action, &extra);
3663
3664     if (action == gtrace_ungline_func)
3665         for (nn=0; nn<extra.glines->used; nn++)
3666             gline_remove(extra.glines->list[nn], 1);
3667     free_string_list(extra.glines);
3668
3669     if (matches)
3670         reply("MSG_MATCH_COUNT", matches);
3671     else
3672         reply("MSG_NO_MATCHES");
3673     free(discrim->alt_target_mask);
3674     free(discrim);
3675     return 1;
3676 }
3677
3678 static int
3679 alert_check_user(const char *key, void *data, void *extra)
3680 {
3681     struct opserv_user_alert *alert = data;
3682     struct userNode *user = extra;
3683
3684     if (!discrim_match(alert->discrim, user))
3685         return 0;
3686
3687     if ((alert->reaction != REACT_NOTICE)
3688         && IsOper(user)
3689         && !alert->discrim->match_opers) {
3690         return 0;
3691     }
3692
3693     /* The user matches the alert criteria, so trigger the reaction. */
3694     if (alert->discrim->option_log)
3695         log_module(OS_LOG, LOG_INFO, "Alert %s triggered by user %s!%s@%s (%s).", key, user->nick, user->ident, user->hostname, alert->discrim->reason);
3696
3697     /* Return 1 to halt alert matching, such as when killing the user
3698        that triggered the alert. */
3699     switch (alert->reaction) {
3700     case REACT_KILL:
3701         DelUser(user, opserv, 1, alert->discrim->reason);
3702         return 1;
3703     case REACT_GLINE:
3704         opserv_block(user, alert->owner, alert->discrim->reason, alert->discrim->duration);
3705         return 1;
3706     default:
3707         log_module(OS_LOG, LOG_ERROR, "Invalid reaction type %d for alert %s.", alert->reaction, key);
3708         /* fall through to REACT_NOTICE case */
3709     case REACT_NOTICE:
3710         opserv_alert("Alert $b%s$b triggered by user $b%s$b!%s@%s (%s).", key, user->nick, user->ident, user->hostname, alert->discrim->reason);
3711         break;
3712     }
3713     return 0;
3714 }
3715
3716 static void
3717 opserv_alert_check_nick(struct userNode *user, UNUSED_ARG(const char *old_nick))
3718 {
3719     struct gag_entry *gag;
3720     dict_foreach(opserv_nick_based_alerts, alert_check_user, user);
3721     /* Gag them if appropriate (and only if). */
3722     user->modes &= ~FLAGS_GAGGED;
3723     for (gag = gagList; gag; gag = gag->next) {
3724         if (user_matches_glob(user, gag->mask, 1)) {
3725             gag_helper_func(user, NULL);
3726             break;
3727         }
3728     }
3729 }
3730
3731 static void
3732 opserv_staff_alert(struct userNode *user, UNUSED_ARG(struct handle_info *old_handle))
3733 {
3734     const char *type;
3735
3736     if (!opserv_conf.staff_auth_channel
3737         || user->uplink->burst
3738         || !user->handle_info)
3739         return;
3740     else if (user->handle_info->opserv_level)
3741         type = "OPER";
3742     else if (IsNetworkHelper(user))
3743         type = "NETWORK HELPER";
3744     else if (IsSupportHelper(user))
3745         type = "SUPPORT HELPER";
3746     else
3747         return;
3748
3749     if (user->ip.s_addr)
3750         send_channel_notice(opserv_conf.staff_auth_channel, opserv, IDENT_FORMAT" authed to %s account %s", IDENT_DATA(user), type, user->handle_info->handle);
3751     else
3752         send_channel_notice(opserv_conf.staff_auth_channel, opserv, "%s [%s@%s] authed to %s account %s", user->nick, user->ident, user->hostname, type, user->handle_info->handle);
3753 }
3754
3755 static MODCMD_FUNC(cmd_log)
3756 {
3757     struct logSearch *discrim;
3758     unsigned int matches;
3759     struct logReport report;
3760
3761     discrim = log_discrim_create(cmd->parent->bot, user, argc, argv);
3762     if (!discrim)
3763         return 0;
3764
3765     reply("OSMSG_LOG_SEARCH_RESULTS");
3766     report.reporter = opserv;
3767     report.user = user;
3768     matches = log_entry_search(discrim, log_report_entry, &report);
3769
3770     if (matches)
3771         reply("MSG_MATCH_COUNT", matches);
3772     else
3773         reply("MSG_NO_MATCHES");
3774
3775     free(discrim);
3776     return 1;
3777 }
3778
3779 static int
3780 gag_helper_func(struct userNode *match, UNUSED_ARG(void *extra))
3781 {
3782     if (IsOper(match) || IsLocal(match))
3783         return 0;
3784     match->modes |= FLAGS_GAGGED;
3785     return 0;
3786 }
3787
3788 static MODCMD_FUNC(cmd_gag)
3789 {
3790     struct gag_entry *gag;
3791     unsigned int gagged;
3792     unsigned long duration;
3793     char *reason;
3794
3795     reason = unsplit_string(argv + 3, argc - 3, NULL);
3796
3797     if (!is_ircmask(argv[1])) {
3798         reply("OSMSG_INVALID_IRCMASK", argv[1]);
3799         return 0;
3800     }
3801
3802     for (gag = gagList; gag; gag = gag->next)
3803         if (match_ircglobs(gag->mask, argv[1]))
3804             break;
3805
3806     if (gag) {
3807         reply("OSMSG_REDUNDANT_GAG", argv[1]);
3808         return 0;
3809     }
3810
3811     duration = ParseInterval(argv[2]);
3812     gagged = gag_create(argv[1], user->handle_info->handle, reason, (duration?now+duration:0));
3813
3814     if (gagged)
3815         reply("OSMSG_GAG_APPLIED", argv[1], gagged);
3816     else
3817         reply("OSMSG_GAG_ADDED", argv[1]);
3818     return 1;
3819 }
3820
3821 static int
3822 ungag_helper_func(struct userNode *match, UNUSED_ARG(void *extra))
3823 {
3824     match->modes &= ~FLAGS_GAGGED;
3825     return 0;
3826 }
3827
3828 static MODCMD_FUNC(cmd_ungag)
3829 {
3830     struct gag_entry *gag;
3831     unsigned int ungagged;
3832
3833     for (gag = gagList; gag; gag = gag->next)
3834         if (!strcmp(gag->mask, argv[1]))
3835             break;
3836
3837     if (!gag) {
3838         reply("OSMSG_GAG_NOT_FOUND", argv[1]);
3839         return 0;
3840     }
3841
3842     timeq_del(gag->expires, gag_expire, gag, 0);
3843     ungagged = gag_free(gag);
3844
3845     if (ungagged)
3846         reply("OSMSG_UNGAG_APPLIED", argv[1], ungagged);
3847     else
3848         reply("OSMSG_UNGAG_ADDED", argv[1]);
3849     return 1;
3850 }
3851
3852 static MODCMD_FUNC(cmd_addalert)
3853 {
3854     opserv_alert_reaction reaction;
3855     struct svccmd *subcmd;
3856     const char *name;
3857     char buf[MAXLEN];
3858
3859     name = argv[1];
3860     sprintf(buf, "addalert %s", argv[2]);
3861     if (!(subcmd = dict_find(cmd->parent->commands, buf, NULL))) {
3862         reply("OSMSG_UNKNOWN_REACTION", argv[2]);
3863         return 0;
3864     }
3865     if (!irccasecmp(argv[2], "notice"))
3866         reaction = REACT_NOTICE;
3867     else if (!irccasecmp(argv[2], "kill"))
3868         reaction = REACT_KILL;
3869     else if (!irccasecmp(argv[2], "gline"))
3870         reaction = REACT_GLINE;
3871     else {
3872         reply("OSMSG_UNKNOWN_REACTION", argv[2]);
3873         return 0;
3874     }
3875     if (!svccmd_can_invoke(user, cmd->parent->bot, subcmd, channel, SVCCMD_NOISY)
3876         || !opserv_add_user_alert(user, name, reaction, unsplit_string(argv + 3, argc - 3, NULL)))
3877         return 0;
3878     reply("OSMSG_ADDED_ALERT", name);
3879     return 1;
3880 }
3881
3882 static MODCMD_FUNC(cmd_delalert)
3883 {
3884     unsigned int i;
3885     for (i=1; i<argc; i++) {
3886         dict_remove(opserv_nick_based_alerts, argv[i]);
3887         dict_remove(opserv_channel_alerts, argv[i]);
3888         if (dict_remove(opserv_user_alerts, argv[i]))
3889             reply("OSMSG_REMOVED_ALERT", argv[i]);
3890         else
3891             reply("OSMSG_NO_SUCH_ALERT", argv[i]);
3892     }
3893     return 1;
3894 }
3895
3896 static void
3897 opserv_conf_read(void)
3898 {
3899     struct record_data *rd;
3900     dict_t conf_node, child;
3901     const char *str, *str2;
3902     struct policer_params *pp;
3903     dict_iterator_t it;
3904
3905     rd = conf_get_node(OPSERV_CONF_NAME);
3906     if (!rd || rd->type != RECDB_OBJECT) {
3907         log_module(OS_LOG, LOG_ERROR, "config node `%s' is missing or has wrong type.", OPSERV_CONF_NAME);
3908         return;
3909     }
3910     conf_node = rd->d.object;
3911     str = database_get_data(conf_node, KEY_DEBUG_CHANNEL, RECDB_QSTRING);
3912     if (opserv && str) {
3913         str2 = database_get_data(conf_node, KEY_DEBUG_CHANNEL_MODES, RECDB_QSTRING);
3914         if (!str2)
3915             str2 = "+tinms";
3916         opserv_conf.debug_channel = AddChannel(str, now, str2, NULL);
3917         AddChannelUser(opserv, opserv_conf.debug_channel)->modes |= MODE_CHANOP;
3918     } else {
3919         opserv_conf.debug_channel = NULL;
3920     }
3921     str = database_get_data(conf_node, KEY_ALERT_CHANNEL, RECDB_QSTRING);
3922     if (opserv && str) {
3923         str2 = database_get_data(conf_node, KEY_ALERT_CHANNEL_MODES, RECDB_QSTRING);
3924         if (!str2)
3925             str2 = "+tns";
3926         opserv_conf.alert_channel = AddChannel(str, now, str2, NULL);
3927         AddChannelUser(opserv, opserv_conf.alert_channel)->modes |= MODE_CHANOP;
3928     } else {
3929         opserv_conf.alert_channel = NULL;
3930     }
3931     str = database_get_data(conf_node, KEY_STAFF_AUTH_CHANNEL, RECDB_QSTRING);
3932     if (opserv && str) {
3933         str2 = database_get_data(conf_node, KEY_STAFF_AUTH_CHANNEL_MODES, RECDB_QSTRING);
3934         if (!str2)
3935             str2 = "+timns";
3936         opserv_conf.staff_auth_channel = AddChannel(str, now, str2, NULL);
3937         AddChannelUser(opserv, opserv_conf.staff_auth_channel)->modes |= MODE_CHANOP;
3938     } else {
3939         opserv_conf.staff_auth_channel = NULL;
3940     }
3941     str = database_get_data(conf_node, KEY_UNTRUSTED_MAX, RECDB_QSTRING);
3942     opserv_conf.untrusted_max = str ? strtoul(str, NULL, 0) : 5;
3943     str = database_get_data(conf_node, KEY_PURGE_LOCK_DELAY, RECDB_QSTRING);
3944     opserv_conf.purge_lock_delay = str ? strtoul(str, NULL, 0) : 60;
3945     str = database_get_data(conf_node, KEY_JOIN_FLOOD_MODERATE, RECDB_QSTRING);
3946     opserv_conf.join_flood_moderate = str ? strtoul(str, NULL, 0) : 1;
3947     str = database_get_data(conf_node, KEY_JOIN_FLOOD_MODERATE_THRESH, RECDB_QSTRING);
3948     opserv_conf.join_flood_moderate_threshold = str ? strtoul(str, NULL, 0) : 50;
3949     str = database_get_data(conf_node, KEY_NICK, RECDB_QSTRING);
3950     if (opserv && str)
3951         NickChange(opserv, str, 0);
3952     str = database_get_data(conf_node, KEY_CLONE_GLINE_DURATION, RECDB_QSTRING);
3953     opserv_conf.clone_gline_duration = str ? ParseInterval(str) : 3600;
3954     str = database_get_data(conf_node, KEY_BLOCK_GLINE_DURATION, RECDB_QSTRING);
3955     opserv_conf.block_gline_duration = str ? ParseInterval(str) : 3600;
3956
3957     if (!opserv_conf.join_policer_params)
3958         opserv_conf.join_policer_params = policer_params_new();
3959     policer_params_set(opserv_conf.join_policer_params, "size", "20");
3960     policer_params_set(opserv_conf.join_policer_params, "drain-rate", "1");
3961     if ((child = database_get_data(conf_node, KEY_JOIN_POLICER, RECDB_OBJECT)))
3962         dict_foreach(child, set_policer_param, opserv_conf.join_policer_params);
3963
3964     for (it = dict_first(channels); it; it = iter_next(it)) {
3965         struct chanNode *cNode = iter_data(it);
3966         cNode->join_policer.params = opserv_conf.join_policer_params;
3967     }
3968
3969     if (opserv_conf.new_user_policer.params)
3970         pp = opserv_conf.new_user_policer.params;
3971     else
3972         pp = opserv_conf.new_user_policer.params = policer_params_new();
3973     policer_params_set(pp, "size", "200");
3974     policer_params_set(pp, "drain-rate", "3");
3975     if ((child = database_get_data(conf_node, KEY_NEW_USER_POLICER, RECDB_OBJECT)))
3976         dict_foreach(child, set_policer_param, pp);
3977 }
3978
3979 static void
3980 opserv_db_init(void) {
3981     /* set up opserv_trusted_hosts dict */
3982     dict_delete(opserv_trusted_hosts);
3983     opserv_trusted_hosts = dict_new();
3984     dict_set_free_data(opserv_trusted_hosts, free_trusted_host);
3985     /* set up opserv_chan_warn dict */
3986     dict_delete(opserv_chan_warn);
3987     opserv_chan_warn = dict_new();
3988     dict_set_free_keys(opserv_chan_warn, free);
3989     dict_set_free_data(opserv_chan_warn, free);
3990     /* set up opserv_user_alerts */
3991     dict_delete(opserv_channel_alerts);
3992     opserv_channel_alerts = dict_new();
3993     dict_delete(opserv_nick_based_alerts);
3994     opserv_nick_based_alerts = dict_new();
3995     dict_delete(opserv_user_alerts);
3996     opserv_user_alerts = dict_new();
3997     dict_set_free_keys(opserv_user_alerts, free);
3998     dict_set_free_data(opserv_user_alerts, opserv_free_user_alert);
3999     /* set up opserv_bad_words */
4000     free_string_list(opserv_bad_words);
4001     opserv_bad_words = alloc_string_list(4);
4002     /* and opserv_exempt_channels */
4003     dict_delete(opserv_exempt_channels);
4004     opserv_exempt_channels = dict_new();
4005     dict_set_free_keys(opserv_exempt_channels, free);
4006 }
4007
4008 static void
4009 opserv_db_cleanup(void)
4010 {
4011     unsigned int nn;
4012
4013     dict_delete(opserv_chan_warn);
4014     dict_delete(opserv_reserved_nick_dict);
4015     free_string_list(opserv_bad_words);
4016     dict_delete(opserv_exempt_channels);
4017     dict_delete(opserv_trusted_hosts);
4018     unreg_del_user_func(opserv_user_cleanup);
4019     dict_delete(opserv_hostinfo_dict);
4020     dict_delete(opserv_nick_based_alerts);
4021     dict_delete(opserv_channel_alerts);
4022     dict_delete(opserv_user_alerts);
4023     for (nn=0; nn<ArrayLength(level_strings); ++nn)
4024         free(level_strings[nn]);
4025     while (gagList)
4026         gag_free(gagList);
4027     policer_params_delete(opserv_conf.join_policer_params);
4028     policer_params_delete(opserv_conf.new_user_policer.params);
4029 }
4030
4031 void
4032 init_opserv(const char *nick)
4033 {
4034     OS_LOG = log_register_type("OpServ", "file:opserv.log");
4035     if (nick) {
4036         const char *modes = conf_get_data("services/opserv/modes", RECDB_QSTRING);
4037         opserv = AddService(nick, modes ? modes : NULL, "Oper Services", NULL);
4038     }
4039     conf_register_reload(opserv_conf_read);
4040
4041     memset(level_strings, 0, sizeof(level_strings));
4042     opserv_module = module_register("OpServ", OS_LOG, "opserv.help", opserv_help_expand);
4043     opserv_define_func("ACCESS", cmd_access, 0, 0, 0);
4044     opserv_define_func("ADDALERT", cmd_addalert, 800, 0, 4);
4045     opserv_define_func("ADDALERT NOTICE", NULL, 0, 0, 0);
4046     opserv_define_func("ADDALERT GLINE", NULL, 900, 0, 0);
4047     opserv_define_func("ADDALERT KILL", NULL, 900, 0, 0);
4048     opserv_define_func("ADDBAD", cmd_addbad, 800, 0, 2);
4049     opserv_define_func("ADDEXEMPT", cmd_addexempt, 800, 0, 2);
4050     opserv_define_func("ADDTRUST", cmd_addtrust, 800, 0, 5);
4051     opserv_define_func("BAN", cmd_ban, 100, 2, 2);
4052     opserv_define_func("BLOCK", cmd_block, 100, 0, 2);
4053     opserv_define_func("CHANINFO", cmd_chaninfo, 0, 3, 0);
4054     opserv_define_func("CLEARBANS", cmd_clearbans, 300, 2, 0);
4055     opserv_define_func("CLEARMODES", cmd_clearmodes, 400, 2, 0);
4056     opserv_define_func("CLONE", cmd_clone, 999, 0, 3);
4057     opserv_define_func("COLLIDE", cmd_collide, 800, 0, 5);
4058     opserv_define_func("CSEARCH", cmd_csearch, 100, 0, 3);
4059     opserv_define_func("CSEARCH COUNT", cmd_csearch, 0, 0, 0);
4060     opserv_define_func("CSEARCH PRINT", cmd_csearch, 0, 0, 0);
4061     opserv_define_func("DELALERT", cmd_delalert, 800, 0, 2);
4062     opserv_define_func("DELBAD", cmd_delbad, 800, 0, 2);
4063     opserv_define_func("DELEXEMPT", cmd_delexempt, 800, 0, 2);
4064     opserv_define_func("DELTRUST", cmd_deltrust, 800, 0, 2);
4065     opserv_define_func("DEOP", cmd_deop, 100, 2, 2);
4066     opserv_define_func("DEOPALL", cmd_deopall, 400, 2, 0);
4067     opserv_define_func("DEVOICEALL", cmd_devoiceall, 300, 2, 0);
4068     opserv_define_func("DIE", cmd_die, 900, 0, 2);
4069     opserv_define_func("DUMP", cmd_dump, 999, 0, 2);
4070     opserv_define_func("EDITTRUST", cmd_edittrust, 800, 0, 5);
4071     opserv_define_func("GAG", cmd_gag, 600, 0, 4);
4072     opserv_define_func("GLINE", cmd_gline, 600, 0, 4);
4073     opserv_define_func("GSYNC", cmd_gsync, 600, 0, 0);
4074     opserv_define_func("GTRACE", cmd_gtrace, 100, 0, 3);
4075     opserv_define_func("GTRACE COUNT", NULL, 0, 0, 0);
4076     opserv_define_func("GTRACE PRINT", NULL, 0, 0, 0);
4077     opserv_define_func("INVITE", cmd_invite, 100, 2, 0);
4078     opserv_define_func("INVITEME", cmd_inviteme, 100, 0, 0);
4079     opserv_define_func("JOIN", cmd_join, 601, 0, 2);
4080     opserv_define_func("JUMP", cmd_jump, 900, 0, 2);
4081     opserv_define_func("JUPE", cmd_jupe, 900, 0, 4);
4082     opserv_define_func("KICK", cmd_kick, 100, 2, 2);
4083     opserv_define_func("KICKALL", cmd_kickall, 400, 2, 0);
4084     opserv_define_func("KICKBAN", cmd_kickban, 100, 2, 2);
4085     opserv_define_func("KICKBANALL", cmd_kickbanall, 450, 2, 0);
4086     opserv_define_func("LOG", cmd_log, 900, 0, 2);
4087     opserv_define_func("MODE", cmd_mode, 100, 2, 2);
4088     opserv_define_func("OP", cmd_op, 100, 2, 2);
4089     opserv_define_func("OPALL", cmd_opall, 400, 2, 0);
4090     opserv_define_func("PART", cmd_part, 601, 0, 2);
4091     opserv_define_func("QUERY", cmd_query, 0, 0, 0);
4092     opserv_define_func("RAW", cmd_raw, 999, 0, 2);
4093     opserv_define_func("RECONNECT", cmd_reconnect, 900, 0, 0);
4094     opserv_define_func("REFRESHG", cmd_refreshg, 600, 0, 0);
4095     opserv_define_func("REHASH", cmd_rehash, 900, 0, 0);
4096     opserv_define_func("REOPEN", cmd_reopen, 900, 0, 0);
4097     opserv_define_func("RESERVE", cmd_reserve, 800, 0, 5);
4098     opserv_define_func("RESTART", cmd_restart, 900, 0, 2);
4099     opserv_define_func("SET", cmd_set, 900, 0, 3);
4100     opserv_define_func("SETTIME", cmd_settime, 901, 0, 0);
4101     opserv_define_func("STATS ALERTS", cmd_stats_alerts, 0, 0, 0);
4102     opserv_define_func("STATS BAD", cmd_stats_bad, 0, 0, 0);
4103     opserv_define_func("STATS GAGS", cmd_stats_gags, 0, 0, 0);
4104     opserv_define_func("STATS GLINES", cmd_stats_glines, 0, 0, 0);
4105     opserv_define_func("STATS LINKS", cmd_stats_links, 0, 0, 0);
4106     opserv_define_func("STATS MAX", cmd_stats_max, 0, 0, 0);
4107     opserv_define_func("STATS NETWORK", cmd_stats_network, 0, 0, 0);
4108     opserv_define_func("STATS NETWORK2", cmd_stats_network2, 0, 0, 0);
4109     opserv_define_func("STATS RESERVED", cmd_stats_reserved, 0, 0, 0);
4110     opserv_define_func("STATS TIMEQ", cmd_stats_timeq, 0, 0, 0);
4111     opserv_define_func("STATS TRUSTED", cmd_stats_trusted, 0, 0, 0);
4112     opserv_define_func("STATS UPLINK", cmd_stats_uplink, 0, 0, 0);
4113     opserv_define_func("STATS UPTIME", cmd_stats_uptime, 0, 0, 0);
4114     opserv_define_func("STATS WARN", cmd_stats_warn, 0, 0, 0);
4115 #if defined(WITH_MALLOC_SRVX)
4116     opserv_define_func("STATS MEMORY", cmd_stats_memory, 0, 0, 0);
4117 #endif
4118     opserv_define_func("TRACE", cmd_trace, 100, 0, 3);
4119     opserv_define_func("TRACE PRINT", NULL, 0, 0, 0);
4120     opserv_define_func("TRACE COUNT", NULL, 0, 0, 0);
4121     opserv_define_func("TRACE DOMAINS", NULL, 0, 0, 0);
4122     opserv_define_func("TRACE GLINE", NULL, 600, 0, 0);
4123     opserv_define_func("TRACE GAG", NULL, 600, 0, 0);
4124     opserv_define_func("TRACE KILL", NULL, 600, 0, 0);
4125     opserv_define_func("UNBAN", cmd_unban, 100, 2, 2);
4126     opserv_define_func("UNGAG", cmd_ungag, 600, 0, 2);
4127     opserv_define_func("UNGLINE", cmd_ungline, 600, 0, 2);
4128     modcmd_register(opserv_module, "GTRACE UNGLINE", NULL, 0, 0, "template", "ungline", NULL);
4129     opserv_define_func("UNJUPE", cmd_unjupe, 900, 0, 2);
4130     opserv_define_func("UNRESERVE", cmd_unreserve, 800, 0, 2);
4131     opserv_define_func("UNWARN", cmd_unwarn, 800, 0, 0);
4132     opserv_define_func("VOICEALL", cmd_voiceall, 300, 2, 0);
4133     opserv_define_func("WARN", cmd_warn, 800, 0, 2);
4134     opserv_define_func("WHOIS", cmd_whois, 0, 0, 2);
4135
4136     opserv_reserved_nick_dict = dict_new();
4137     opserv_hostinfo_dict = dict_new();
4138     dict_set_free_keys(opserv_hostinfo_dict, free);
4139     dict_set_free_data(opserv_hostinfo_dict, opserv_free_hostinfo);
4140
4141     reg_new_user_func(opserv_new_user_check);
4142     reg_nick_change_func(opserv_alert_check_nick);
4143     reg_del_user_func(opserv_user_cleanup);
4144     reg_new_channel_func(opserv_channel_check);
4145     reg_del_channel_func(opserv_channel_delete);
4146     reg_join_func(opserv_join_check);
4147     reg_auth_func(opserv_staff_alert);
4148
4149     opserv_db_init();
4150     saxdb_register("OpServ", opserv_saxdb_read, opserv_saxdb_write);
4151     if (nick)
4152         service_register(opserv)->trigger = '?';
4153
4154     reg_exit_func(opserv_db_cleanup);
4155     message_register_table(msgtab);
4156 }