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