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