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