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