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