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