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