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