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