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