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