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