Bug fixes and cleanups
[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_NICK_UNRESERVED", "Nick $b%s$b is no longer reserve." },
164     { "OSMSG_NOT_RESERVED", "Nick $b%s$b is not reserved." },
165     { "OSMSG_ILLEGAL_REASON", "This channel is illegal." },
166     { "OSMSG_ILLEGAL_KILL_REASON", "Joined an illegal modeless channel - do not repeat." },
167     { "OSMSG_ILLEGAL_CHANNEL", "$b%s$b is an ILLEGAL channel. Do not re-join it." },
168     { "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." },
169     { "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." },
170     { "OSMSG_CLONE_ADDED", "Added clone $b%s$b." },
171     { "OSMSG_CLONE_FAILED", "Unable to add user $b%s$b." },
172     { "OSMSG_NOT_A_CLONE", "Har har.  $b%s$b isn't a clone." },
173     { "OSMSG_CLONE_REMOVED", "Removed clone $b%s$b." },
174     { "OSMSG_CLONE_JOINED", "$b%s$b has joined $b%s$b." },
175     { "OSMSG_CLONE_PARTED", "$b%s$b has left $b%s$b." },
176     { "OSMSG_OPS_GIVEN", "I have given ops in $b%s$b to $b%s$b." },
177     { "OSMSG_CLONE_SAID", "$b%s$b has spoken to $b%s$b." },
178     { "OSMSG_UNKNOWN_SUBCOMMAND", "$b%s$b is not a valid subcommand of $b%s$b." },
179     { "OSMSG_UNKNOWN_OPTION", "$b%s$b has not been set." },
180     { "OSMSG_OPTION_IS", "$b%s$b is set to $b%s$b." },
181     { "OSMSG_OPTION_ROOT", "The following keys can be queried:" },
182     { "OSMSG_OPTION_LIST", "$b%s$b contains the following values:" },
183     { "OSMSG_OPTION_KEYS", "$b%s$b contains the following keys:" },
184     { "OSMSG_OPTION_LIST_EMPTY", "Empty list." },
185     { "OSMSG_SET_NOT_SET", "$b%s$b does not exist, and cannot be set." },
186     { "OSMSG_SET_BAD_TYPE", "$b%s$b is not a string, and cannot be set." },
187     { "OSMSG_SET_SUCCESS", "$b%s$b has been set to $b%s$b." },
188     { "OSMSG_SETTIME_SUCCESS", "Set time for servers named like $b%s$b." },
189     { "OSMSG_BAD_ACTION", "Unrecognized trace action $b%s$b." },
190     { "OSMSG_USER_SEARCH_RESULTS", "The following users were found:" },
191     { "OSMSG_CHANNEL_SEARCH_RESULTS", "The following channels were found:" },
192     { "OSMSG_GLINE_SEARCH_RESULTS", "The following glines were found:" },
193     { "OSMSG_LOG_SEARCH_RESULTS", "The following log entries were found:" },
194     { "OSMSG_GSYNC_RUNNING", "Synchronizing glines from %s." },
195     { "OSMSG_GTRACE_FORMAT", "%s (issued %s by %s, expires %s): %s" },
196     { "OSMSG_GAG_APPLIED", "Gagged $b%s$b, affecting %d users." },
197     { "OSMSG_GAG_ADDED", "Gagged $b%s$b." },
198     { "OSMSG_REDUNDANT_GAG", "Gag $b%s$b is redundant." },
199     { "OSMSG_GAG_NOT_FOUND", "Could not find gag $b%s$b." },
200     { "OSMSG_NO_GAGS", "No gags have been set." },
201     { "OSMSG_UNGAG_APPLIED", "Ungagged $b%s$b, affecting %d users." },
202     { "OSMSG_UNGAG_ADDED", "Ungagged $b%s$b." },
203     { "OSMSG_TIMEQ_INFO", "%u events in timeq; next in %lu seconds." },
204     { "OSMSG_ALERT_EXISTS", "An alert named $b%s$b already exists." },
205     { "OSMSG_UNKNOWN_REACTION", "Unknown alert reaction $b%s$b." },
206     { "OSMSG_ADDED_ALERT", "Added alert named $b%s$b." },
207     { "OSMSG_REMOVED_ALERT", "Removed alert named $b%s$b." },
208     { "OSMSG_NO_SUCH_ALERT", "No alert named $b%s$b could be found." },
209     { "OSMSG_ALERT_IS", "%s (by %s, reaction %s): %s" },
210     { "OSMSG_ALERTS_LIST", "Current $O alerts:" },
211     { "OSMSG_REHASH_COMPLETE", "Completed rehash of configuration database." },
212     { "OSMSG_REHASH_FAILED", "Rehash of configuration database failed, previous configuration is intact." },
213     { "OSMSG_REOPEN_COMPLETE", "Closed and reopened all log files." },
214     { "OSMSG_RECONNECTING", "Reconnecting to my uplink." },
215     { "OSMSG_NUMERIC_COLLIDE", "Numeric %d (%s) is already in use." },
216     { "OSMSG_NAME_COLLIDE", "That name is already in use." },
217     { "OSMSG_SRV_CREATE_FAILED", "Server creation failed -- check log files." },
218     { "OSMSG_SERVER_JUPED", "Added new jupe server %s." },
219     { "OSMSG_SERVER_NOT_JUPE", "That server is not a juped server." },
220     { "OSMSG_SERVER_UNJUPED", "Server jupe removed." },
221     { "OSMSG_WARN_ADDED", "Added channel activity warning for $b%s$b (%s)" },
222     { "OSMSG_WARN_EXISTS", "Channel activity warning for $b%s$b already exists." },
223     { "OSMSG_WARN_DELETED", "Removed channel activity warning for $b%s$b" },
224     { "OSMSG_WARN_NOEXIST", "Channel activity warning for $b%s$b does not exist." },
225     { "OSMSG_WARN_LISTSTART", "Channel activity warnings:" },
226     { "OSMSG_WARN_LISTENTRY", "%s (%s)" },
227     { "OSMSG_WARN_LISTEND", "End of activity warning list." },
228     { "OSMSG_UPLINK_CONNECTING", "Establishing connection with %s (%s:%d)." },
229     { "OSMSG_CURRENT_UPLINK", "$b%s$b is already the current uplink." },
230     { "OSMSG_INVALID_UPLINK", "$b%s$b is not a valid uplink name." },
231     { "OSMSG_UPLINK_DISABLED", "$b%s$b is a disabled or unavailable uplink." },
232     { "OSMSG_UPLINK_START", "Uplink $b%s$b:" },
233     { "OSMSG_UPLINK_ADDRESS", "Address: %s:%d" },
234     { "OSMSG_STUPID_GLINE", "Gline %s?  Now $bthat$b would be smooth." },
235     { "OSMSG_ACCOUNTMASK_AUTHED", "Invalid criteria: it is impossible to match an account mask but not be authed" },
236     { "OSMSG_CHANINFO_HEADER", "%s Information" },
237     { "OSMSG_CHANINFO_TIMESTAMP", "Created on: %a %b %d %H:%M:%S %Y (%s)" },
238     { "OSMSG_CHANINFO_MODES", "Modes: %s" },
239     { "OSMSG_CHANINFO_MODES_BADWORD", "Modes: %s; bad-word channel" },
240     { "OSMSG_CHANINFO_TOPIC", "Topic (set by %%s, %a %b %d %H:%M:%S %Y): %%s" },
241     { "OSMSG_CHANINFO_TOPIC_UNKNOWN", "Topic: (none / not gathered)" },
242     { "OSMSG_CHANINFO_BAN_COUNT", "Bans (%d):" },
243     { "OSMSG_CHANINFO_BAN", "%%s by %%s (%a %b %d %H:%M:%S %Y)" },
244     { "OSMSG_CHANINFO_MANY_USERS", "%d users (\"/msg $S %s %s users\" for the list)" },
245     { "OSMSG_CHANINFO_USER_COUNT", "Users (%d):" },
246     { "OSMSG_CSEARCH_CHANNEL_INFO", "%s [%d users] %s %s" },
247     { NULL, NULL }
248 };
249
250 #define OPSERV_SYNTAX() svccmd_send_help(user, opserv, cmd)
251
252 typedef int (*discrim_search_func)(struct userNode *match, void *extra);
253
254 struct userNode *opserv;
255
256 static dict_t opserv_chan_warn; /* data is char* */
257 static dict_t opserv_reserved_nick_dict; /* data is struct userNode* */
258 static struct string_list *opserv_bad_words;
259 static dict_t opserv_exempt_channels; /* data is not used */
260 static dict_t opserv_trusted_hosts; /* data is struct trusted_host* */
261 static dict_t opserv_hostinfo_dict; /* data is struct opserv_hostinfo* */
262 static dict_t opserv_user_alerts; /* data is struct opserv_user_alert* */
263 static dict_t opserv_nick_based_alerts; /* data is struct opserv_user_alert* */
264 static dict_t opserv_channel_alerts; /* data is struct opserv_user_alert* */
265 static struct module *opserv_module;
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 #define opserv_debug(format...) do { if (opserv_conf.debug_channel) send_channel_notice(opserv_conf.debug_channel , opserv , ## format); } while (0)
369 #define opserv_alert(format...) do { if (opserv_conf.alert_channel) send_channel_notice(opserv_conf.alert_channel , opserv , ## format); } while (0)
370
371 /* A lot of these commands are very similar to what ChanServ can do,
372  * but OpServ can do them even on channels that aren't registered.
373  */
374
375 static MODCMD_FUNC(cmd_access)
376 {
377     struct handle_info *hi;
378     const char *target;
379     unsigned int res;
380
381     target = (argc > 1) ? (const char*)argv[1] : user->nick;
382     if (!irccasecmp(target, "*")) {
383         nickserv_show_oper_accounts(user, cmd);
384         return 1;
385     }
386     if (!(hi = modcmd_get_handle_info(user, target)))
387         return 0;
388     res = (argc > 2) ? oper_try_set_access(user, cmd->parent->bot, hi, strtoul(argv[2], NULL, 0)) : 0;
389     reply("OSMSG_USER_ACCESS_IS", target, hi->handle, hi->opserv_level);
390     return res;
391 }
392
393 static MODCMD_FUNC(cmd_ban)
394 {
395     struct mod_chanmode change;
396     struct userNode *victim;
397
398     change.modes_set = change.modes_clear = 0;
399     change.argc = 1;
400     change.args[0].mode = MODE_BAN;
401     if (is_ircmask(argv[1]))
402         change.args[0].hostmask = strdup(argv[1]);
403     else if ((victim = GetUserH(argv[1])))
404         change.args[0].hostmask = generate_hostmask(victim, 0);
405     else {
406         reply("OSMSG_INVALID_IRCMASK", argv[1]);
407         return 0;
408     }
409     modcmd_chanmode_announce(&change);
410     reply("OSMSG_ADDED_BAN", change.args[0].hostmask, channel->name);
411     free((char*)change.args[0].hostmask);
412     return 1;
413 }
414
415 static MODCMD_FUNC(cmd_chaninfo)
416 {
417     char buffer[MAXLEN];
418     const char *fmt;
419     struct banNode *ban;
420     struct modeNode *moden;
421     unsigned int n;
422
423     reply("OSMSG_CHANINFO_HEADER", channel->name);
424     fmt = user_find_message(user, "OSMSG_CHANINFO_TIMESTAMP");
425     strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->timestamp));
426     send_message_type(4, user, cmd->parent->bot, "%s", buffer);
427     irc_make_chanmode(channel, buffer);
428     if (channel->bad_channel)
429         reply("OSMSG_CHANINFO_MODES_BADWORD", buffer);
430     else
431         reply("OSMSG_CHANINFO_MODES", buffer);
432     if (channel->topic_time) {
433         fmt = user_find_message(user, "OSMSG_CHANINFO_TOPIC");
434         strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->topic_time));
435         send_message_type(4, user, cmd->parent->bot, buffer, channel->topic_nick, channel->topic);
436     } else {
437         irc_fetchtopic(cmd->parent->bot, channel->name);
438         reply("OSMSG_CHANINFO_TOPIC_UNKNOWN");
439     }
440     if (channel->banlist.used) {
441         reply("OSMSG_CHANINFO_BAN_COUNT", channel->banlist.used);
442         fmt = user_find_message(user, "OSMSG_CHANINFO_BAN");
443         for (n = 0; n < channel->banlist.used; n++) {
444             ban = channel->banlist.list[n];
445             strftime(buffer, sizeof(buffer), fmt, localtime(&ban->set));
446             send_message_type(4, user, cmd->parent->bot, buffer, ban->ban, ban->who);
447         }
448     }
449     if ((argc < 2) && (channel->members.used >= 50)) {
450         /* early out unless they ask for users */
451         reply("OSMSG_CHANINFO_MANY_USERS", channel->members.used, argv[0], channel->name);
452         return 1;
453     }
454     reply("OSMSG_CHANINFO_USER_COUNT", channel->members.used);
455     for (n=0; n<channel->members.used; n++) {
456         moden = channel->members.list[n];
457         if (moden->modes & MODE_CHANOP)
458             send_message_type(4, user, cmd->parent->bot, " @%s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
459     }
460     for (n=0; n<channel->members.used; n++) {
461         moden = channel->members.list[n];
462         if ((moden->modes & (MODE_CHANOP|MODE_VOICE)) == MODE_VOICE)
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)) == 0)
468             send_message_type(4, user, cmd->parent->bot, "  %s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
469     }
470     return 1;
471 }
472
473 static MODCMD_FUNC(cmd_warn) 
474 {
475     char *reason, *message;
476
477     if (!IsChannelName(argv[1])) {
478         reply("OSMSG_NEED_CHANNEL", argv[0]);
479         return 0;
480     }
481     reason = dict_find(opserv_chan_warn, argv[1], NULL);
482     if (reason) {
483         reply("OSMSG_WARN_EXISTS", argv[1]);
484         return 0;
485     }
486     if (argv[2])
487         reason = strdup(unsplit_string(argv+2, argc-2, NULL));
488     else
489         reason = strdup("No reason");
490     dict_insert(opserv_chan_warn, strdup(argv[1]), reason);
491     reply("OSMSG_WARN_ADDED", argv[1], reason);
492     if (dict_find(channels, argv[1], NULL)) {
493         message = alloca(strlen(reason) + strlen(argv[1]) + 55);
494         sprintf(message, "Channel activity warning for channel %s: %s", argv[1], reason);
495         global_message(MESSAGE_RECIPIENT_OPERS, message);
496     }
497     return 1;
498 }
499
500 static MODCMD_FUNC(cmd_unwarn)
501 {
502     if ((argc < 2) || !IsChannelName(argv[1])) {
503         reply("OSMSG_NEED_CHANNEL", argv[0]);
504         return 0;
505     }
506     if (!dict_remove(opserv_chan_warn, argv[1])) {
507         reply("OSMSG_WARN_NOEXIST", argv[1]);
508         return 0;
509     }
510     reply("OSMSG_WARN_DELETED", argv[1]);
511     return 1;
512 }
513
514 static MODCMD_FUNC(cmd_clearbans)
515 {
516     struct mod_chanmode *change;
517     unsigned int ii;
518
519     change = mod_chanmode_alloc(channel->banlist.used);
520     for (ii=0; ii<channel->banlist.used; ii++) {
521         change->args[ii].mode = MODE_REMOVE | MODE_BAN;
522         change->args[ii].hostmask = channel->banlist.list[ii]->ban;
523     }
524     modcmd_chanmode_announce(change);
525     mod_chanmode_free(change);
526     reply("OSMSG_CLEARBANS_DONE", channel->name);
527     return 1;
528 }
529
530 static MODCMD_FUNC(cmd_clearmodes)
531 {
532     struct mod_chanmode change;
533
534     if (!channel->modes) {
535         reply("OSMSG_NO_CHANNEL_MODES", channel->name);
536         return 0;
537     }
538     change.modes_set = 0;
539     change.modes_clear = channel->modes;
540     change.argc = 0;
541     modcmd_chanmode_announce(&change);
542     reply("OSMSG_CLEARMODES_DONE", channel->name);
543     return 1;
544 }
545
546 static MODCMD_FUNC(cmd_deop)
547 {
548     struct mod_chanmode *change;
549     unsigned int arg, count;
550
551     change = mod_chanmode_alloc(argc-1);
552     for (arg = 1, count = 0; arg < argc; ++arg) {
553         struct userNode *victim = GetUserH(argv[arg]);
554         struct modeNode *mn;
555         if (!victim || IsService(victim)
556             || !(mn = GetUserMode(channel, victim))
557             || !(mn->modes & MODE_CHANOP))
558             continue;
559         change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
560         change->args[count++].member = mn;
561     }
562     if (count) {
563         change->argc = count;
564         modcmd_chanmode_announce(change);
565     }
566     mod_chanmode_free(change);
567     reply("OSMSG_DEOP_DONE");
568     return 1;
569 }
570
571 static MODCMD_FUNC(cmd_deopall)
572 {
573     struct mod_chanmode *change;
574     unsigned int ii, count;
575
576     change = mod_chanmode_alloc(channel->members.used);
577     for (ii = count = 0; ii < channel->members.used; ++ii) {
578         struct modeNode *mn = channel->members.list[ii];
579         if (IsService(mn->user) || !(mn->modes & MODE_CHANOP))
580             continue;
581         change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
582         change->args[count++].member = mn;
583     }
584     if (count) {
585         change->argc = count;
586         modcmd_chanmode_announce(change);
587     }
588     mod_chanmode_free(change);
589     reply("OSMSG_DEOPALL_DONE", channel->name);
590     return 1;
591 }
592
593 static MODCMD_FUNC(cmd_rehash)
594 {
595     extern char *services_config;
596
597     if (conf_read(services_config))
598         reply("OSMSG_REHASH_COMPLETE");
599     else
600         reply("OSMSG_REHASH_FAILED");
601     return 1;
602 }
603
604 static MODCMD_FUNC(cmd_reopen)
605 {
606     log_reopen();
607     reply("OSMSG_REOPEN_COMPLETE");
608     return 1;
609 }
610
611 static MODCMD_FUNC(cmd_reconnect)
612 {
613     reply("OSMSG_RECONNECTING");
614     irc_squit(self, "Reconnecting.", NULL);
615     return 1;
616 }
617
618 static MODCMD_FUNC(cmd_jupe)
619 {
620     extern int force_n2k;
621     struct server *newsrv;
622     unsigned int num;
623     char numeric[COMBO_NUMERIC_LEN+1], srvdesc[SERVERDESCRIPTMAX+1];
624
625     num = atoi(argv[2]);
626     if ((num < 64) && !force_n2k) {
627         inttobase64(numeric, num, 1);
628         inttobase64(numeric+1, 64*64-1, 2);
629     } else {
630         inttobase64(numeric, num, 2);
631         inttobase64(numeric+2, 64*64*64-1, 3);
632     }
633 #ifdef WITH_PROTOCOL_P10
634     if (GetServerN(numeric)) {
635         reply("OSMSG_NUMERIC_COLLIDE", num, numeric);
636         return 0;
637     }
638 #endif
639     if (GetServerH(argv[1])) {
640         reply("OSMSG_NAME_COLLIDE");
641         return 0;
642     }
643     snprintf(srvdesc, sizeof(srvdesc), "JUPE %s", unsplit_string(argv+3, argc-3, NULL));
644     newsrv = AddServer(self, argv[1], 1, now, now, numeric, srvdesc);
645     if (!newsrv) {
646         reply("OSMSG_SRV_CREATE_FAILED");
647         return 0;
648     }
649     irc_server(newsrv);
650     reply("OSMSG_SERVER_JUPED", argv[1]);
651     return 1;
652 }
653
654 static MODCMD_FUNC(cmd_unjupe)
655 {
656     struct server *srv;
657     char *reason;
658
659     srv = GetServerH(argv[1]);
660     if (!srv) {
661         reply("MSG_SERVER_UNKNOWN", argv[1]);
662         return 0;
663     }
664     if (strncmp(srv->description, "JUPE", 4)) {
665         reply("OSMSG_SERVER_NOT_JUPE");
666         return 0;
667     }
668     reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : "Unjuping server";
669     DelServer(srv, 1, reason);
670     reply("OSMSG_SERVER_UNJUPED");
671     return 1;
672 }
673
674 static MODCMD_FUNC(cmd_jump)
675 {
676     extern struct cManagerNode cManager;
677     void uplink_select(char *name);
678     struct uplinkNode *uplink_find(char *name);
679     struct uplinkNode *uplink;
680     char *target;
681
682     target = unsplit_string(argv+1, argc-1, NULL);
683
684     if (!strcmp(cManager.uplink->name, target)) {
685         reply("OSMSG_CURRENT_UPLINK", cManager.uplink->name);
686         return 0;
687     }
688
689     uplink = uplink_find(target);
690     if (!uplink) {
691         reply("OSMSG_INVALID_UPLINK", target);
692         return 0;
693     }
694     if (uplink->flags & UPLINK_UNAVAILABLE) {
695         reply("OSMSG_UPLINK_DISABLED", uplink->name);
696         return 0;
697     }
698
699     reply("OSMSG_UPLINK_CONNECTING", uplink->name, uplink->host, uplink->port);
700     uplink_select(target);
701     irc_squit(self, "Reconnecting.", NULL);
702     return 1;
703 }
704
705 static MODCMD_FUNC(cmd_die)
706 {
707     char *reason, *text;
708
709     text = unsplit_string(argv+1, argc-1, NULL);
710     reason = alloca(strlen(text) + strlen(user->nick) + 20);
711     sprintf(reason, "Disconnected by %s [%s]", user->nick, text);
712     irc_squit(self, reason, text);
713     quit_services = 1;
714     return 1;
715 }
716
717 static MODCMD_FUNC(cmd_restart)
718 {
719     extern int services_argc;
720     extern char **services_argv;
721     char **restart_argv, *reason, *text;
722
723     text = unsplit_string(argv+1, argc-1, NULL);
724     reason = alloca(strlen(text) + strlen(user->nick) + 17);
725     sprintf(reason, "Restarted by %s [%s]", user->nick, text);
726     irc_squit(self, reason, text);
727
728     /* Append a NULL to the end of argv[]. */
729     restart_argv = (char **)alloca((services_argc + 1) * sizeof(char *));
730     memcpy(restart_argv, services_argv, services_argc * sizeof(char *));
731     restart_argv[services_argc] = NULL;
732
733     call_exit_funcs();
734
735     /* Don't blink. */
736     execv(services_argv[0], restart_argv);
737
738     /* If we're still here, that means something went wrong. Reconnect. */
739     return 1;
740 }
741
742 static struct gline *
743 opserv_block(struct userNode *target, char *src_handle, char *reason, unsigned long duration)
744 {
745     char *mask;
746     mask = alloca(MAXLEN);
747     snprintf(mask, MAXLEN, "*@%s", target->hostname);
748     if (!reason) {
749         reason = alloca(MAXLEN);
750         snprintf(reason, MAXLEN, "G-line requested by %s.", src_handle);
751     }
752     if (!duration) duration = opserv_conf.block_gline_duration;
753     return gline_add(src_handle, mask, duration, reason, now, 1);
754 }
755
756 static MODCMD_FUNC(cmd_block)
757 {
758     struct userNode *target;
759     struct gline *gline;
760     char *reason;
761
762     target = GetUserH(argv[1]);
763     if (!target) {
764         reply("MSG_NICK_UNKNOWN", argv[1]);
765         return 0;
766     }
767     if (IsService(target)) {
768         reply("MSG_SERVICE_IMMUNE", target->nick);
769         return 0;
770     }
771     reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : NULL;
772     gline = opserv_block(target, user->handle_info->handle, reason, 0);
773     reply("OSMSG_GLINE_ISSUED", gline->target);
774     return 1;
775 }
776
777 static MODCMD_FUNC(cmd_gline)
778 {
779     unsigned long duration;
780     char *reason;
781     struct gline *gline;
782
783     reason = unsplit_string(argv+3, argc-3, NULL);
784     if (!is_gline(argv[1]) && !IsChannelName(argv[1]) && (argv[1][0] != '&')) {
785         reply("MSG_INVALID_GLINE", argv[1]);
786         return 0;
787     }
788     if (!argv[1][strspn(argv[1], "#&*?@.")] && (strlen(argv[1]) < 10)) {
789         reply("OSMSG_STUPID_GLINE", argv[1]);
790         return 0;
791     }
792     duration = ParseInterval(argv[2]);
793     if (!duration) {
794         reply("MSG_INVALID_DURATION", argv[2]);
795         return 0;
796     }
797     gline = gline_add(user->handle_info->handle, argv[1], duration, reason, now, 1);
798     reply("OSMSG_GLINE_ISSUED", gline->target);
799     return 1;
800 }
801
802 static MODCMD_FUNC(cmd_ungline)
803 {
804     if (gline_remove(argv[1], 1))
805         reply("OSMSG_GLINE_REMOVED", argv[1]);
806     else
807         reply("OSMSG_GLINE_FORCE_REMOVED", argv[1]);
808     return 1;
809 }
810
811 static MODCMD_FUNC(cmd_refreshg)
812 {
813     if (argc > 1) {
814         unsigned int count;
815         dict_iterator_t it;
816         struct server *srv;
817
818         for (it=dict_first(servers), count=0; it; it=iter_next(it)) {
819             srv = iter_data(it);
820             if ((srv == self) || !match_ircglob(srv->name, argv[1]))
821                 continue;
822             gline_refresh_server(srv);
823             reply("OSMSG_GLINES_ONE_REFRESHED", srv->name);
824             count++;
825         }
826         if (!count) {
827             reply("MSG_SERVER_UNKNOWN", argv[1]);
828             return 0;
829         }
830     } else {
831         gline_refresh_all();
832         reply("OSMSG_GLINES_REFRESHED");
833     }
834     return 1;
835 }
836
837 static void
838 opserv_ison(struct userNode *tell, struct userNode *target, const char *message)
839 {
840     struct modeNode *mn;
841     unsigned int count, here_len, n, maxlen;
842     char buff[MAXLEN];
843
844     maxlen = tell->handle_info ? tell->handle_info->screen_width : 0;
845     if (!maxlen)
846         maxlen = MAX_LINE_SIZE;
847     for (n=count=0; n<target->channels.used; n++) {
848         mn = target->channels.list[n];
849         here_len = strlen(mn->channel->name);
850         if ((count + here_len + 4) > maxlen) {
851             buff[count] = 0;
852             send_message(tell, opserv, message, buff);
853             count = 0;
854         }
855         if (mn->modes & MODE_CHANOP)
856             buff[count++] = '@';
857         if (mn->modes & MODE_VOICE)
858             buff[count++] = '+';
859         memcpy(buff+count, mn->channel->name, here_len);
860         count += here_len;
861         buff[count++] = ' ';
862     }
863     if (count) {
864         buff[count] = 0;
865         send_message(tell, opserv, message, buff);
866     }
867 }
868
869 static MODCMD_FUNC(cmd_inviteme)
870 {
871     struct userNode *target;
872
873     if (argc < 2) {
874         target = user;
875     } else {
876         target = GetUserH(argv[1]);
877         if (!target) {
878             reply("MSG_NICK_UNKNOWN", argv[1]);
879             return 0;
880         }
881     }
882     if (opserv_conf.debug_channel == NULL) {
883         reply("OSMSG_NO_DEBUG_CHANNEL");
884         return 0;
885     }
886     if (GetUserMode(opserv_conf.debug_channel, user)) {
887         reply("OSMSG_ALREADY_THERE", channel->name);
888         return 0;
889     }
890     irc_invite(cmd->parent->bot, target, opserv_conf.debug_channel);
891     if (target != user)
892         reply("OSMSG_INVITE_DONE", target->nick, opserv_conf.debug_channel->name);
893     return 1;
894 }
895
896 static MODCMD_FUNC(cmd_invite)
897 {
898     if (GetUserMode(channel, user)) {
899         reply("OSMSG_ALREADY_THERE", channel->name);
900         return 0;
901     }
902     irc_invite(cmd->parent->bot, user, channel);
903     return 1;
904 }
905
906 static MODCMD_FUNC(cmd_join)
907 {
908     struct userNode *bot = cmd->parent->bot;
909
910     if (!IsChannelName(argv[1])) {
911         reply("MSG_NOT_CHANNEL_NAME");
912         return 0;
913     } else if (!(channel = GetChannel(argv[1]))) {
914         channel = AddChannel(argv[1], now, NULL, NULL);
915         AddChannelUser(bot, channel)->modes |= MODE_CHANOP;
916     } else if (GetUserMode(channel, bot)) {
917         reply("OSMSG_ALREADY_JOINED", channel->name);
918         return 0;
919     } else {
920         struct mod_chanmode change;
921         change.modes_set = change.modes_clear = 0;
922         change.argc = 1;
923         change.args[0].mode = MODE_CHANOP;
924         change.args[0].member = AddChannelUser(bot, channel);
925         modcmd_chanmode_announce(&change);
926     }
927     irc_fetchtopic(bot, channel->name);
928     reply("OSMSG_JOIN_DONE", channel->name);
929     return 1;
930 }
931
932 static MODCMD_FUNC(cmd_kick)
933 {
934     struct userNode *target;
935     char *reason;
936
937     if (argc < 3) {
938         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
939         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
940     } else {
941         reason = unsplit_string(argv+2, argc-2, NULL);
942     }
943     target = GetUserH(argv[1]);
944     if (!target) {
945         reply("MSG_NICK_UNKNOWN", argv[1]);
946         return 0;
947     }
948     if (!GetUserMode(channel, target)) {
949         reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
950         return 0;
951     }
952     KickChannelUser(target, channel, cmd->parent->bot, reason);
953     return 1;
954 }
955
956 static MODCMD_FUNC(cmd_kickall)
957 {
958     unsigned int limit, n, inchan;
959     struct modeNode *mn;
960     char *reason;
961     struct userNode *bot = cmd->parent->bot;
962
963     /* ircu doesn't let servers KICK users, so if OpServ's not in the
964      * channel, we have to join it in temporarily. */
965     if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
966         struct mod_chanmode change;
967         memset(&change, 0, sizeof(change));
968         change.args[0].mode = MODE_CHANOP;
969         change.args[0].member = AddChannelUser(bot, channel);
970         modcmd_chanmode_announce(&change);
971     }
972     if (argc < 2) {
973         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
974         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
975     } else {
976         reason = unsplit_string(argv+1, argc-1, NULL);
977     }
978     limit = user->handle_info->opserv_level;
979     for (n=channel->members.used; n>0;) {
980         mn = channel->members.list[--n];
981         if (IsService(mn->user)
982             || (mn->user->handle_info
983                 && (mn->user->handle_info->opserv_level >= limit))) {
984             continue;
985         }
986         KickChannelUser(mn->user, channel, bot, reason);
987     }
988     if (!inchan)
989         DelChannelUser(bot, channel, "My work here is done", 0);
990     reply("OSMSG_KICKALL_DONE", channel->name);
991     return 1;
992 }
993
994 static MODCMD_FUNC(cmd_kickban)
995 {
996     struct mod_chanmode change;
997     struct userNode *target;
998     char *reason;
999     char *mask;
1000
1001     if (argc == 2) {
1002         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1003         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1004     } else {
1005         reason = unsplit_string(argv+2, argc-2, NULL);
1006     }
1007     target = GetUserH(argv[1]);
1008     if (!target) {
1009         reply("MSG_NICK_UNKNOWN", argv[1]);
1010         return 0;
1011     }
1012     if (!GetUserMode(channel, target)) {
1013         reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
1014         return 0;
1015     }
1016     change.modes_set = change.modes_clear = 0;
1017     change.argc = 1;
1018     change.args[0].mode = MODE_BAN;
1019     change.args[0].hostmask = mask = generate_hostmask(target, 0);
1020     modcmd_chanmode_announce(&change);
1021     KickChannelUser(target, channel, cmd->parent->bot, reason);
1022     free(mask);
1023     return 1;
1024 }
1025
1026 static MODCMD_FUNC(cmd_kickbanall)
1027 {
1028     struct modeNode *mn;
1029     struct userNode *bot = cmd->parent->bot;
1030     struct mod_chanmode *change;
1031     char *reason;
1032     unsigned int limit, n, inchan;
1033
1034     /* ircu doesn't let servers KICK users, so if OpServ's not in the
1035      * channel, we have to join it in temporarily. */
1036     if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
1037         change = mod_chanmode_alloc(2);
1038         change->args[0].mode = MODE_CHANOP;
1039         change->args[0].member = AddChannelUser(bot, channel);
1040         change->args[1].mode = MODE_BAN;
1041         change->args[1].hostmask = "*!*@*";
1042     } else {
1043         change = mod_chanmode_alloc(1);
1044         change->args[0].mode = MODE_BAN;
1045         change->args[0].hostmask = "*!*@*";
1046     }
1047     modcmd_chanmode_announce(change);
1048     if (argc < 2) {
1049         reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1050         sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1051     } else {
1052         reason = unsplit_string(argv+1, argc-1, NULL);
1053     }
1054     /* now kick them */
1055     limit = user->handle_info->opserv_level;
1056     for (n=channel->members.used; n>0; ) {
1057         mn = channel->members.list[--n];
1058         if (IsService(mn->user)
1059             || (mn->user->handle_info
1060                 && (mn->user->handle_info->opserv_level >= limit))) {
1061             continue;
1062         }
1063         KickChannelUser(mn->user, channel, bot, reason);
1064     }
1065     if (!inchan)
1066         DelChannelUser(bot, channel, "My work here is done", 0);
1067     reply("OSMSG_KICKALL_DONE", channel->name);
1068     return 1;    
1069 }
1070
1071 static MODCMD_FUNC(cmd_part)
1072 {
1073     char *reason;
1074
1075     if (!IsChannelName(argv[1])) {
1076         reply("MSG_NOT_CHANNEL_NAME");
1077         return 0;
1078     }
1079     if ((channel = GetChannel(argv[1]))) {
1080         if (!GetUserMode(channel, cmd->parent->bot)) {
1081             reply("OSMSG_NOT_ON_CHANNEL", cmd->parent->bot->nick, channel->name);
1082             return 0;
1083         }
1084         reason = (argc < 3) ? "Leaving." : unsplit_string(argv+2, argc-2, NULL);
1085         reply("OSMSG_LEAVING", channel->name);
1086         DelChannelUser(cmd->parent->bot, channel, reason, 0);
1087     }
1088     return 1;
1089 }
1090
1091 static MODCMD_FUNC(cmd_mode)
1092 {
1093     if (!modcmd_chanmode(argv+1, argc-1, MCP_ALLOW_OVB|MCP_KEY_FREE|MC_ANNOUNCE)) {
1094         reply("MSG_INVALID_MODES", unsplit_string(argv+1, argc-1, NULL));
1095         return 0;
1096     }
1097     reply("OSMSG_MODE_SET", channel->name);
1098     return 1;
1099 }
1100
1101 static MODCMD_FUNC(cmd_op)
1102 {
1103     struct mod_chanmode *change;
1104     unsigned int arg, count;
1105
1106     change = mod_chanmode_alloc(argc-1);
1107     for (arg = 1, count = 0; arg < argc; ++arg) {
1108         struct userNode *victim;
1109         struct modeNode *mn;
1110         if (!(victim = GetUserH(argv[arg])))
1111             continue;
1112         if (!(mn =  GetUserMode(channel, victim)))
1113             continue;
1114         if (!(mn->modes & MODE_CHANOP))
1115             continue;
1116         change->args[count].mode = MODE_CHANOP;
1117         change->args[count++].member = mn;
1118     }
1119     if (count) {
1120         change->argc = count;
1121         modcmd_chanmode_announce(change);
1122     }
1123     mod_chanmode_free(change);
1124     reply("OSMSG_OP_DONE");
1125     return 1;
1126 }
1127
1128 static MODCMD_FUNC(cmd_opall)
1129 {
1130     struct mod_chanmode *change;
1131     unsigned int ii, count;
1132
1133     change = mod_chanmode_alloc(channel->members.used);
1134     for (ii = count = 0; ii < channel->members.used; ++ii) {
1135         struct modeNode *mn = channel->members.list[ii];
1136         if (mn->modes & MODE_CHANOP)
1137             continue;
1138         change->args[count].mode = MODE_CHANOP;
1139         change->args[count++].member = mn;
1140     }
1141     if (count) {
1142         change->argc = count;
1143         modcmd_chanmode_announce(change);
1144     }
1145     mod_chanmode_free(change);
1146     reply("OSMSG_OPALL_DONE", channel->name);
1147     return 1;
1148 }
1149
1150 static MODCMD_FUNC(cmd_whois)
1151 {
1152     struct userNode *target;
1153     char buffer[128];
1154     int bpos, herelen;
1155
1156 #ifdef WITH_PROTOCOL_P10
1157     if (argv[1][0] == '*')
1158         target = GetUserN(argv[1]+1);
1159     else
1160         target = GetUserH(argv[1]);
1161 #else
1162     target = GetUserH(argv[1]);
1163 #endif
1164     if (!target) {
1165         reply("MSG_NICK_UNKNOWN", argv[1]);
1166         return 0;
1167     }
1168     reply("OSMSG_WHOIS_NICK", target->nick);
1169     reply("OSMSG_WHOIS_HOST", target->ident, target->hostname);
1170     reply("OSMSG_WHOIS_IP", inet_ntoa(target->ip));
1171     if (target->modes) {
1172         bpos = 0;
1173 #define buffer_cat(str) (herelen = strlen(str), memcpy(buffer+bpos, str, herelen), bpos += herelen)
1174         if (IsInvisible(target)) buffer[bpos++] = 'i';
1175         if (IsWallOp(target)) buffer[bpos++] = 'w';
1176         if (IsOper(target)) buffer[bpos++] = 'o';
1177         if (IsGlobal(target)) buffer[bpos++] = 'g';
1178         if (IsServNotice(target)) buffer[bpos++] = 's';
1179         if (IsHelperIrcu(target)) buffer[bpos++] = 'h';
1180         if (IsService(target)) buffer[bpos++] = 'k';
1181         if (IsDeaf(target)) buffer[bpos++] = 'd';
1182         if (IsHiddenHost(target)) buffer[bpos++] = 'x';
1183         if (IsGagged(target)) buffer_cat(" (gagged)");
1184         buffer[bpos] = 0;
1185         if (bpos > 0)
1186             reply("OSMSG_WHOIS_MODES", buffer);
1187     }
1188     reply("OSMSG_WHOIS_INFO", target->info);
1189 #ifdef WITH_PROTOCOL_P10
1190     reply("OSMSG_WHOIS_NUMERIC", target->numeric);
1191 #endif
1192     reply("OSMSG_WHOIS_SERVER", target->uplink->name);
1193     reply("OSMSG_WHOIS_ACCOUNT", (target->handle_info ? target->handle_info->handle : "Not authenticated"));
1194     intervalString(buffer, now - target->timestamp);
1195     reply("OSMSG_WHOIS_NICK_AGE", buffer);
1196     if (target->channels.used <= MAX_CHANNELS_WHOIS)
1197         opserv_ison(user, target, "OSMSG_WHOIS_CHANNELS");
1198     else
1199         reply("OSMSG_WHOIS_HIDECHANS");
1200     return 1;
1201 }
1202
1203 static MODCMD_FUNC(cmd_unban)
1204 {
1205     struct mod_chanmode change;
1206     change.modes_set = change.modes_clear = 0;
1207     change.argc = 1;
1208     change.args[0].mode = MODE_REMOVE | MODE_BAN;
1209     change.args[0].hostmask = argv[1];
1210     modcmd_chanmode_announce(&change);
1211     reply("OSMSG_UNBAN_DONE", channel->name);
1212     return 1;
1213 }
1214
1215 static MODCMD_FUNC(cmd_voiceall)
1216 {
1217     struct mod_chanmode *change;
1218     unsigned int ii, count;
1219
1220     change = mod_chanmode_alloc(channel->members.used);
1221     for (ii = count = 0; ii < channel->members.used; ++ii) {
1222         struct modeNode *mn = channel->members.list[ii];
1223         if (mn->modes & (MODE_CHANOP|MODE_VOICE))
1224             continue;
1225         change->args[count].mode = MODE_VOICE;
1226         change->args[count++].member = mn;
1227     }
1228     if (count) {
1229         change->argc = count;
1230         modcmd_chanmode_announce(change);
1231     }
1232     mod_chanmode_free(change);
1233     reply("OSMSG_CHANNEL_VOICED", channel->name);
1234     return 1;
1235 }
1236
1237 static MODCMD_FUNC(cmd_devoiceall)
1238 {
1239     struct mod_chanmode *change;
1240     unsigned int ii, count;
1241
1242     change = mod_chanmode_alloc(channel->members.used);
1243     for (ii = count = 0; ii < channel->members.used; ++ii) {
1244         struct modeNode *mn = channel->members.list[ii];
1245         if (mn->modes & MODE_VOICE)
1246             continue;
1247         change->args[count].mode = MODE_REMOVE | MODE_VOICE;
1248         change->args[count++].member = mn;
1249     }
1250     if (count) {
1251         change->argc = count;
1252         modcmd_chanmode_announce(change);
1253     }
1254     mod_chanmode_free(change);
1255     reply("OSMSG_CHANNEL_DEVOICED", channel->name);
1256     return 1;
1257 }
1258
1259 static MODCMD_FUNC(cmd_stats_bad) {
1260     dict_iterator_t it;
1261     unsigned int ii, end, here_len;
1262     char buffer[400];
1263
1264     /* Show the bad word list.. */
1265     for (ii=end=0; ii<opserv_bad_words->used; ii++) {
1266         here_len = strlen(opserv_bad_words->list[ii]);
1267         if ((end + here_len + 2) > sizeof(buffer)) {
1268             buffer[end] = 0;
1269             reply("OSMSG_BADWORD_LIST", buffer);
1270             end = 0;
1271         }
1272         memcpy(buffer+end, opserv_bad_words->list[ii], here_len);
1273         end += here_len;
1274         buffer[end++] = ' ';
1275     }
1276     buffer[end] = 0;
1277     reply("OSMSG_BADWORD_LIST", buffer);
1278
1279     /* Show the exemption list.. */
1280     for (it=dict_first(opserv_exempt_channels), end=0; it; it=iter_next(it)) {
1281         here_len = strlen(iter_key(it));
1282         if ((end + here_len + 2) > sizeof(buffer)) {
1283             buffer[end] = 0;
1284             reply("OSMSG_EXEMPTED_LIST", buffer);
1285             end = 0;
1286         }
1287         memcpy(buffer+end, iter_key(it), here_len);
1288         end += here_len;
1289         buffer[end++] = ' ';
1290     }
1291     buffer[end] = 0;
1292     reply("OSMSG_EXEMPTED_LIST", buffer);
1293     return 1;
1294 }
1295
1296 static MODCMD_FUNC(cmd_stats_glines) {
1297     reply("OSMSG_GLINE_COUNT", gline_count());
1298     return 1;
1299 }
1300
1301 static void
1302 trace_links(struct userNode *bot, struct userNode *user, struct server *server, unsigned int depth) {
1303     unsigned int nn, pos;
1304     char buffer[400];
1305
1306     for (nn=1; nn<=depth; nn<<=1) ;
1307     for (pos=0, nn>>=1; nn>1; ) {
1308         nn >>= 1;
1309         buffer[pos++] = (depth & nn) ? ((nn == 1) ? '`' : ' ') : '|';
1310         buffer[pos++] = (nn == 1) ? '-': ' ';
1311     }
1312     buffer[pos] = 0;
1313     send_message(user, bot, "OSMSG_LINKS_SERVER", buffer, server->name, server->clients, server->description);
1314     if (!server->children.used)
1315         return;
1316     for (nn=0; nn<server->children.used-1; nn++) {
1317         trace_links(bot, user, server->children.list[nn], depth<<1);
1318     }
1319     trace_links(bot, user, server->children.list[nn], (depth<<1)|1);
1320 }
1321
1322 static MODCMD_FUNC(cmd_stats_links) {
1323     trace_links(cmd->parent->bot, user, self, 1);
1324     return 1;
1325 }
1326
1327
1328 static MODCMD_FUNC(cmd_stats_max) {
1329     reply("OSMSG_MAX_CLIENTS", max_clients, asctime(localtime(&max_clients_time)));
1330     return 1;
1331 }
1332
1333 static MODCMD_FUNC(cmd_stats_network) {
1334     struct helpfile_table tbl;
1335     unsigned int nn, tot_clients;
1336     dict_iterator_t it;
1337
1338     tot_clients = dict_size(clients);
1339     reply("OSMSG_NETWORK_INFO", tot_clients, invis_clients, curr_opers.used);
1340     tbl.length = dict_size(servers)+1;
1341     tbl.width = 3;
1342     tbl.flags = TABLE_NO_FREE;
1343     tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
1344     tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
1345     tbl.contents[0][0] = "Server Name";
1346     tbl.contents[0][1] = "Clients";
1347     tbl.contents[0][2] = "Load";
1348     for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
1349         struct server *server = iter_data(it);
1350         char *buffer = malloc(32);
1351         tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
1352         tbl.contents[nn][0] = server->name;
1353         tbl.contents[nn][1] = buffer;
1354         sprintf(buffer, "%u", server->clients);
1355         tbl.contents[nn][2] = buffer + 16;
1356         sprintf(buffer+16, "%3.3g%%", ((double)server->clients/tot_clients)*100);
1357         nn++;
1358     }
1359     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1360     for (nn=1; nn<tbl.length; nn++) {
1361         free((char*)tbl.contents[nn][1]);
1362         free(tbl.contents[nn]);
1363     }
1364     free(tbl.contents[0]);
1365     free(tbl.contents);
1366     return 1;
1367 }
1368
1369 static MODCMD_FUNC(cmd_stats_network2) {
1370     struct helpfile_table tbl;
1371     unsigned int nn;
1372     dict_iterator_t it;
1373
1374     tbl.length = dict_size(servers)+1;
1375     tbl.width = 3;
1376     tbl.flags = TABLE_NO_FREE;
1377     tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
1378     tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
1379     tbl.contents[0][0] = "Server Name";
1380     tbl.contents[0][1] = "Numeric";
1381     tbl.contents[0][2] = "Link Time";
1382     for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
1383         struct server *server = iter_data(it);
1384         char *buffer = malloc(64);
1385         int ofs;
1386
1387         tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
1388         tbl.contents[nn][0] = server->name;
1389 #ifdef WITH_PROTOCOL_P10
1390         sprintf(buffer, "%s (%ld)", server->numeric, base64toint(server->numeric, strlen(server->numeric)));
1391 #else
1392         buffer[0] = 0;
1393 #endif
1394         tbl.contents[nn][1] = buffer;
1395         ofs = strlen(buffer) + 1;
1396         intervalString(buffer + ofs, now - server->link);
1397         if (server->self_burst) strcat(buffer + ofs, " Bursting");
1398         tbl.contents[nn][2] = buffer + ofs;
1399         nn++;
1400     }
1401     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
1402     for (nn=1; nn<tbl.length; nn++) {
1403         free((char*)tbl.contents[nn][1]);
1404         free(tbl.contents[nn]);
1405     }
1406     free(tbl.contents[0]);
1407     free(tbl.contents);
1408     return 1;
1409 }
1410
1411 static MODCMD_FUNC(cmd_stats_reserved) {
1412     dict_iterator_t it;
1413
1414     reply("OSMSG_RESERVED_LIST");
1415     for (it = dict_first(opserv_reserved_nick_dict); it; it = iter_next(it))
1416         send_message_type(4, user, cmd->parent->bot, "%s", iter_key(it));
1417     return 1;
1418 }
1419
1420 static MODCMD_FUNC(cmd_stats_trusted) {
1421     dict_iterator_t it;
1422     struct trusted_host *th;
1423     char length[INTERVALLEN], issued[INTERVALLEN], limit[32];
1424
1425     if (argc > 1) {
1426         th = dict_find(opserv_trusted_hosts, argv[1], NULL);
1427         if (th) {
1428             if (th->issued)
1429                 intervalString(issued, now - th->issued);
1430             if (th->expires)
1431                 intervalString(length, th->expires - now);
1432             if (th->limit)
1433                 sprintf(limit, "limit %lu", th->limit);
1434             reply("OSMSG_HOST_IS_TRUSTED",
1435                   th->ipaddr,
1436                   (th->limit ? limit : "no limit"),
1437                   (th->issued ? issued : "some time"),
1438                   (th->issuer ? th->issuer : "<unknown>"),
1439                   (th->expires ? length : "never"),
1440                   (th->reason ? th->reason : "<unknown>"));
1441         } else {
1442             reply("OSMSG_HOST_NOT_TRUSTED", argv[1]);
1443         }
1444     } else {
1445         reply("OSMSG_TRUSTED_LIST");
1446         for (it = dict_first(opserv_trusted_hosts); it; it = iter_next(it)) {
1447             th = iter_data(it);
1448             if (th->issued)
1449                 intervalString(issued, now - th->issued);
1450             if (th->expires)
1451                 intervalString(length, th->expires - now);
1452             if (th->limit)
1453                 sprintf(limit, "limit %lu", th->limit);
1454             reply("OSMSG_HOST_IS_TRUSTED", iter_key(it),
1455                   (th->limit ? limit : "no limit"),
1456                   (th->issued ? issued : "some time"),
1457                   (th->issuer ? th->issuer : "<unknown>"),
1458                   (th->expires ? length : "never"),
1459                   (th->reason ? th->reason : "<unknown>"));
1460         }
1461     }
1462     return 1;
1463 }
1464
1465 static MODCMD_FUNC(cmd_stats_uplink) {
1466     extern struct cManagerNode cManager;
1467     struct uplinkNode *uplink;
1468
1469     uplink = cManager.uplink;
1470     reply("OSMSG_UPLINK_START", uplink->name);
1471     reply("OSMSG_UPLINK_ADDRESS", uplink->host, uplink->port);
1472     return 1;
1473 }
1474
1475 static MODCMD_FUNC(cmd_stats_uptime) {
1476     char uptime[INTERVALLEN];
1477     struct tms buf;
1478     extern time_t boot_time;
1479     extern int lines_processed;
1480     static long clocks_per_sec;
1481
1482     if (!clocks_per_sec) {
1483 #if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1484         clocks_per_sec = sysconf(_SC_CLK_TCK);
1485         if (clocks_per_sec <= 0)
1486 #endif
1487         {
1488             log_module(OS_LOG, LOG_ERROR, "Unable to query sysconf(_SC_CLK_TCK), output of 'stats uptime' will be wrong");
1489             clocks_per_sec = CLOCKS_PER_SEC;
1490         }
1491     }
1492     intervalString(uptime, time(NULL)-boot_time);
1493     times(&buf);
1494     reply("OSMSG_UPTIME_STATS",
1495           uptime, lines_processed,
1496           buf.tms_utime/(double)clocks_per_sec,
1497           buf.tms_stime/(double)clocks_per_sec);
1498     return 1;
1499 }
1500
1501 static MODCMD_FUNC(cmd_stats_alerts) {
1502     dict_iterator_t it;
1503     struct opserv_user_alert *alert;
1504     const char *reaction;
1505
1506     reply("OSMSG_ALERTS_LIST");
1507     for (it = dict_first(opserv_user_alerts); it; it = iter_next(it)) {
1508         alert = iter_data(it);
1509         switch (alert->reaction) {
1510         case REACT_NOTICE: reaction = "notice"; break;
1511         case REACT_KILL: reaction = "kill"; break;
1512         case REACT_GLINE: reaction = "gline"; break;
1513         default: reaction = "<unknown>"; break;
1514         }
1515         reply("OSMSG_ALERT_IS", iter_key(it), alert->owner, reaction, alert->text_discrim);
1516     }
1517     return 1;
1518 }
1519
1520 static MODCMD_FUNC(cmd_stats_gags) {
1521     struct gag_entry *gag;
1522     struct helpfile_table table;
1523     unsigned int nn;
1524
1525     if (!gagList) {
1526         reply("OSMSG_NO_GAGS");
1527         return 1;
1528     }
1529     for (nn=0, gag=gagList; gag; nn++, gag=gag->next) ;
1530     table.length = nn+1;
1531     table.width = 4;
1532     table.flags = TABLE_NO_FREE;
1533     table.contents = calloc(table.length, sizeof(char**));
1534     table.contents[0] = calloc(table.width, sizeof(char*));
1535     table.contents[0][0] = "Mask";
1536     table.contents[0][1] = "Owner";
1537     table.contents[0][2] = "Expires";
1538     table.contents[0][3] = "Reason";
1539     for (nn=1, gag=gagList; gag; nn++, gag=gag->next) {
1540         char expstr[INTERVALLEN];
1541         if (gag->expires) intervalString(expstr, gag->expires - now);
1542         else strcpy(expstr, "Never");
1543         table.contents[nn] = calloc(table.width, sizeof(char*));
1544         table.contents[nn][0] = gag->mask;
1545         table.contents[nn][1] = gag->owner;
1546         table.contents[nn][2] = strdup(expstr);
1547         table.contents[nn][3] = gag->reason;
1548     }
1549     table_send(cmd->parent->bot, user->nick, 0, NULL, table);
1550     for (nn=1; nn<table.length; nn++) {
1551         free((char*)table.contents[nn][2]);
1552         free(table.contents[nn]);
1553     }
1554     free(table.contents[0]);
1555     free(table.contents);
1556     return 1;
1557 }
1558
1559 static MODCMD_FUNC(cmd_stats_timeq) {
1560     reply("OSMSG_TIMEQ_INFO", timeq_size(), timeq_next()-now);
1561     return 1;
1562 }
1563
1564 static MODCMD_FUNC(cmd_stats_warn) {
1565     dict_iterator_t it;
1566
1567     reply("OSMSG_WARN_LISTSTART");
1568     for (it=dict_first(opserv_chan_warn); it; it=iter_next(it))
1569         reply("OSMSG_WARN_LISTENTRY", iter_key(it), (char*)iter_data(it));
1570     reply("OSMSG_WARN_LISTEND");
1571     return 1;
1572 }
1573
1574 static MODCMD_FUNC(cmd_dump)
1575 {
1576     char linedup[MAXLEN], *original;
1577
1578     original = unsplit_string(argv+1, argc-1, NULL);
1579     safestrncpy(linedup, original, sizeof(linedup));
1580     /* assume it's only valid IRC if we can parse it */
1581     if (parse_line(linedup, 1)) {
1582         irc_raw(original);
1583         reply("OSMSG_LINE_DUMPED");
1584     } else
1585         reply("OSMSG_RAW_PARSE_ERROR");
1586     return 1;
1587 }
1588
1589 static MODCMD_FUNC(cmd_raw)
1590 {
1591     char linedup[MAXLEN], *original;
1592
1593     original = unsplit_string(argv+1, argc-1, NULL);
1594     safestrncpy(linedup, original, sizeof(linedup));
1595     /* Try to parse the line before sending it; if it's too wrong,
1596      * maybe it will core us instead of our uplink. */
1597     parse_line(linedup, 1);
1598     irc_raw(original);
1599     reply("OSMSG_LINE_DUMPED");
1600     return 1;
1601 }
1602
1603 static struct userNode *
1604 opserv_add_reserve(struct svccmd *cmd, struct userNode *user, const char *nick, const char *ident, const char *host, const char *desc)
1605 {
1606     struct userNode *resv = GetUserH(nick);
1607     if (resv) {
1608         if (IsService(resv)) {
1609             reply("MSG_SERVICE_IMMUNE", resv->nick);
1610             return NULL;
1611         }
1612         if (resv->handle_info
1613             && resv->handle_info->opserv_level > user->handle_info->opserv_level) {
1614             reply("OSMSG_LEVEL_TOO_LOW");
1615             return NULL;
1616         }
1617     }
1618     if ((resv = AddClone(nick, ident, host, desc))) {
1619         dict_insert(opserv_reserved_nick_dict, resv->nick, resv);
1620     }
1621     return resv;
1622 }
1623
1624 static MODCMD_FUNC(cmd_collide)
1625 {
1626     struct userNode *resv;
1627
1628     resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
1629     if (resv) {
1630         reply("OSMSG_COLLIDED_NICK", resv->nick);
1631         return 1;
1632     } else {
1633         reply("OSMSG_CLONE_FAILED", argv[1]);
1634         return 0;
1635     }
1636 }
1637
1638 static MODCMD_FUNC(cmd_reserve)
1639 {
1640     struct userNode *resv;
1641
1642     resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
1643     if (resv) {
1644         resv->modes |= FLAGS_PERSISTENT;
1645         reply("OSMSG_RESERVED_NICK", resv->nick);
1646         return 1;
1647     } else {
1648         reply("OSMSG_CLONE_FAILED", argv[1]);
1649         return 0;
1650     }
1651 }
1652
1653 static int
1654 free_reserve(char *nick)
1655 {
1656     struct userNode *resv;
1657     unsigned int rlen;
1658     char *reason;
1659
1660     resv = dict_find(opserv_reserved_nick_dict, nick, NULL);
1661     if (!resv)
1662         return 0;
1663
1664     rlen = strlen(resv->nick)+strlen(OSMSG_PART_REASON);
1665     reason = alloca(rlen);
1666     snprintf(reason, rlen, OSMSG_PART_REASON, resv->nick);
1667     DelUser(resv, NULL, 1, reason);
1668     dict_remove(opserv_reserved_nick_dict, nick);
1669     return 1;
1670 }
1671
1672 static MODCMD_FUNC(cmd_unreserve)
1673 {
1674     if (free_reserve(argv[1]))
1675         reply("OSMSG_NICK_UNRESERVED", argv[1]);
1676     else
1677         reply("OSMSG_NOT_RESERVED", argv[1]);
1678     return 1;
1679 }
1680
1681 static void
1682 opserv_part_channel(void *data)
1683 {
1684     DelChannelUser(opserv, data, "Leaving.", 0);
1685 }
1686
1687 static int alert_check_user(const char *key, void *data, void *extra);
1688
1689 static int
1690 opserv_new_user_check(struct userNode *user)
1691 {
1692     struct opserv_hostinfo *ohi;
1693     struct gag_entry *gag;
1694
1695     /* Check to see if we should ignore them entirely. */
1696     if (IsLocal(user) || IsService(user))
1697         return 0;
1698
1699     /* Check for alerts, and stop if we find one that kills them. */
1700     if (dict_foreach(opserv_user_alerts, alert_check_user, user))
1701         return 1;
1702
1703     /* Gag them if appropriate. */
1704     for (gag = gagList; gag; gag = gag->next) {
1705         if (user_matches_glob(user, gag->mask, 1)) {
1706             gag_helper_func(user, NULL);
1707             break;
1708         }
1709     }
1710
1711     /* Add to host info struct */
1712     if (!(ohi = dict_find(opserv_hostinfo_dict, inet_ntoa(user->ip), NULL))) {
1713         ohi = calloc(1, sizeof(*ohi));
1714         dict_insert(opserv_hostinfo_dict, strdup(inet_ntoa(user->ip)), ohi);
1715         userList_init(&ohi->clients);
1716     }
1717     userList_append(&ohi->clients, user);
1718
1719     /* Only warn of new user floods outside of bursts. */
1720     if (!user->uplink->burst) {
1721         if (!policer_conforms(&opserv_conf.new_user_policer, now, 10)) {
1722             if (!new_user_flood) {
1723                 new_user_flood = 1;
1724                 opserv_alert("Warning: Possible new-user flood.");
1725             }
1726         } else {
1727             new_user_flood = 0;
1728         }
1729     }
1730
1731     /* Only warn or G-line if there's an untrusted max and their IP is sane. */
1732     if (opserv_conf.untrusted_max && user->ip.s_addr && (ntohl(user->ip.s_addr) != INADDR_LOOPBACK)) {
1733         struct trusted_host *th = dict_find(opserv_trusted_hosts, inet_ntoa(user->ip), NULL);
1734         unsigned int limit = th ? th->limit : opserv_conf.untrusted_max;
1735         if (!limit) {
1736             /* 0 means unlimited hosts */
1737         } else if (ohi->clients.used == limit) {
1738             unsigned int nn;
1739             for (nn=0; nn<ohi->clients.used; nn++)
1740                 send_message(ohi->clients.list[nn], opserv, "OSMSG_CLONE_WARNING");
1741         } else if (ohi->clients.used > limit) {
1742             char target[18];
1743             sprintf(target, "*@%s", inet_ntoa(user->ip));
1744             gline_add(opserv->nick, target, opserv_conf.clone_gline_duration, "AUTO Excessive connections from a single host.", now, 1);
1745         }
1746     }
1747
1748     return 0;
1749 }
1750
1751 static void
1752 opserv_user_cleanup(struct userNode *user, UNUSED_ARG(struct userNode *killer), UNUSED_ARG(const char *why))
1753 {
1754     struct opserv_hostinfo *ohi;
1755
1756     if (IsLocal(user)) {
1757         /* Try to remove it from the reserved nick dict without
1758          * calling free_reserve, because that would call DelUser(),
1759          * and we'd loop back to here. */
1760         dict_remove(opserv_reserved_nick_dict, user->nick);
1761         return;
1762     }
1763     if ((ohi = dict_find(opserv_hostinfo_dict, inet_ntoa(user->ip), NULL))) {
1764         userList_remove(&ohi->clients, user);
1765         if (ohi->clients.used == 0) dict_remove(opserv_hostinfo_dict, inet_ntoa(user->ip));
1766     }
1767 }
1768
1769 int
1770 opserv_bad_channel(const char *name)
1771 {
1772     unsigned int found;
1773
1774     dict_find(opserv_exempt_channels, name, &found);
1775     if (found)
1776         return 0;
1777
1778     if (gline_find(name))
1779         return 1;
1780
1781     for (found=0; found<opserv_bad_words->used; ++found)
1782         if (irccasestr(name, opserv_bad_words->list[found]))
1783             return 1;
1784
1785     return 0;
1786 }
1787
1788 static void
1789 opserv_shutdown_channel(struct chanNode *channel, const char *reason)
1790 {
1791     struct mod_chanmode *change;
1792     unsigned int nn;
1793
1794     change = mod_chanmode_alloc(2);
1795     change->modes_set = MODE_SECRET | MODE_INVITEONLY;
1796     change->args[0].mode = MODE_CHANOP;
1797     change->args[0].member = AddChannelUser(opserv, channel);
1798     change->args[1].mode = MODE_BAN;
1799     change->args[1].hostmask = "*!*@*";
1800     mod_chanmode_announce(opserv, channel, change);
1801     mod_chanmode_free(change);
1802     for (nn=channel->members.used; nn>0; ) {
1803         struct modeNode *mNode = channel->members.list[--nn];
1804         if (IsService(mNode->user))
1805             continue;
1806         KickChannelUser(mNode->user, channel, opserv, reason);
1807     }
1808     timeq_add(now + opserv_conf.purge_lock_delay, opserv_part_channel, channel);
1809 }
1810
1811 static void
1812 opserv_channel_check(struct chanNode *newchan)
1813 {
1814     char *warning;
1815
1816     if (!newchan->join_policer.params) {
1817         newchan->join_policer.last_req = now;
1818         newchan->join_policer.params = opserv_conf.join_policer_params;
1819     }
1820     if ((warning = dict_find(opserv_chan_warn, newchan->name, NULL))) {
1821         char message[MAXLEN];
1822         snprintf(message, sizeof(message), "Channel activity warning for channel %s: %s", newchan->name, warning);
1823         global_message(MESSAGE_RECIPIENT_OPERS, message);
1824     }
1825
1826     /* Wait until the join check to shut channels down. */
1827     newchan->bad_channel = opserv_bad_channel(newchan->name);
1828 }
1829
1830 static int
1831 opserv_join_check(struct modeNode *mNode)
1832 {
1833     struct userNode *user = mNode->user;
1834     struct chanNode *channel = mNode->channel;
1835     const char *msg;
1836
1837     if (IsService(user))
1838         return 0;
1839
1840     dict_foreach(opserv_channel_alerts, alert_check_user, user);
1841
1842     if (channel->bad_channel) {
1843         opserv_debug("Found $b%s$b in bad-word channel $b%s$b; removing the user.", user->nick, channel->name);
1844         if (channel->name[0] != '#')
1845             DelUser(user, opserv, 1, "OSMSG_ILLEGAL_KILL_REASON");
1846         else if (!GetUserMode(channel, opserv))
1847             opserv_shutdown_channel(channel, user_find_message(user, "OSMSG_ILLEGAL_REASON"));
1848         else {
1849             send_message(user, opserv, "OSMSG_ILLEGAL_CHANNEL", channel->name);
1850             msg = user_find_message(user, "OSMSG_ILLEGAL_REASON");
1851             KickChannelUser(user, channel, opserv, msg);
1852         }
1853         return 1;
1854     }
1855
1856     if (user->uplink->burst)
1857         return 0;
1858     if (policer_conforms(&channel->join_policer, now, 1.0)) {
1859         channel->join_flooded = 0;
1860         return 0;
1861     }
1862     if (!channel->join_flooded) {
1863         /* Don't moderate the channel unless it is activated and
1864            the number of users in the channel is over the threshold. */
1865         struct mod_chanmode change;
1866         change.modes_set = change.modes_clear = change.argc = 0;
1867         channel->join_flooded = 1;
1868         if (opserv_conf.join_flood_moderate && (channel->members.used > opserv_conf.join_flood_moderate_threshold)) {
1869             if (!GetUserMode(channel, opserv)) {
1870                 /* If we aren't in the channel, join it. */
1871                 change.args[0].mode = MODE_CHANOP;
1872                 change.args[0].member = AddChannelUser(opserv, channel);
1873                 change.argc++;
1874             }
1875             if (!(channel->modes & MODE_MODERATED))
1876                 change.modes_set |= MODE_MODERATED;
1877             if (change.modes_set || change.argc)
1878                 mod_chanmode_announce(opserv, channel, &change);
1879             send_target_message(0, channel->name, opserv, "OSMSG_FLOOD_MODERATE");
1880             opserv_alert("Warning: Possible join flood in %s (currently %d users; channel moderated).", channel->name, channel->members.used);
1881         } else {
1882             opserv_alert("Warning: Possible join flood in %s (currently %d users).", channel->name, channel->members.used);
1883         }
1884     }
1885     log_module(OS_LOG, LOG_INFO, "Join to %s during flood: "IDENT_FORMAT, channel->name, IDENT_DATA(user));
1886     return 0;
1887 }
1888
1889 static int
1890 opserv_add_bad_word(struct svccmd *cmd, struct userNode *user, const char *new_bad) {
1891     unsigned int bad_idx;
1892
1893     for (bad_idx = 0; bad_idx < opserv_bad_words->used; ++bad_idx) {
1894         char *orig_bad = opserv_bad_words->list[bad_idx];
1895         if (irccasestr(new_bad, orig_bad)) {
1896             if (user)
1897                 reply("OSMSG_BAD_REDUNDANT", new_bad, orig_bad);
1898             return 0;
1899         } else if (irccasestr(orig_bad, new_bad)) {
1900             if (user)
1901                 reply("OSMSG_BAD_GROWING", orig_bad, new_bad);
1902             free(orig_bad);
1903             opserv_bad_words->list[bad_idx] = strdup(new_bad);
1904             for (bad_idx++; bad_idx < opserv_bad_words->used; bad_idx++) {
1905                 orig_bad = opserv_bad_words->list[bad_idx];
1906                 if (!irccasestr(orig_bad, new_bad))
1907                     continue;
1908                 if (user)
1909                     reply("OSMSG_BAD_NUKING", orig_bad);
1910                 string_list_delete(opserv_bad_words, bad_idx);
1911                 bad_idx--;
1912                 free(orig_bad);
1913             }
1914             return 1;
1915         }
1916     }
1917     string_list_append(opserv_bad_words, strdup(new_bad));
1918     if (user)
1919         reply("OSMSG_ADDED_BAD", new_bad);
1920     return 1;
1921 }
1922
1923 static MODCMD_FUNC(cmd_addbad)
1924 {
1925     unsigned int arg, count;
1926     dict_iterator_t it;
1927     int bad_found, exempt_found;
1928
1929     /* Create the bad word if it doesn't exist. */
1930     bad_found = !opserv_add_bad_word(cmd, user, argv[1]);
1931
1932     /* Look for exception modifiers. */
1933     for (arg=2; arg<argc; arg++) {
1934         if (!irccasecmp(argv[arg], "except")) {
1935             reply("MSG_DEPRECATED_COMMAND", "addbad ... except", "addexempt");
1936             if (++arg > argc) {
1937                 reply("MSG_MISSING_PARAMS", "except");
1938                 break;
1939             }
1940             for (count = 0; (arg < argc) && IsChannelName(argv[arg]); arg++) {
1941                 dict_find(opserv_exempt_channels, argv[arg], &exempt_found);
1942                 if (!exempt_found) {
1943                     dict_insert(opserv_exempt_channels, strdup(argv[arg]), NULL);
1944                     count++;
1945                 }
1946             }
1947             reply("OSMSG_ADDED_EXEMPTIONS", count);
1948         } else {
1949             reply("MSG_DEPRECATED_COMMAND", "addbad (with modifiers)", "addbad");
1950             reply("OSMSG_BAD_MODIFIER", argv[arg]);
1951         }
1952     }
1953
1954     /* Scan for existing channels that match the new bad word. */
1955     if (!bad_found) {
1956         for (it = dict_first(channels); it; it = iter_next(it)) {
1957             struct chanNode *channel = iter_data(it);
1958
1959             if (!opserv_bad_channel(channel->name))
1960                 continue;
1961             channel->bad_channel = 1;
1962             if (channel->name[0] == '#')
1963                 opserv_shutdown_channel(channel, "OSMSG_ILLEGAL_REASON");
1964             else {
1965                 unsigned int nn;
1966                 for (nn=0; nn<channel->members.used; nn++) {
1967                     struct userNode *user = channel->members.list[nn]->user;
1968                     DelUser(user, cmd->parent->bot, 1, "OSMSG_ILLEGAL_KILL_REASON");
1969                 }
1970             }
1971         }
1972     }
1973
1974     return 1;
1975 }
1976
1977 static MODCMD_FUNC(cmd_delbad)
1978 {
1979     dict_iterator_t it;
1980     unsigned int nn;
1981
1982     for (nn=0; nn<opserv_bad_words->used; nn++) {
1983         if (!irccasecmp(opserv_bad_words->list[nn], argv[1])) {
1984             string_list_delete(opserv_bad_words, nn);
1985             for (it = dict_first(channels); it; it = iter_next(it)) {
1986                 channel = iter_data(it);
1987                 if (irccasestr(channel->name, argv[1])
1988                     && !opserv_bad_channel(channel->name)) {
1989                     DelChannelUser(cmd->parent->bot, channel, "Channel name no longer contains a bad word.", 1);
1990                     timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
1991                     channel->bad_channel = 0;
1992                 }
1993             }
1994             reply("OSMSG_REMOVED_BAD", argv[1]);
1995             return 1;
1996         }
1997     }
1998     reply("OSMSG_NOT_BAD_WORD", argv[1]);
1999     return 0;
2000 }
2001
2002 static MODCMD_FUNC(cmd_addexempt)
2003 {
2004     const char *chanName;
2005
2006     if ((argc > 1) && IsChannelName(argv[1])) {
2007         chanName = argv[1];
2008     } else {
2009         reply("MSG_NOT_CHANNEL_NAME");
2010         OPSERV_SYNTAX();
2011         return 0;
2012     }
2013     dict_insert(opserv_exempt_channels, strdup(chanName), NULL);
2014     channel = GetChannel(chanName);
2015     if (channel) {
2016         if (channel->bad_channel) {
2017             DelChannelUser(cmd->parent->bot, channel, "Channel is now exempt from bad-word checking.", 1);
2018             timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
2019         }
2020         channel->bad_channel = 0;
2021     }
2022     reply("OSMSG_ADDED_EXEMPTION", chanName);
2023     return 1;
2024 }
2025
2026 static MODCMD_FUNC(cmd_delexempt)
2027 {
2028     const char *chanName;
2029
2030     if ((argc > 1) && IsChannelName(argv[1])) {
2031         chanName = argv[1];
2032     } else {
2033         reply("MSG_NOT_CHANNEL_NAME");
2034         OPSERV_SYNTAX();
2035         return 0;
2036     }
2037     if (!dict_remove(opserv_exempt_channels, chanName)) {
2038         reply("OSMSG_NOT_EXEMPT", chanName);
2039         return 0;
2040     }
2041     reply("OSMSG_REMOVED_EXEMPTION", chanName);
2042     return 1;
2043 }
2044
2045 static void
2046 opserv_expire_trusted_host(void *data)
2047 {
2048     struct trusted_host *th = data;
2049     dict_remove(opserv_trusted_hosts, th->ipaddr);
2050 }
2051
2052 static void
2053 opserv_add_trusted_host(const char *ipaddr, unsigned int limit, const char *issuer, time_t issued, time_t expires, const char *reason)
2054 {
2055     struct trusted_host *th;
2056     th = calloc(1, sizeof(*th));
2057     if (!th)
2058         return;
2059     th->ipaddr = strdup(ipaddr);
2060     th->reason = reason ? strdup(reason) : NULL;
2061     th->issuer = issuer ? strdup(issuer) : NULL;
2062     th->issued = issued;
2063     th->limit = limit;
2064     th->expires = expires;
2065     dict_insert(opserv_trusted_hosts, th->ipaddr, th);
2066     if (th->expires)
2067         timeq_add(th->expires, opserv_expire_trusted_host, th);
2068 }
2069
2070 static void
2071 free_trusted_host(void *data)
2072 {
2073     struct trusted_host *th = data;
2074     free(th->ipaddr);
2075     free(th->reason);
2076     free(th->issuer);
2077     free(th);
2078 }
2079
2080 static MODCMD_FUNC(cmd_addtrust)
2081 {
2082     unsigned long interval;
2083     char *reason, *tmp;
2084     struct in_addr tmpaddr;
2085     int count;
2086
2087     if (dict_find(opserv_trusted_hosts, argv[1], NULL)) {
2088         reply("OSMSG_ALREADY_TRUSTED", argv[1]);
2089         return 0;
2090     }
2091
2092     if (!inet_aton(argv[1], &tmpaddr)) {
2093         reply("OSMSG_BAD_IP", argv[1]);
2094         return 0;
2095     }
2096
2097     count = strtoul(argv[2], &tmp, 10);
2098     if (!count || *tmp != '\0') {
2099         reply("OSMSG_BAD_NUMBER", argv[2]);
2100         return 0;
2101     }
2102
2103     interval = ParseInterval(argv[3]);
2104     if (!interval && strcmp(argv[3], "0")) {
2105         reply("MSG_INVALID_DURATION", argv[3]);
2106         return 0;
2107     }
2108
2109     reason = unsplit_string(argv+4, argc-4, NULL);
2110     opserv_add_trusted_host(argv[1], count, user->handle_info->handle, now, interval ? (now + interval) : 0, reason);
2111     reply("OSMSG_ADDED_TRUSTED");
2112     return 1;
2113 }
2114
2115 static MODCMD_FUNC(cmd_edittrust)
2116 {
2117     unsigned long interval;
2118     struct trusted_host *th;
2119     char *reason, *tmp;
2120     int count;
2121
2122     th = dict_find(opserv_trusted_hosts, argv[1], NULL);
2123     if (!th) {
2124         reply("OSMSG_NOT_TRUSTED", argv[1]);
2125         return 0;
2126     }
2127     count = strtoul(argv[2], &tmp, 10);
2128     if (!count || *tmp) {
2129         reply("OSMSG_BAD_NUMBER", argv[2]);
2130         return 0;
2131     }
2132     interval = ParseInterval(argv[3]);
2133     if (!interval && strcmp(argv[3], "0")) {
2134         reply("MSG_INVALID_DURATION", argv[3]);
2135         return 0;
2136     }
2137     reason = unsplit_string(argv+4, argc-4, NULL);
2138     if (th->expires)
2139         timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
2140
2141     free(th->reason);
2142     th->reason = strdup(reason);
2143     free(th->issuer);
2144     th->issuer = strdup(user->handle_info->handle);
2145     th->issued = now;
2146     th->limit = count;
2147     if (interval) {
2148         th->expires = now + interval;
2149         timeq_add(th->expires, opserv_expire_trusted_host, th);
2150     } else
2151         th->expires = 0;
2152     reply("OSMSG_UPDATED_TRUSTED", th->ipaddr);
2153     return 1;
2154 }
2155
2156 static MODCMD_FUNC(cmd_deltrust)
2157 {
2158     unsigned int n;
2159
2160     for (n=1; n<argc; n++) {
2161         struct trusted_host *th = dict_find(opserv_trusted_hosts, argv[n], NULL);
2162         if (!th)
2163             continue;
2164         if (th->expires)
2165             timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
2166         dict_remove(opserv_trusted_hosts, argv[n]);
2167     }
2168     reply("OSMSG_REMOVED_TRUSTED");
2169     return 1;
2170 }
2171
2172 /* This doesn't use dict_t because it's a little simpler to open-code the
2173  * comparisons (and simpler arg-passing for the ADD subcommand).
2174  */
2175 static MODCMD_FUNC(cmd_clone)
2176 {
2177     int i;
2178     struct userNode *clone;
2179
2180     clone = GetUserH(argv[2]);
2181     if (!irccasecmp(argv[1], "ADD")) {
2182         char *userinfo;
2183         char ident[USERLEN+1];
2184
2185         if (argc < 5) {
2186             reply("MSG_MISSING_PARAMS", argv[1]);
2187             OPSERV_SYNTAX();
2188             return 0;
2189         }
2190         if (clone) {
2191             reply("OSMSG_CLONE_EXISTS", argv[2]);
2192             return 0;
2193         }
2194         userinfo = unsplit_string(argv+4, argc-4, NULL);
2195         for (i=0; argv[3][i] && (i<USERLEN); i++) {
2196             if (argv[3][i] == '@') {
2197                 ident[i++] = 0;
2198                 break;
2199             } else {
2200                 ident[i] = argv[3][i];
2201             }
2202         }
2203         if (!argv[3][i] || (i==USERLEN)) {
2204             reply("OSMSG_NOT_A_HOSTMASK");
2205             return 0;
2206         }
2207         if (!(clone = AddClone(argv[2], ident, argv[3]+i, userinfo))) {
2208             reply("OSMSG_CLONE_FAILED", argv[2]);
2209             return 0;
2210         }
2211         reply("OSMSG_CLONE_ADDED", clone->nick);
2212         return 1;
2213     }
2214     if (!clone) {
2215         reply("MSG_NICK_UNKNOWN", argv[2]);
2216         return 0;
2217     }
2218     if (clone->uplink != self || IsService(clone)) {
2219         reply("OSMSG_NOT_A_CLONE", clone->nick);
2220         return 0;
2221     }
2222     if (!irccasecmp(argv[1], "REMOVE")) {
2223         const char *reason;
2224         if (argc > 3) {
2225             reason = unsplit_string(argv+3, argc-3, NULL);
2226         } else {
2227             char *tmp;
2228             tmp = alloca(strlen(clone->nick) + strlen(OSMSG_PART_REASON));
2229             sprintf(tmp, OSMSG_PART_REASON, clone->nick);
2230             reason = tmp;
2231         }
2232         DelUser(clone, NULL, 1, reason);
2233         reply("OSMSG_CLONE_REMOVED", argv[2]);
2234         return 1;
2235     }
2236     if (argc < 4) {
2237         reply("MSG_MISSING_PARAMS", argv[1]);
2238         OPSERV_SYNTAX();
2239         return 0;
2240     }
2241     channel = GetChannel(argv[3]);
2242     if (!irccasecmp(argv[1], "JOIN")) {
2243         if (!channel
2244             && !(channel = AddChannel(argv[3], now, NULL, NULL))) {
2245             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2246             return 0;
2247         }
2248         AddChannelUser(clone, channel);
2249         reply("OSMSG_CLONE_JOINED", clone->nick, channel->name);
2250         return 1;
2251     }
2252     if (!irccasecmp(argv[1], "PART")) {
2253         if (!channel) {
2254             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2255             return 0;
2256         }
2257         if (!GetUserMode(channel, clone)) {
2258             reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
2259             return 0;
2260         }
2261         reply("OSMSG_CLONE_PARTED", clone->nick, channel->name);
2262         DelChannelUser(clone, channel, "Leaving.", 0);
2263         return 1;
2264     }
2265     if (!irccasecmp(argv[1], "OP")) {
2266         struct mod_chanmode change;
2267         if (!channel) {
2268             reply("MSG_CHANNEL_UNKNOWN", argv[3]);
2269             return 0;
2270         }
2271         change.modes_set = change.modes_clear = 0;
2272         change.argc = 1;
2273         change.args[0].mode = MODE_CHANOP;
2274         change.args[0].member = GetUserMode(channel, clone);
2275         if (!change.args[0].member) {
2276             reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
2277             return 0;
2278         }
2279         modcmd_chanmode_announce(&change);
2280         reply("OSMSG_OPS_GIVEN", channel->name, clone->nick);
2281         return 1;
2282     }
2283     if (argc < 5) {
2284         reply("MSG_MISSING_PARAMS", argv[1]);
2285         OPSERV_SYNTAX();
2286         return 0;
2287     }
2288     if (!irccasecmp(argv[1], "SAY")) {
2289         char *text = unsplit_string(argv+4, argc-4, NULL);
2290         irc_privmsg(clone, argv[3], text);
2291         reply("OSMSG_CLONE_SAID", clone->nick, argv[3]);
2292         return 1;
2293     }
2294     reply("OSMSG_UNKNOWN_SUBCOMMAND", argv[1], argv[0]);
2295     return 0;
2296 }
2297
2298 static struct helpfile_expansion
2299 opserv_help_expand(const char *variable)
2300 {
2301     extern struct userNode *message_source;
2302     struct helpfile_expansion exp;
2303     struct service *service;
2304     struct svccmd *cmd;
2305     dict_iterator_t it;
2306     int row;
2307     unsigned int level;
2308
2309     if (!(service = service_find(message_source->nick))) {
2310         exp.type = HF_STRING;
2311         exp.value.str = NULL;
2312     } else 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(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(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 = dict_find(service->commands, variable+6, NULL);
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, "flags", "+oper", NULL);
2363     } else {
2364         return modcmd_register(opserv_module, name, func, min_argc, iflags, "level", buf, "flags", "+oper", 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 = dict_find(cmd->parent->commands, buf, NULL))) {
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 = dict_find(cmd->parent->commands, buf, NULL))
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 = dict_find(cmd->parent->commands, buf, NULL))
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 = dict_find(cmd->parent->commands, buf, NULL))) {
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 (opserv && 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 (opserv && 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 (opserv && 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 (opserv && 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     OS_LOG = log_register_type("OpServ", "file:opserv.log");
4011     if (nick)
4012         opserv = AddService(nick, "Oper Services");
4013     conf_register_reload(opserv_conf_read);
4014
4015     memset(level_strings, 0, sizeof(level_strings));
4016     opserv_module = module_register("OpServ", OS_LOG, "opserv.help", opserv_help_expand);
4017     opserv_define_func("ACCESS", cmd_access, 0, 0, 0);
4018     opserv_define_func("ADDALERT", cmd_addalert, 800, 0, 4);
4019     opserv_define_func("ADDALERT NOTICE", NULL, 0, 0, 0);
4020     opserv_define_func("ADDALERT GLINE", NULL, 900, 0, 0);
4021     opserv_define_func("ADDALERT KILL", NULL, 900, 0, 0);
4022     opserv_define_func("ADDBAD", cmd_addbad, 800, 0, 2);
4023     opserv_define_func("ADDEXEMPT", cmd_addexempt, 800, 0, 2);
4024     opserv_define_func("ADDTRUST", cmd_addtrust, 800, 0, 5);
4025     opserv_define_func("BAN", cmd_ban, 100, 2, 2);
4026     opserv_define_func("BLOCK", cmd_block, 100, 0, 2);
4027     opserv_define_func("CHANINFO", cmd_chaninfo, 0, 3, 0);
4028     opserv_define_func("CLEARBANS", cmd_clearbans, 300, 2, 0);
4029     opserv_define_func("CLEARMODES", cmd_clearmodes, 400, 2, 0);
4030     opserv_define_func("CLONE", cmd_clone, 999, 0, 3);
4031     opserv_define_func("COLLIDE", cmd_collide, 800, 0, 5);
4032     opserv_define_func("CSEARCH", cmd_csearch, 100, 0, 3);
4033     opserv_define_func("CSEARCH COUNT", cmd_csearch, 0, 0, 0);
4034     opserv_define_func("CSEARCH PRINT", cmd_csearch, 0, 0, 0);
4035     opserv_define_func("DELALERT", cmd_delalert, 800, 0, 2);
4036     opserv_define_func("DELBAD", cmd_delbad, 800, 0, 2);
4037     opserv_define_func("DELEXEMPT", cmd_delexempt, 800, 0, 2);
4038     opserv_define_func("DELTRUST", cmd_deltrust, 800, 0, 2);
4039     opserv_define_func("DEOP", cmd_deop, 100, 2, 2);
4040     opserv_define_func("DEOPALL", cmd_deopall, 400, 2, 0);
4041     opserv_define_func("DEVOICEALL", cmd_devoiceall, 300, 2, 0);
4042     opserv_define_func("DIE", cmd_die, 900, 0, 2);
4043     opserv_define_func("DUMP", cmd_dump, 999, 0, 2);
4044     opserv_define_func("EDITTRUST", cmd_edittrust, 800, 0, 5);
4045     opserv_define_func("GAG", cmd_gag, 600, 0, 4);
4046     opserv_define_func("GLINE", cmd_gline, 600, 0, 4);
4047     opserv_define_func("GSYNC", cmd_gsync, 600, 0, 0);
4048     opserv_define_func("GTRACE", cmd_gtrace, 100, 0, 3);
4049     opserv_define_func("GTRACE COUNT", NULL, 0, 0, 0);
4050     opserv_define_func("GTRACE PRINT", NULL, 0, 0, 0);
4051     opserv_define_func("INVITE", cmd_invite, 100, 2, 0);
4052     opserv_define_func("INVITEME", cmd_inviteme, 100, 0, 0);
4053     opserv_define_func("JOIN", cmd_join, 601, 0, 2);
4054     opserv_define_func("JUMP", cmd_jump, 900, 0, 2);
4055     opserv_define_func("JUPE", cmd_jupe, 900, 0, 4);
4056     opserv_define_func("KICK", cmd_kick, 100, 2, 2);
4057     opserv_define_func("KICKALL", cmd_kickall, 400, 2, 0);
4058     opserv_define_func("KICKBAN", cmd_kickban, 100, 2, 2);
4059     opserv_define_func("KICKBANALL", cmd_kickbanall, 450, 2, 0);
4060     opserv_define_func("LOG", cmd_log, 900, 0, 2);
4061     opserv_define_func("MODE", cmd_mode, 100, 2, 2);
4062     opserv_define_func("OP", cmd_op, 100, 2, 2);
4063     opserv_define_func("OPALL", cmd_opall, 400, 2, 0);
4064     opserv_define_func("PART", cmd_part, 601, 0, 2);
4065     opserv_define_func("QUERY", cmd_query, 0, 0, 0);
4066     opserv_define_func("RAW", cmd_raw, 999, 0, 2);
4067     opserv_define_func("RECONNECT", cmd_reconnect, 900, 0, 0);
4068     opserv_define_func("REFRESHG", cmd_refreshg, 600, 0, 0);
4069     opserv_define_func("REHASH", cmd_rehash, 900, 0, 0);
4070     opserv_define_func("REOPEN", cmd_reopen, 900, 0, 0);
4071     opserv_define_func("RESERVE", cmd_reserve, 800, 0, 5);
4072     opserv_define_func("RESTART", cmd_restart, 900, 0, 2);
4073     opserv_define_func("SET", cmd_set, 900, 0, 3);
4074     opserv_define_func("SETTIME", cmd_settime, 901, 0, 0);
4075     opserv_define_func("STATS ALERTS", cmd_stats_alerts, 0, 0, 0);
4076     opserv_define_func("STATS BAD", cmd_stats_bad, 0, 0, 0);
4077     opserv_define_func("STATS GAGS", cmd_stats_gags, 0, 0, 0);
4078     opserv_define_func("STATS GLINES", cmd_stats_glines, 0, 0, 0);
4079     opserv_define_func("STATS LINKS", cmd_stats_links, 0, 0, 0);
4080     opserv_define_func("STATS MAX", cmd_stats_max, 0, 0, 0);
4081     opserv_define_func("STATS NETWORK", cmd_stats_network, 0, 0, 0);
4082     opserv_define_func("STATS NETWORK2", cmd_stats_network2, 0, 0, 0);
4083     opserv_define_func("STATS RESERVED", cmd_stats_reserved, 0, 0, 0);
4084     opserv_define_func("STATS TIMEQ", cmd_stats_timeq, 0, 0, 0);
4085     opserv_define_func("STATS TRUSTED", cmd_stats_trusted, 0, 0, 0);
4086     opserv_define_func("STATS UPLINK", cmd_stats_uplink, 0, 0, 0);
4087     opserv_define_func("STATS UPTIME", cmd_stats_uptime, 0, 0, 0);
4088     opserv_define_func("STATS WARN", cmd_stats_warn, 0, 0, 0);
4089     opserv_define_func("TRACE", cmd_trace, 100, 0, 3);
4090     opserv_define_func("TRACE PRINT", NULL, 0, 0, 0);
4091     opserv_define_func("TRACE COUNT", NULL, 0, 0, 0);
4092     opserv_define_func("TRACE DOMAINS", NULL, 0, 0, 0);
4093     opserv_define_func("TRACE GLINE", NULL, 600, 0, 0);
4094     opserv_define_func("TRACE GAG", NULL, 600, 0, 0);
4095     opserv_define_func("TRACE KILL", NULL, 600, 0, 0);
4096     opserv_define_func("UNBAN", cmd_unban, 100, 2, 2);
4097     opserv_define_func("UNGAG", cmd_ungag, 600, 0, 2);
4098     opserv_define_func("UNGLINE", cmd_ungline, 600, 0, 2);
4099     modcmd_register(opserv_module, "GTRACE UNGLINE", NULL, 0, 0, "template", "ungline", NULL);
4100     opserv_define_func("UNJUPE", cmd_unjupe, 900, 0, 2);
4101     opserv_define_func("UNRESERVE", cmd_unreserve, 800, 0, 2);
4102     opserv_define_func("UNWARN", cmd_unwarn, 800, 0, 0);
4103     opserv_define_func("VOICEALL", cmd_voiceall, 300, 2, 0);
4104     opserv_define_func("WARN", cmd_warn, 800, 0, 2);
4105     opserv_define_func("WHOIS", cmd_whois, 0, 0, 2);
4106
4107     opserv_reserved_nick_dict = dict_new();
4108     opserv_hostinfo_dict = dict_new();
4109     dict_set_free_keys(opserv_hostinfo_dict, free);
4110     dict_set_free_data(opserv_hostinfo_dict, opserv_free_hostinfo);
4111
4112     reg_new_user_func(opserv_new_user_check);
4113     reg_nick_change_func(opserv_alert_check_nick);
4114     reg_del_user_func(opserv_user_cleanup);
4115     reg_new_channel_func(opserv_channel_check);
4116     reg_join_func(opserv_join_check);
4117     reg_auth_func(opserv_staff_alert);
4118
4119     opserv_db_init();
4120     saxdb_register("OpServ", opserv_saxdb_read, opserv_saxdb_write);
4121     if (nick)
4122         service_register(opserv, '?');
4123
4124     reg_exit_func(opserv_db_cleanup);
4125     message_register_table(msgtab);
4126 }