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