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