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