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