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