]> jfr.im git - irc/evilnet/x3.git/blob - src/opserv.c
make it so that lamers do not affect users above inviteme level in the channel
[irc/evilnet/x3.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 x3.
5 *
6 * x3 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 "common.h"
23 #include "gline.h"
24 #include "global.h"
25 #include "nickserv.h"
26 #include "modcmd.h"
27 #include "modules.h"
28 #include "proto.h"
29 #include "opserv.h"
30 #include "timeq.h"
31 #include "saxdb.h"
32 #include "shun.h"
33
34 #include <tre/regex.h>
35
36 #ifdef HAVE_SYS_TIMES_H
37 #include <sys/times.h>
38 #endif
39 #ifdef HAVE_NETINET_IN_H
40 #include <netinet/in.h>
41 #endif
42 #ifdef HAVE_ARPA_INET_H
43 #include <arpa/inet.h>
44 #endif
45
46
47 #define OPSERV_CONF_NAME "services/opserv"
48
49 #define KEY_ALERT_CHANNEL "alert_channel"
50 #define KEY_ALERT_CHANNEL_MODES "alert_channel_modes"
51 #define KEY_DEBUG_CHANNEL "debug_channel"
52 #define KEY_DEBUG_CHANNEL_MODES "debug_channel_modes"
53 #define KEY_UNTRUSTED_MAX "untrusted_max"
54 #define KEY_PURGE_LOCK_DELAY "purge_lock_delay"
55 #define KEY_JOIN_FLOOD_MODERATE "join_flood_moderate"
56 #define KEY_JOIN_FLOOD_MODERATE_THRESH "join_flood_moderate_threshold"
57 #define KEY_NICK "nick"
58 #define KEY_JOIN_POLICER "join_policer"
59 #define KEY_NEW_USER_POLICER "new_user_policer"
60 #define KEY_AUTOJOIN_CHANNELS "autojoin_channels"
61 #define KEY_REASON "reason"
62 #define KEY_RESERVES "reserves"
63 #define KEY_IDENT "username" /* for compatibility with 1.0 DBs */
64 #define KEY_HOSTNAME "hostname"
65 #define KEY_DESC "description"
66 #define KEY_BAD_WORDS "bad"
67 #define KEY_EXEMPT_CHANNELS "exempt"
68 #define KEY_SECRET_WORDS "secret"
69 #define KEY_TRUSTED_HOSTS "trusted"
70 #define KEY_OWNER "owner"
71 #define KEY_GAGS "gags"
72 #define KEY_ALERTS "alerts"
73 #define KEY_REACTION "reaction"
74 #define KEY_DISCRIM "discrim"
75 #define KEY_WARN "chanwarn"
76 #define KEY_MAX "max"
77 #define KEY_TIME "time"
78 #define KEY_MAX_CLIENTS "max_clients"
79 #define KEY_LIMIT "limit"
80 #define KEY_EXPIRES "expires"
81 #define KEY_STAFF_AUTH_CHANNEL "staff_auth_channel"
82 #define KEY_STAFF_AUTH_CHANNEL_MODES "staff_auth_channel_modes"
83 #define KEY_CLONE_GLINE_DURATION "clone_gline_duration"
84 #define KEY_BLOCK_GLINE_DURATION "block_gline_duration"
85 #define KEY_BLOCK_SHUN_DURATION "block_shun_duration"
86 #define KEY_ISSUER "issuer"
87 #define KEY_ISSUED "issued"
88 #define KEY_ADMIN_LEVEL "admin_level"
89 #define KEY_SILENT_LEVEL "silent_level"
90 #define KEY_UPLINK "uplink"
91 #define KEY_SECOND "secondaryuplink"
92 #define KEY_PORT "port"
93 #define KEY_KARMA "karma"
94 #define KEY_OFFLINE "offline"
95 #define KEY_ROUTINGPLAN "routingplan"
96 #define KEY_ROUTINGPLAN_OPTIONS "routingplan_options"
97 #define KEY_DEFCON1 "DefCon1"
98 #define KEY_DEFCON2 "DefCon2"
99 #define KEY_DEFCON3 "DefCon3"
100 #define KEY_DEFCON4 "DefCon4"
101 #define KEY_DEFCON_LEVEL "DefConLevel"
102 #define KEY_DEFCON_CHANMODES "DefConChanModes"
103 #define KEY_DEFCON_SESSION_LIMIT "DefConSessionLimit"
104 #define KEY_DEFCON_TIMEOUT "DefConTimeOut"
105 #define KEY_DEFCON_GLOBAL "GlobalOnDefcon"
106 #define KEY_DEFCON_GLOBAL_MORE "GlobalOnDefconMore"
107 #define KEY_DEFCON_MESSAGE "DefconMessage"
108 #define KEY_DEFCON_OFF_MESSAGE "DefConOffMessage"
109 #define KEY_DEFCON_GLINE_DURATION "DefConGlineExpire"
110 #define KEY_DEFCON_GLINE_REASON "DefConGlineReason"
111
112 /* Routing karma values: */
113 /* What value we start out with when new servers are added: */
114 #define KARMA_DEFAULT 10
115 /* max, min */
116 #define KARMA_MAX 10
117 #define KARMA_MIN -10
118 /* ping out, reduce karma by this much: */
119 #define KARMA_PINGOUT -8
120 /* read err, reduce karma by this much: */
121 #define KARMA_READERROR -5
122 /* every 24 hours everyone gets this much added (so we eventually re-try bad servers) */
123 #define KARMA_ENTROPE 1
124 /* every 24 hours servers linked for 24 hours get an additional ammount: */
125 #define KARMA_RELIABLE 1
126 /* How often to run entrope and reliable checks */
127 #define KARMA_TIMER 86400 /* 1 day */
128
129 #define ROUTING_CONNECT_TIMEOUT 30 /* 30 seconds */
130
131 #define IDENT_FORMAT "%s [%s@%s/%s]"
132 #define IDENT_DATA(user) user->nick, user->ident, user->hostname, irc_ntoa(&user->ip)
133 #define MAX_CHANNELS_WHOIS 50
134 #define OSMSG_PART_REASON "%s has no reason."
135 #define OSMSG_KICK_REQUESTED "Kick requested by %s."
136 #define OSMSG_KILL_REQUESTED "Kill requested by %s."
137 #define OSMSG_GAG_REQUESTED "Gag requested by %s."
138
139 static const struct message_entry msgtab[] = {
140 { "OSMSG_BAR", "----------------------------------------" },
141 { "OSMSG_USER_ACCESS_IS", "$b%s$b (account $b%s$b) has %d access." },
142 { "OSMSG_LEVEL_TOO_LOW", "You lack sufficient access to use this command." },
143 { "OSMSG_NEED_CHANNEL", "You must specify a channel for $b%s$b." },
144 { "OSMSG_INVALID_IRCMASK", "$b%s$b is an invalid IRC hostmask." },
145 { "OSMSG_ADDED_BAN", "I have banned $b%s$b from $b%s$b." },
146 { "OSMSG_SHUN_ISSUED", "Shun issued for $b%s$b." },
147 { "OSMSG_SHUN_REMOVED", "Shun removed for $b%s$b." },
148 { "OSMSG_SHUN_FORCE_REMOVED", "Unknown/expired Shun removed for $b%s$b." },
149 { "OSMSG_SHUN_ONE_REFRESHED", "All Shuns resent to $b%s$b." },
150 { "OSMSG_SHUN_REFRESHED", "All Shuns refreshed." },
151 { "OSMSG_GLINE_ISSUED", "G-line issued for $b%s$b." },
152 { "OSMSG_GLINE_REMOVED", "G-line removed for $b%s$b." },
153 { "OSMSG_GLINE_FORCE_REMOVED", "Unknown/expired G-line removed for $b%s$b." },
154 { "OSMSG_GLINES_ONE_REFRESHED", "All G-lines resent to $b%s$b." },
155 { "OSMSG_GLINES_REFRESHED", "All G-lines refreshed." },
156 { "OSMSG_CLEARBANS_DONE", "Cleared all bans from channel $b%s$b." },
157 { "OSMSG_CLEARMODES_DONE", "Cleared all modes from channel $b%s$b." },
158 { "OSMSG_NO_CHANNEL_MODES", "Channel $b%s$b had no modes to clear." },
159 { "OSMSG_DEOP_DONE", "Deopped the requested lusers." },
160 { "OSMSG_DEOPALL_DONE", "Deopped everyone on $b%s$b." },
161 { "OSMSG_DEHOP_DONE", "Dehalfopped the requested lusers." },
162 { "OSMSG_DEHOPALL_DONE", "Dehalfopped everyone on $b%s$b." },
163 { "OSMSG_NO_DEBUG_CHANNEL", "No debug channel has been configured." },
164 { "OSMSG_INVITE_DONE", "Invited $b%s$b to $b%s$b." },
165 { "OSMSG_ALREADY_THERE", "You are already in $b%s$b." },
166 { "OSMSG_JOIN_DONE", "I have joined $b%s$b." },
167 { "OSMSG_ALREADY_JOINED", "I am already in $b%s$b." },
168 { "OSMSG_NOT_ON_CHANNEL", "$b%s$b does not seem to be on $b%s$b." },
169 { "OSMSG_KICKALL_DONE", "I have cleared out %s." },
170 { "OSMSG_LEAVING", "Leaving $b%s$b." },
171 { "OSMSG_MODE_SET", "I have set the modes for $b%s$b." },
172 { "OSMSG_OP_DONE", "Opped the requested lusers." },
173 { "OSMSG_OPALL_DONE", "Opped everyone on $b%s$b." },
174 { "OSMSG_HOP_DONE", "Halfopped the requested lusers." },
175 { "OSMSG_HOPALL_DONE", "Halfopped everyone on $b%s$b." },
176 { "OSMSG_WHOIS_IDENT", "%s (%s@%s) from %d.%d.%d.%d" },
177 { "OSMSG_WHOIS_NICK", "Nick : %s" },
178 { "OSMSG_WHOIS_HOST", "Host : %s@%s" },
179 { "OSMSG_WHOIS_FAKEHOST", "Fakehost : %s" },
180 { "OSMSG_WHOIS_CRYPT_HOST", "Crypt Host : %s" },
181 { "OSMSG_WHOIS_CRYPT_IP", "Crypt IP : %s" },
182 { "OSMSG_WHOIS_IP", "Real IP : %s" },
183 { "OSMSG_WHOIS_COUNTRY", "Country : %s" },
184 { "OSMSG_WHOIS_COUNTRY_CODE","Country Code : %s" },
185 { "OSMSG_WHOIS_CITY", "City : %s" },
186 { "OSMSG_WHOIS_REGION", "Region/State : %s" },
187 { "OSMSG_WHOIS_POSTAL_CODE","Postal Code : %s" },
188 { "OSMSG_WHOIS_LATITUDE", "Latitude : %f" },
189 { "OSMSG_WHOIS_LONGITUDE", "Longitude : %f" },
190 { "OSMSG_WHOIS_MAP", "Map : %s" },
191 { "OSMSG_WHOIS_DMA_CODE", "DMA Code : %d" },
192 { "OSMSG_WHOIS_AREA_CODE", "Area Code : %d" },
193 { "OSMSG_WHOIS_MODES", "Modes : +%s " },
194 { "OSMSG_WHOIS_INFO", "Info : %s" },
195 { "OSMSG_WHOIS_NUMERIC", "Numnick : %s" },
196 { "OSMSG_WHOIS_SERVER", "Server : %s" },
197 { "OSMSG_WHOIS_NICK_AGE", "Nick Age : %s" },
198 { "OSMSG_WHOIS_ACCOUNT", "Account : %s" },
199 { "OSMSG_WHOIS_PRIVS", "IRCd Privs : %s" },
200 { "OSMSG_WHOIS_CHANNELS", "Channels : %s" },
201 { "OSMSG_WHOIS_HIDECHANS", "Channel list omitted for your sanity." },
202 { "OSMSG_UNBAN_DONE", "Ban(s) removed from channel %s." },
203 { "OSMSG_CHANNEL_VOICED", "All users on %s voiced." },
204 { "OSMSG_CHANNEL_DEVOICED", "All voiced users on %s de-voiced." },
205 { "OSMSG_BAD_MODIFIER", "Unknown bad-word modifier $b%s$b." },
206 { "OSMSG_BAD_REDUNDANT", "$b%s$b is already covered by a bad word ($b%s$b)." },
207 { "OSMSG_BAD_GROWING", "Replacing bad word $b%s$b with shorter bad word $b%s$b." },
208 { "OSMSG_BAD_NUKING", " .. and removing redundant bad word $b%s$b." },
209 { "OSMSG_ADDED_BAD", "Added $b%s$b to the bad-word list." },
210 { "OSMSG_REMOVED_BAD", "Removed $b%s$b from the bad-word list." },
211 { "OSMSG_NOT_BAD_WORD", "$b%s$b is not a bad word." },
212 { "OSMSG_ADDED_EXEMPTION", "Added $b%s$b to the bad-word exemption list." },
213 { "OSMSG_ADDED_EXEMPTIONS", "Added %d exception(s) to the bad word list." },
214 { "OSMSG_REMOVED_EXEMPTION", "Removed $b%s$b from the exemption list." },
215 { "OSMSG_NOT_EXEMPT", "$b%s$b is not on the exempt list." },
216 { "OSMSG_ALREADY_TRUSTED", "Host $b%s$b is already trusted (use $bdeltrust$b and then $baddtrust$b to adjust)." },
217 { "OSMSG_NOT_TRUSTED", "Host $b%s$b is not trusted." },
218 { "OSMSG_BAD_IP", "$b%s$b is not a valid IP address" },
219 { "OSMSG_BAD_NUMBER", "$b%s$b is not a number" },
220 { "OSMSG_ADDED_TRUSTED", "Added trusted hosts to the trusted-hosts list." },
221 { "OSMSG_UPDATED_TRUSTED", "Updated trusted host $b%s$b." },
222 { "OSMSG_REMOVED_TRUSTED", "Removed trusted hosts from the trusted-hosts list." },
223 { "OSMSG_CLONE_EXISTS", "Nick $b%s$b is already in use." },
224 { "OSMSG_NOT_A_HOSTMASK", "The hostmask must be in user@host form." },
225 { "OSMSG_BADWORD_LIST", "Bad words: %s" },
226 { "OSMSG_EXEMPTED_LIST", "Exempted channels: %s" },
227 { "OSMSG_GLINE_COUNT", "There are %d glines active on the network." },
228 { "OSMSG_SHUN_COUNT", "There are %d shuns active on the network." },
229 { "OSMSG_LINKS_SERVER", "%s%s (%u clients; %s)" },
230 { "OSMSG_MAX_CLIENTS", "Max clients: %d at %s" },
231 { "OSMSG_NETWORK_INFO", "Total users: %d (%d invisible, %d opers)" },
232 { "OSMSG_RESERVED_LIST", "List of reserved nicks:" },
233 { "OSMSG_TRUSTED_LIST", "$bTrusted Hosts$b" },
234 { "OSMSG_TRUSTED_LIST_HEADER", "IP Address Limit By Time" },
235 { "OSMSG_HOST_IS_TRUSTED", "%-15s %-5s %-10s set %s ago, expires %s" },
236 { "OSMSG_HOST_IS_TRUSTED_DESC", " Reason: %s" },
237 { "OSMSG_TRUSTED_LIST_BAR", "----------------------------------------" },
238 { "OSMSG_TRUSTED_LIST_END", "----------End of Trusted Hosts----------" },
239 { "OSMSG_HOST_NOT_TRUSTED", "%s does not have a special trust." },
240 { "OSMSG_UPTIME_STATS", "Uptime: %s (%u lines processed, CPU time %.2fu/%.2fs)" },
241 { "OSMSG_LINE_DUMPED", "Raw line sent." },
242 { "OSMSG_RAW_PARSE_ERROR", "Error parsing raw line (not dumping to uplink)." },
243 { "OSMSG_COLLIDED_NICK", "Now temporarily holding nick $b%s$b." },
244 { "OSMSG_RESERVED_NICK", "Now reserving nick $b%s$b." },
245 { "OSMSG_NICK_UNRESERVED", "Nick $b%s$b is no longer reserved." },
246 { "OSMSG_NOT_RESERVED", "Nick $b%s$b is not reserved." },
247 { "OSMSG_ILLEGAL_REASON", "This channel is illegal." },
248 { "OSMSG_ILLEGAL_KILL_REASON", "Joined an illegal modeless channel - do not repeat." },
249 { "OSMSG_ILLEGAL_CHANNEL", "$b%s$b is an ILLEGAL channel. Do not re-join it." },
250 { "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." },
251 { "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." },
252 { "OSMSG_CLONE_ADDED", "Added clone $b%s$b." },
253 { "OSMSG_CLONE_FAILED", "Unable to add user $b%s$b." },
254 { "OSMSG_NOT_A_CLONE", "Har har. $b%s$b isn't a clone." },
255 { "OSMSG_CLONE_REMOVED", "Removed clone $b%s$b." },
256 { "OSMSG_CLONE_JOINED", "$b%s$b has joined $b%s$b." },
257 { "OSMSG_CLONE_PARTED", "$b%s$b has left $b%s$b." },
258 { "OSMSG_OPS_GIVEN", "I have given ops in $b%s$b to $b%s$b." },
259 { "OSMSG_HOPS_GIVEN", "I have given halfops in $b%s$b to $b%s$b." },
260 { "OSMSG_CLONE_SAID", "$b%s$b has spoken to $b%s$b." },
261 { "OSMSG_UNKNOWN_SUBCOMMAND", "$b%s$b is not a valid subcommand of $b%s$b." },
262 { "OSMSG_UNKNOWN_OPTION", "$b%s$b has not been set." },
263 { "OSMSG_OPTION_IS", "$b%s$b is set to $b%s$b." },
264 { "OSMSG_OPTION_ROOT", "The following keys can be queried:" },
265 { "OSMSG_OPTION_LIST", "$b%s$b contains the following values:" },
266 { "OSMSG_OPTION_KEYS", "$b%s$b contains the following keys:" },
267 { "OSMSG_OPTION_LIST_EMPTY", "Empty list." },
268 { "OSMSG_SET_NOT_SET", "$b%s$b does not exist, and cannot be set." },
269 { "OSMSG_SET_BAD_TYPE", "$b%s$b is not a string, and cannot be set." },
270 { "OSMSG_SET_SUCCESS", "$b%s$b has been set to $b%s$b." },
271 { "OSMSG_SETTIME_SUCCESS", "Set time for servers named like $b%s$b." },
272 { "OSMSG_BAD_ACTION", "Unrecognized trace action $b%s$b." },
273 { "OSMSG_USER_SEARCH_RESULTS", "The following users were found:" },
274 { "OSMSG_USER_SEARCH_HEADER", "Nick User@Host (Account)" },
275 { "OSMSG_USER_SEARCH_BAR", "-------------------------------------------" },
276 { "OSMSG_USER_SEARCH_COUNT", "There were %4u matches" },
277 { "OSMSG_USER_SEARCH_COUNT_BAR", "------------ Found %4u matches -----------" },
278 { "OSMSG_CHANNEL_SEARCH_RESULTS", "The following channels were found:" },
279 { "OSMSG_GLINE_SEARCH_RESULTS", "The following glines were found:" },
280 { "OSMSG_SHUN_SEARCH_RESULTS", "The following shun were found:" },
281 { "OSMSG_LOG_SEARCH_RESULTS", "The following log entries were found:" },
282 { "OSMSG_GSYNC_RUNNING", "Synchronizing glines from %s." },
283 { "OSMSG_SSYNC_RUNNING", "Synchronizing shuns from %s." },
284 { "OSMSG_GTRACE_FORMAT", "%s (issued %s by %s, expires %s): %s" },
285 { "OSMSG_STRACE_FORMAT", "%s (issued %s by %s, expires %s): %s" },
286 { "OSMSG_GAG_APPLIED", "Gagged $b%s$b, affecting %d users." },
287 { "OSMSG_GAG_ADDED", "Gagged $b%s$b." },
288 { "OSMSG_REDUNDANT_GAG", "Gag $b%s$b is redundant." },
289 { "OSMSG_GAG_NOT_FOUND", "Could not find gag $b%s$b." },
290 { "OSMSG_NO_GAGS", "No gags have been set." },
291 { "OSMSG_UNGAG_APPLIED", "Ungagged $b%s$b, affecting %d users." },
292 { "OSMSG_UNGAG_ADDED", "Ungagged $b%s$b." },
293 { "OSMSG_TIMEQ_INFO", "%u events in timeq; next in %lu seconds." },
294 { "OSMSG_ALERT_EXISTS", "An alert named $b%s$b already exists." },
295 { "OSMSG_UNKNOWN_REACTION", "Unknown alert reaction $b%s$b." },
296 { "OSMSG_ADDED_ALERT", "Added alert named $b%s$b." },
297 { "OSMSG_REMOVED_ALERT", "Removed alert named $b%s$b." },
298 { "OSMSG_NO_SUCH_ALERT", "No alert named $b%s$b could be found." },
299 { "OSMSG_ALERTS_LIST", "$bCurrent $O alerts$b" },
300 { "OSMSG_ALERTS_BAR", "----------------------------------------------" },
301 { "OSMSG_ALERTS_HEADER", "Name Action (by Oper)" },
302 { "OSMSG_ALERTS_DESC", " Criteria: %s" },
303 { "OSMSG_ALERT_IS", "$b%-20s$b %-6s (by %s)" },
304 { "OSMSG_ALERT_END", "----------------End of Alerts-----------------" },
305 /* routing messages */
306 { "OSMSG_ROUTINGPLAN_LIST", "$bRouting Plans$b" },
307 { "OSMSG_ROUTINGPLAN_BAR", "----------------------------------------------" },
308 { "OSMSG_ROUTINGPLAN_END", "-------------End of Routing Plans-------------" },
309 { "OSMSG_ROUTINGPLAN_OPTION", "%s is set to %s" },
310 { "OSMSG_ROUTINGPLAN_ACTIVE", "Auto routing is active, using plan '%s'." },
311 { "OSMSG_ROUTING_ACTIVATION_ERROR", "There was an error activating the routing plan. Check for loops, and make sure the map includes my own uplink." },
312 { "OSMSG_ROUTINGPLAN_OPTION_NOT_FOUND", "There is no routing plan option '%s'." },
313 { "OSMSG_ROUTINGPLAN_OPTION_NOT_SET", "Option '%s' is not currently set." },
314 { "OSMSG_ROUTINGPLAN_NAME", "$b%s:$b" },
315 { "OSMSG_ROUTINGPLAN_SERVER"," %s:%d <-- %s[%d/%s] (%s)" },
316 { "OSMSG_ADDPLAN_SUCCESS", "Added new routing plan '%s'." },
317 { "OSMSG_ADDPLAN_FAILED", "Could not add new plan '%s' (does it already exist?)." },
318 { "OSMSG_INVALID_PLAN", "That routing plan name is not valid." },
319 { "OSMSG_PLAN_DELETED", "The routing plan was sucessfully deleted." },
320 { "OSMSG_PLAN_NOT_FOUND", "There is no routing plan called '%s'." },
321 { "OSMSG_PLAN_SERVER_ADDED", "Added %s to the routing plan." },
322 { "OSMSG_PLAN_SERVER_DELETED", "The server has been deleted." },
323 { "OSMSG_PLAN_SERVER_NOT_FOUND", "The server '%s' was not found in that routing plan." },
324 { "OSMSG_ROUTING_DISABLED", "Routing is now disabled." },
325 { "OSMSG_DOWNLINKS_FORMAT_A", "%s%s-$b%s$b [%s]" },
326 { "OSMSG_DOWNLINKS_FORMAT_B", "$b%s$b (me)" },
327 { "OSMSG_ROUTELIST_EMPTY", "No servers in route list" },
328 { "OSMSG_ROUTELIST_AS_PLANNED", "Routing plan: Servers as they SHOULD be linked" },
329 { "OSMSG_MAP_CENTERED", "map %s centered, Maxdepth:%d" },
330 { "OSMSG_NO_SERVERS_MISSING", "No servers are missing." },
331 { "OSMSG_CONNECTING_MISSING", "Attempted to connect %d missing servers." },
332 { "OSMSG_CONNECT", "->connect %s %d %s" },
333 { "OSMSG_SQUIT", "->squit %s" },
334 { "OSMSG_COULDNT_FIND_SERVER", "Couldnt find %s, so using %s to link %s" },
335 { "OSMSG_INSPECTING_SERVER", "Inspecting server [%s]" },
336 { "OSMSG_REROUTING_ACC_MAP", "Rerouting network according to loaded map.." },
337 { "OSMSG_REROUTING_NOTCONFIGURED", "You have not configured routing. See $/msg $O help routing$b." },
338 { "OSMSG_CONNECTING_MISSING_ONLY", "Connecting missing servers only.." },
339 { "OSMSG_NO_ROUTING_NECESSARY", "No rerouting appears necessary." },
340 { "OSMSG_TESTING_REROUTE", "Testing Reroute(): Commands not sent to socket.." },
341 { "OSMSG_INVALID_DIRECTIVE", "Reroute(): Invalid directive %s", },
342 { "OSMSG_UPLINKS_MISSING", "%d servers' uplinks were missing, and were not connected." },
343 { "OSMSG_REROUTE_COMPLETE", "Reroute complete: Moved %d, connected %d, total %d changes." },
344 /* end of routing */
345 { "OSMSG_REHASH_COMPLETE", "Completed rehash of configuration database." },
346 { "OSMSG_REHASH_FAILED", "Rehash of configuration database failed, previous configuration is intact." },
347 { "OSMSG_REOPEN_COMPLETE", "Closed and reopened all log files." },
348 { "OSMSG_RECONNECTING", "Reconnecting to my uplink." },
349 { "OSMSG_NUMERIC_COLLIDE", "Numeric %d (%s) is already in use." },
350 { "OSMSG_NAME_COLLIDE", "That name is already in use." },
351 { "OSMSG_SRV_CREATE_FAILED", "Server creation failed -- check log files." },
352 { "OSMSG_SERVER_JUPED", "Added new jupe server %s." },
353 { "OSMSG_INVALID_NUMERIC", "Invalid numeric" },
354 { "OSMSG_INVALID_SERVERNAME", "Server name must contain a '.'." },
355 { "OSMSG_SERVER_NOT_JUPE", "That server is not a juped server." },
356 { "OSMSG_SERVER_UNJUPED", "Server jupe removed." },
357 /*
358 { "OSMSG_WARN_ADDED", "Added channel activity warning for $b%s$b (%s)" },
359 { "OSMSG_WARN_EXISTS", "Channel activity warning for $b%s$b already exists." },
360 { "OSMSG_WARN_DELETED", "Removed channel activity warning for $b%s$b" },
361 { "OSMSG_WARN_NOEXIST", "Channel activity warning for $b%s$b does not exist." },
362 { "OSMSG_WARN_LISTSTART", "Channel activity warnings:" },
363 { "OSMSG_WARN_LISTENTRY", "%s (%s)" },
364 { "OSMSG_WARN_LISTEND", "End of activity warning list." },
365 */
366 { "OSMSG_UPLINK_CONNECTING", "Establishing connection with %s (%s:%d)." },
367 { "OSMSG_CURRENT_UPLINK", "$b%s$b is already the current uplink." },
368 { "OSMSG_INVALID_UPLINK", "$b%s$b is not a valid uplink name." },
369 { "OSMSG_UPLINK_DISABLED", "$b%s$b is a disabled or unavailable uplink." },
370 { "OSMSG_UPLINK_START", "Uplink $b%s$b:" },
371 { "OSMSG_UPLINK_ADDRESS", "Address: %s:%d" },
372 { "OSMSG_STUPID_GLINE", "Gline %s? Now $bthat$b would be smooth." },
373 { "OSMSG_STUPID_SHUN", "Shun %s? Now $bthat$b would be smooth." },
374 { "OSMSG_ACCOUNTMASK_AUTHED", "Invalid criteria: it is impossible to match an account mask but not be authed" },
375 { "OSMSG_CHANINFO_HEADER", "%s Information" },
376 { "OSMSG_CHANINFO_TIMESTAMP", "Created on: %a %b %d %H:%M:%S %Y (%s)" },
377 { "OSMSG_CHANINFO_MODES", "Modes: %s" },
378 { "OSMSG_CHANINFO_MODES_BADWORD", "Modes: %s; bad-word channel" },
379 { "OSMSG_CHANINFO_TOPIC", "Topic (set by %%s, %a %b %d %H:%M:%S %Y): %%s" },
380 { "OSMSG_CHANINFO_TOPIC_UNKNOWN", "Topic: (none / not gathered)" },
381 { "OSMSG_CHANINFO_BAN_COUNT", "Bans (%d):" },
382 { "OSMSG_CHANINFO_BAN", "%%s by %%s (%a %b %d %H:%M:%S %Y)" },
383 { "OSMSG_CHANINFO_EXEMPT_COUNT", "Exempts (%d):" },
384 { "OSMSG_CHANINFO_EXEMPT", "%%s by %%s (%a %b %d %H:%M:%S %Y)" },
385 { "OSMSG_CHANINFO_MANY_USERS", "%d users (\"/msg $S %s %s users\" for the list)" },
386 { "OSMSG_CHANINFO_USER_COUNT", "Users (%d):" },
387 { "OSMSG_CSEARCH_CHANNEL_INFO", "%s [%d users] %s %s" },
388 { "OSMSG_INVALID_REGEX", "Invalid regex: %s: %s (%d)" },
389 { "OSMSG_TRACK_DISABLED", "Tracking is not currently compiled into X3" },
390 { "OSMSG_MAXUSERS_RESET", "Max clients has been reset to $b%d$b" },
391
392 { "OSMSG_DEFCON_INVALID", "DefCon level %d is invalid, please choose a value between 1 and 5" },
393 { "OSMSG_DEFCON_ALLOWING_ALL", "DefCon is at level 5 and allowing everything" },
394 { "OSMSG_DEFCON_DISALLOWING", "DefCon is at level %d and enforcing:" },
395 { "OSMSG_DEFCON_NO_NEW_CHANNELS", "No Channel Registrations" },
396 { "OSMSG_DEFCON_NO_NEW_NICKS", "No Nickname/Account Registrations" },
397 { "OSMSG_DEFCON_NO_MODE_CHANGE", "No Channel Mode Changes" },
398 { "OSMSG_DEFCON_NO_NEW_CLIENTS", "No New Clients" },
399 { "OSMSG_DEFCON_FORCE_CHANMODES", "Forcing Channel Mode(s): %s" },
400 { "OSMSG_DEFCON_REDUCE_SESSION", "Forcing Reduced Session: %d" },
401 { "OSMSG_DEFCON_OPER_ONLY", "Allowing Services Communication With Opers Only" },
402 { "OSMSG_DEFCON_SILENT_OPER_ONLY", "Allowing Services Communication With Opers Only AND Silently Ignoring Regular Users" },
403 { "OSMSG_DEFCON_GLINE_NEW_CLIENTS", "Glining New Clients" },
404 { "OSMSG_DEFCON_SHUN_NEW_CLIENTS", "Shunning New Clients" },
405 { "OSMSG_DEFCON_NO_NEW_MEMOS", "Disallowing New Memos" },
406
407 { "OSMSG_PRIV_UNKNOWN", "Unknown privilege flag %s, see /msg $O HELP PRIVFLAGS for a flag list" },
408 { "OSMSG_PRIV_SET", "Privilege flag %s has been %sset" },
409
410 { NULL, NULL }
411 };
412
413 #define OPSERV_SYNTAX() svccmd_send_help_brief(user, opserv, cmd)
414
415 int DefConLevel = 5;
416 int DefCon[6];
417 int DefConTimeOut;
418 int GlobalOnDefcon = 0;
419 int GlobalOnDefconMore = 0;
420 int DefConGlineExpire;
421 int DefConModesSet = 0;
422 unsigned int DefConSessionLimit;
423 char *DefConChanModes;
424 char *DefConGlineReason;
425 char *DefConMessage;
426 char *DefConOffMessage;
427
428 extern void add_track_user(struct userNode *user);
429 typedef int (*discrim_search_func)(struct userNode *match, void *extra);
430
431 struct userNode *opserv;
432 static struct service *opserv_service;
433
434 /*static dict_t opserv_chan_warn; */ /* data is char* */
435 static dict_t opserv_reserved_nick_dict; /* data is struct userNode* */
436 static struct string_list *opserv_bad_words;
437 static dict_t opserv_exempt_channels; /* data is not used */
438 static dict_t opserv_trusted_hosts; /* data is struct trusted_host* */
439 static dict_t opserv_routing_plans; /* data is struct routingPlan */
440 static dict_t opserv_routing_plan_options; /* data is a dict_t key->val list*/
441 static dict_t opserv_waiting_connections; /* data is struct waitingConnection */
442 static dict_t opserv_hostinfo_dict; /* data is struct opserv_hostinfo* */
443 static dict_t opserv_user_alerts; /* data is struct opserv_user_alert* */
444 static dict_t opserv_nick_based_alerts; /* data is struct opserv_user_alert* */
445 static dict_t opserv_channel_alerts; /* data is struct opserv_user_alert* */
446 static struct module *opserv_module;
447 static struct log_type *OS_LOG;
448 static unsigned int new_user_flood;
449 static char *level_strings[1001];
450 struct string_list *autojoin_channels;
451 struct route *opserv_route = NULL; /* Main active routing table from activate_routing()*/
452
453 static struct {
454 struct chanNode *debug_channel;
455 struct chanNode *alert_channel;
456 struct chanNode *staff_auth_channel;
457 struct policer_params *join_policer_params;
458 struct policer new_user_policer;
459 unsigned long untrusted_max;
460 unsigned long clone_gline_duration;
461 unsigned long block_gline_duration;
462 unsigned long block_shun_duration;
463 unsigned long purge_lock_delay;
464 unsigned long join_flood_moderate;
465 unsigned long join_flood_moderate_threshold;
466 unsigned long admin_level;
467 unsigned long silent_level;
468 } opserv_conf;
469
470 struct trusted_host {
471 char *ipaddr;
472 char *issuer;
473 char *reason;
474 unsigned long limit;
475 time_t issued;
476 time_t expires;
477 };
478
479 struct gag_entry {
480 char *mask;
481 char *owner;
482 char *reason;
483 time_t expires;
484 struct gag_entry *next;
485 };
486
487 static struct gag_entry *gagList;
488
489 struct opserv_hostinfo {
490 struct userList clients;
491 struct trusted_host *trusted;
492 };
493
494 static void
495 opserv_free_hostinfo(void *data)
496 {
497 struct opserv_hostinfo *ohi = data;
498 userList_clean(&ohi->clients);
499 free(ohi);
500 }
501
502 static void
503 opserv_free_waiting_connection(void *data)
504 {
505 struct waitingConnection *wc = data;
506 free(wc->server);
507 free(wc->target);
508 free(wc);
509 }
510
511 typedef struct opservDiscrim {
512 struct chanNode *channel;
513 char *mask_nick, *mask_ident, *mask_host, *mask_info, *server, *reason, *accountmask;
514 irc_in_addr_t ip_mask;
515 unsigned long limit;
516 time_t min_ts, max_ts;
517 regex_t regex_nick, regex_ident, regex_host, regex_info;
518 unsigned int has_regex_nick : 1, has_regex_ident : 1, has_regex_host : 1, has_regex_info : 1;
519 unsigned int min_level, max_level, domain_depth, duration, min_clones, min_channels, max_channels;
520 unsigned char ip_mask_bits;
521 unsigned int match_opers : 1, option_log : 1;
522 unsigned int chan_req_modes : 2, chan_no_modes : 2;
523 int authed : 2, info_space : 2;
524 unsigned int intra_scmp : 2, intra_dcmp : 2;
525 unsigned int use_regex : 1;
526 unsigned int silent : 1;
527 } *discrim_t;
528
529 struct discrim_and_source {
530 discrim_t discrim;
531 struct userNode *source;
532 struct userNode *destination;
533 dict_t dict;
534 unsigned int disp_limit;
535 };
536
537 static discrim_t opserv_discrim_create(struct userNode *user, struct userNode *bot, unsigned int argc, char *argv[], int allow_channel);
538 static unsigned int opserv_discrim_search(discrim_t discrim, discrim_search_func dsf, void *data);
539 static int gag_helper_func(struct userNode *match, void *extra);
540 static int ungag_helper_func(struct userNode *match, void *extra);
541
542 typedef enum {
543 REACT_NOTICE,
544 REACT_KILL,
545 // REACT_SILENT,
546 REACT_GLINE,
547 REACT_TRACK,
548 REACT_SHUN
549 } opserv_alert_reaction;
550
551 struct opserv_user_alert {
552 char *owner;
553 char *text_discrim, *split_discrim;
554 discrim_t discrim;
555 opserv_alert_reaction reaction;
556 };
557
558 /* funny type to make it acceptible to dict_set_free_data, far below */
559 static void
560 opserv_free_user_alert(void *data)
561 {
562 struct opserv_user_alert *alert = data;
563 if (alert->discrim->channel)
564 UnlockChannel(alert->discrim->channel);
565 free(alert->owner);
566 free(alert->text_discrim);
567 free(alert->split_discrim);
568 if(alert->discrim->has_regex_nick)
569 regfree(&alert->discrim->regex_nick);
570 if(alert->discrim->has_regex_ident)
571 regfree(&alert->discrim->regex_ident);
572 if(alert->discrim->has_regex_host)
573 regfree(&alert->discrim->regex_host);
574 if(alert->discrim->has_regex_info)
575 regfree(&alert->discrim->regex_info);
576 free(alert->discrim->reason);
577 free(alert->discrim);
578 free(alert);
579 }
580
581 #define opserv_debug(format...) do { if (opserv_conf.debug_channel) send_channel_notice(opserv_conf.debug_channel , opserv , ## format); } while (0)
582 #define opserv_alert(format...) do { if (opserv_conf.alert_channel) send_channel_notice(opserv_conf.alert_channel , opserv , ## format); } while (0)
583
584
585 char *defconReverseModes(const char *modes)
586 {
587 char *newmodes = NULL;
588 unsigned int i = 0;
589 if (!modes) {
590 return NULL;
591 }
592 if (!(newmodes = malloc(sizeof(char) * strlen(modes) + 1))) {
593 return NULL;
594 }
595 for (i = 0; i < strlen(modes); i++) {
596 if (modes[i] == '+')
597 newmodes[i] = '-';
598 else if (modes[i] == '-')
599 newmodes[i] = '+';
600 else
601 newmodes[i] = modes[i];
602 }
603 newmodes[i] = '\0';
604 return newmodes;
605 }
606
607 int checkDefCon(int level)
608 {
609 return DefCon[DefConLevel] & level;
610 }
611
612 void showDefConSettings(struct userNode *user, struct svccmd *cmd)
613 {
614 if (DefConLevel == 5) {
615 reply("OSMSG_DEFCON_ALLOWING_ALL");
616 return;
617 } else
618 reply("OSMSG_DEFCON_DISALLOWING", DefConLevel);
619
620 if (checkDefCon(DEFCON_NO_NEW_CHANNELS))
621 reply("OSMSG_DEFCON_NO_NEW_CHANNELS");
622
623 if (checkDefCon(DEFCON_NO_NEW_NICKS))
624 reply("OSMSG_DEFCON_NO_NEW_NICKS");
625
626 if (checkDefCon(DEFCON_NO_MODE_CHANGE))
627 reply("OSMSG_DEFCON_NO_MODE_CHANGE");
628
629 if (checkDefCon(DEFCON_FORCE_CHAN_MODES) && (DefConChanModes))
630 reply("OSMSG_DEFCON_FORCE_CHANMODES", DefConChanModes);
631
632 if (checkDefCon(DEFCON_REDUCE_SESSION))
633 reply("OSMSG_DEFCON_REDUCE_SESSION", DefConSessionLimit);
634
635 if (checkDefCon(DEFCON_NO_NEW_CLIENTS))
636 reply("OSMSG_DEFCON_NO_NEW_CLIENTS");
637
638 if (checkDefCon(DEFCON_OPER_ONLY))
639 reply("OSMSG_DEFCON_OPER_ONLY");
640
641 if (checkDefCon(DEFCON_SILENT_OPER_ONLY))
642 reply("OSMSG_DEFCON_SILENT_OPER_ONLY");
643
644 if (checkDefCon(DEFCON_GLINE_NEW_CLIENTS))
645 reply("OSMSG_DEFCON_GLINE_NEW_CLIENTS");
646
647 if (checkDefCon(DEFCON_SHUN_NEW_CLIENTS))
648 reply("OSMSG_DEFCON_SHUN_NEW_CLIENTS");
649
650 if (checkDefCon(DEFCON_NO_NEW_MEMOS))
651 reply("OSMSG_DEFCON_NO_NEW_MEMOS");
652
653 return;
654 }
655
656 void do_mass_mode(char *modes)
657 {
658 dict_iterator_t it;
659
660 if (!modes)
661 return;
662
663 for (it = dict_first(channels); it; it = iter_next(it)) {
664 struct chanNode *chan = iter_data(it);
665
666 irc_mode(opserv, chan, modes);
667 }
668
669 }
670
671 void DefConProcess(struct userNode *user)
672 {
673 char *newmodes;
674
675 if (GlobalOnDefcon)
676 global_message_args(MESSAGE_RECIPIENT_LUSERS, "DEFCON_NETWORK_CHANGED", DefConLevel);
677
678 if (GlobalOnDefconMore && GlobalOnDefcon)
679 global_message(MESSAGE_RECIPIENT_LUSERS, DefConMessage);
680
681 if ((DefConLevel == 5) && !GlobalOnDefconMore && !GlobalOnDefcon)
682 global_message(MESSAGE_RECIPIENT_LUSERS, DefConOffMessage);
683
684 if (user)
685 global_message_args(MESSAGE_RECIPIENT_OPERS, "DEFCON_OPER_LEVEL_CHANGE", user->nick, DefConLevel);
686 else
687 global_message_args(MESSAGE_RECIPIENT_OPERS, "DEFCON_TIMEOUT_LEVEL_CHANGE", DefConLevel);
688
689 if (checkDefCon(DEFCON_FORCE_CHAN_MODES)) {
690 if (DefConChanModes && !DefConModesSet) {
691 if (DefConChanModes[0] == '+' || DefConChanModes[0] == '-') {
692 do_mass_mode(DefConChanModes);
693 DefConModesSet = 1;
694 }
695 }
696 } else {
697 if (DefConChanModes && (DefConModesSet != 0)) {
698 if (DefConChanModes[0] == '+' || DefConChanModes[0] == '-') {
699 if ((newmodes = defconReverseModes(DefConChanModes))) {
700 do_mass_mode(newmodes);
701 free(newmodes);
702 }
703 DefConModesSet = 0;
704 }
705 }
706 }
707
708 return;
709 }
710
711 void
712 defcon_timeout(UNUSED_ARG(void *data))
713 {
714 DefConLevel = 5;
715 DefConProcess(NULL);
716 }
717
718 static MODCMD_FUNC(cmd_defcon)
719 {
720 if ((argc < 2) || (atoi(argv[1]) == DefConLevel)) {
721 showDefConSettings(user, cmd);
722 return 1;
723 }
724
725 if ((atoi(argv[1]) < 1) || (atoi(argv[1]) > 5)) {
726 reply("OSMSG_DEFCON_INVALID", atoi(argv[1]));
727 return 0;
728 }
729
730 DefConLevel = atoi(argv[1]);
731 showDefConSettings(user, cmd);
732
733 if (DefConTimeOut > 0) {
734 timeq_del(0, defcon_timeout, NULL, TIMEQ_IGNORE_DATA & TIMEQ_IGNORE_WHEN);
735 timeq_add(now + DefConTimeOut, defcon_timeout, NULL);
736 }
737
738 DefConProcess(user);
739 return 1;
740 }
741
742 /* TODO
743 static MODCMD_FUNC(cmd_privallow)
744 {
745 //privallow servername/username +/-flag (global is set in conf)
746 }
747
748 static MODCMD_FUNC(cmd_privdissallow)
749 {
750 //privdisallow servername/username +/-flag (global is set in conf)
751 }
752
753 static MODCMD_FUNC(cmd_privlist)
754 {
755 //privlist servername/user (global with none)
756 }
757 */
758
759 static MODCMD_FUNC(cmd_privset)
760 {
761 struct userNode *target;
762 char *flag;
763 int add = PRIV_ADD;
764
765 flag = argv[2];
766 if (*flag == '-') {
767 add = PRIV_DEL;
768 flag++;
769 } else if (*flag == '+') {
770 add = PRIV_ADD;
771 flag++;
772 }
773
774 target = GetUserH(argv[1]);
775 if (!target) {
776 reply("MSG_NICK_UNKNOWN", argv[1]);
777 return 0;
778 }
779
780 if (check_priv(flag)) {
781 irc_privs(target, flag, add);
782 reply("OSMSG_PRIV_SET", argv[2], (add == 1) ? "" : "un");
783 } else {
784 reply("OSMSG_PRIV_UNKNOWN", argv[2]);
785 return 0;
786 }
787
788 return 1;
789 }
790
791 /* A lot of these commands are very similar to what ChanServ can do,
792 * but OpServ can do them even on channels that aren't registered.
793 */
794
795 static MODCMD_FUNC(cmd_access)
796 {
797 struct handle_info *hi;
798 const char *target;
799 unsigned int res;
800
801 target = (argc > 1) ? (const char*)argv[1] : user->nick;
802 if (!irccasecmp(target, "*")) {
803 nickserv_show_oper_accounts(user, cmd);
804 return 1;
805 }
806 if (!(hi = modcmd_get_handle_info(user, target)))
807 return 0;
808 res = (argc > 2) ? oper_try_set_access(user, opserv_service->bot, hi, strtoul(argv[2], NULL, 0)) : 0;
809 reply("OSMSG_USER_ACCESS_IS", target, hi->handle, hi->opserv_level);
810 return res;
811 }
812
813 static MODCMD_FUNC(cmd_ban)
814 {
815 struct mod_chanmode change;
816 struct userNode *victim;
817
818 mod_chanmode_init(&change);
819 change.argc = 1;
820 change.args[0].mode = MODE_BAN;
821 if (is_ircmask(argv[1]))
822 change.args[0].u.hostmask = strdup(argv[1]);
823 else if ((victim = GetUserH(argv[1])))
824 change.args[0].u.hostmask = generate_hostmask(victim, 0);
825 else {
826 reply("OSMSG_INVALID_IRCMASK", argv[1]);
827 return 0;
828 }
829 modcmd_chanmode_announce(&change);
830 reply("OSMSG_ADDED_BAN", change.args[0].u.hostmask, channel->name);
831 free((char*)change.args[0].u.hostmask);
832 return 1;
833 }
834
835 static MODCMD_FUNC(cmd_chaninfo)
836 {
837 char buffer[MAXLEN];
838 const char *fmt;
839 struct banNode *ban;
840 struct exemptNode *exempt;
841 struct modeNode *moden;
842 unsigned int n;
843
844 reply("OSMSG_CHANINFO_HEADER", channel->name);
845 fmt = user_find_message(user, "OSMSG_CHANINFO_TIMESTAMP");
846 strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->timestamp));
847 send_message_type(4, user, cmd->parent->bot, "%s", buffer);
848 irc_make_chanmode(channel, buffer);
849 if (channel->bad_channel)
850 reply("OSMSG_CHANINFO_MODES_BADWORD", buffer);
851 else
852 reply("OSMSG_CHANINFO_MODES", buffer);
853 if (channel->topic_time) {
854 fmt = user_find_message(user, "OSMSG_CHANINFO_TOPIC");
855 strftime(buffer, sizeof(buffer), fmt, gmtime(&channel->topic_time));
856 send_message_type(4, user, cmd->parent->bot, buffer, channel->topic_nick, channel->topic);
857 } else {
858 irc_fetchtopic(cmd->parent->bot, channel->name);
859 reply("OSMSG_CHANINFO_TOPIC_UNKNOWN");
860 }
861 if (channel->banlist.used) {
862 reply("OSMSG_CHANINFO_BAN_COUNT", channel->banlist.used);
863 fmt = user_find_message(user, "OSMSG_CHANINFO_BAN");
864 for (n = 0; n < channel->banlist.used; n++) {
865 ban = channel->banlist.list[n];
866 strftime(buffer, sizeof(buffer), fmt, localtime(&ban->set));
867 send_message_type(4, user, cmd->parent->bot, buffer, ban->ban, ban->who);
868 }
869 }
870 if (channel->exemptlist.used) {
871 reply("OSMSG_CHANINFO_EXEMPT_COUNT", channel->exemptlist.used);
872 fmt = user_find_message(user, "OSMSG_CHANINFO_EXEMPT");
873 for (n = 0; n < channel->exemptlist.used; n++) {
874 exempt = channel->exemptlist.list[n];
875 strftime(buffer, sizeof(buffer), fmt, localtime(&exempt->set));
876 send_message_type(4, user, cmd->parent->bot, buffer, exempt->exempt, exempt->who);
877 }
878 }
879 if ((argc < 2) && (channel->members.used >= 50)) {
880 /* early out unless they ask for users */
881 reply("OSMSG_CHANINFO_MANY_USERS", channel->members.used, argv[0], channel->name);
882 return 1;
883 }
884 reply("OSMSG_CHANINFO_USER_COUNT", channel->members.used);
885 for (n=0; n<channel->members.used; n++) {
886 moden = channel->members.list[n];
887 if (moden->modes & MODE_CHANOP) {
888 if (moden->oplevel >= 0)
889 send_message_type(4, user, cmd->parent->bot, " @%s:%d (%s@%s)", moden->user->nick, moden->oplevel, moden->user->ident, moden->user->hostname);
890 else
891 send_message_type(4, user, cmd->parent->bot, " @%s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
892 }
893 }
894 for (n=0; n<channel->members.used; n++) {
895 moden = channel->members.list[n];
896 if ((moden->modes & (MODE_CHANOP|MODE_HALFOP|MODE_VOICE)) == MODE_HALFOP)
897 send_message_type(4, user, cmd->parent->bot, " %s%s (%s@%s)", "%", moden->user->nick, moden->user->ident, moden->user->hostname);
898 }
899 for (n=0; n<channel->members.used; n++) {
900 moden = channel->members.list[n];
901 if ((moden->modes & (MODE_CHANOP|MODE_HALFOP|MODE_VOICE)) == MODE_VOICE)
902 send_message_type(4, user, cmd->parent->bot, " +%s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
903 }
904 for (n=0; n<channel->members.used; n++) {
905 moden = channel->members.list[n];
906 if ((moden->modes & (MODE_CHANOP|MODE_HALFOP|MODE_VOICE)) == 0)
907 send_message_type(4, user, cmd->parent->bot, " %s (%s@%s)", moden->user->nick, moden->user->ident, moden->user->hostname);
908 }
909 return 1;
910 }
911
912 /* This command has been replaced by 'alert notice channel #foo' */
913 /*
914 static MODCMD_FUNC(cmd_warn)
915 {
916 char *reason, *message;
917
918 if (!IsChannelName(argv[1])) {
919 reply("OSMSG_NEED_CHANNEL", argv[0]);
920 return 0;
921 }
922 reason = dict_find(opserv_chan_warn, argv[1], NULL);
923 if (reason) {
924 reply("OSMSG_WARN_EXISTS", argv[1]);
925 return 0;
926 }
927 if (argv[2])
928 reason = strdup(unsplit_string(argv+2, argc-2, NULL));
929 else
930 reason = strdup("No reason");
931 dict_insert(opserv_chan_warn, strdup(argv[1]), reason);
932 reply("OSMSG_WARN_ADDED", argv[1], reason);
933 if (dict_find(channels, argv[1], NULL)) {
934 global_message_args(MESSAGE_RECIPIENT_OPERS, "OSMSG_CHANNEL_ACTIVITY_WARN" argv[1], reason);
935 }
936 return 1;
937 }
938
939 static MODCMD_FUNC(cmd_unwarn)
940 {
941 if ((argc < 2) || !IsChannelName(argv[1])) {
942 reply("OSMSG_NEED_CHANNEL", argv[0]);
943 return 0;
944 }
945 if (!dict_remove(opserv_chan_warn, argv[1])) {
946 reply("OSMSG_WARN_NOEXIST", argv[1]);
947 return 0;
948 }
949 reply("OSMSG_WARN_DELETED", argv[1]);
950 return 1;
951 }
952 */
953
954 static MODCMD_FUNC(cmd_clearbans)
955 {
956 struct mod_chanmode *change;
957 unsigned int ii;
958
959 change = mod_chanmode_alloc(channel->banlist.used);
960 for (ii=0; ii<channel->banlist.used; ii++) {
961 change->args[ii].mode = MODE_REMOVE | MODE_BAN;
962 change->args[ii].u.hostmask = strdup(channel->banlist.list[ii]->ban);
963 }
964 modcmd_chanmode_announce(change);
965 for (ii=0; ii<change->argc; ++ii)
966 free((char*)change->args[ii].u.hostmask);
967 mod_chanmode_free(change);
968 reply("OSMSG_CLEARBANS_DONE", channel->name);
969 return 1;
970 }
971
972 static MODCMD_FUNC(cmd_clearmodes)
973 {
974 struct mod_chanmode change;
975
976 if (!channel->modes) {
977 reply("OSMSG_NO_CHANNEL_MODES", channel->name);
978 return 0;
979 }
980 mod_chanmode_init(&change);
981 change.modes_clear = channel->modes;
982 modcmd_chanmode_announce(&change);
983 reply("OSMSG_CLEARMODES_DONE", channel->name);
984 return 1;
985 }
986
987 static MODCMD_FUNC(cmd_deop)
988 {
989 struct mod_chanmode *change;
990 unsigned int arg, count;
991
992 change = mod_chanmode_alloc(argc-1);
993 for (arg = 1, count = 0; arg < argc; ++arg) {
994 struct userNode *victim = GetUserH(argv[arg]);
995 struct modeNode *mn;
996 if (!victim || IsService(victim)
997 || !(mn = GetUserMode(channel, victim))
998 || !(mn->modes & MODE_CHANOP))
999 continue;
1000 change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
1001 change->args[count++].u.member = mn;
1002 }
1003 if (count) {
1004 change->argc = count;
1005 modcmd_chanmode_announce(change);
1006 }
1007 mod_chanmode_free(change);
1008 reply("OSMSG_DEOP_DONE");
1009 return 1;
1010 }
1011
1012 static MODCMD_FUNC(cmd_dehop)
1013 {
1014 struct mod_chanmode *change;
1015 unsigned int arg, count;
1016
1017 change = mod_chanmode_alloc(argc-1);
1018 for (arg = 1, count = 0; arg < argc; ++arg) {
1019 struct userNode *victim = GetUserH(argv[arg]);
1020 struct modeNode *mn;
1021 if (!victim || IsService(victim)
1022 || !(mn = GetUserMode(channel, victim))
1023 || !(mn->modes & MODE_HALFOP))
1024 continue;
1025 change->args[count].mode = MODE_REMOVE | MODE_HALFOP;
1026 change->args[count++].u.member = mn;
1027 }
1028 if (count) {
1029 change->argc = count;
1030 modcmd_chanmode_announce(change);
1031 }
1032 mod_chanmode_free(change);
1033 reply("OSMSG_DEHOP_DONE");
1034 return 1;
1035 }
1036
1037 static MODCMD_FUNC(cmd_deopall)
1038 {
1039 struct mod_chanmode *change;
1040 unsigned int ii, count;
1041
1042 change = mod_chanmode_alloc(channel->members.used);
1043 for (ii = count = 0; ii < channel->members.used; ++ii) {
1044 struct modeNode *mn = channel->members.list[ii];
1045 if (IsService(mn->user) || !(mn->modes & MODE_CHANOP))
1046 continue;
1047 change->args[count].mode = MODE_REMOVE | MODE_CHANOP;
1048 change->args[count++].u.member = mn;
1049 }
1050 if (count) {
1051 change->argc = count;
1052 modcmd_chanmode_announce(change);
1053 }
1054 mod_chanmode_free(change);
1055 reply("OSMSG_DEOPALL_DONE", channel->name);
1056 return 1;
1057 }
1058
1059 static MODCMD_FUNC(cmd_dehopall)
1060 {
1061 struct mod_chanmode *change;
1062 unsigned int ii, count;
1063
1064 change = mod_chanmode_alloc(channel->members.used);
1065 for (ii = count = 0; ii < channel->members.used; ++ii) {
1066 struct modeNode *mn = channel->members.list[ii];
1067 if (IsService(mn->user) || !(mn->modes & MODE_HALFOP))
1068 continue;
1069 change->args[count].mode = MODE_REMOVE | MODE_HALFOP;
1070 change->args[count++].u.member = mn;
1071 }
1072 if (count) {
1073 change->argc = count;
1074 modcmd_chanmode_announce(change);
1075 }
1076 mod_chanmode_free(change);
1077 reply("OSMSG_DEHOPALL_DONE", channel->name);
1078 return 1;
1079 }
1080
1081 static MODCMD_FUNC(cmd_resetmax)
1082 {
1083 max_clients = dict_size(clients);
1084 max_clients_time = now;
1085 reply("OSMSG_MAXUSERS_RESET", max_clients);
1086 return 1;
1087 }
1088
1089 static MODCMD_FUNC(cmd_rehash)
1090 {
1091 extern char *services_config;
1092
1093 if (conf_read(services_config))
1094 reply("OSMSG_REHASH_COMPLETE");
1095 else
1096 reply("OSMSG_REHASH_FAILED");
1097 return 1;
1098 }
1099
1100 static MODCMD_FUNC(cmd_reopen)
1101 {
1102 log_reopen();
1103 reply("OSMSG_REOPEN_COMPLETE");
1104 return 1;
1105 }
1106
1107 static MODCMD_FUNC(cmd_reconnect)
1108 {
1109 reply("OSMSG_RECONNECTING");
1110 irc_squit(self, "Reconnecting.", NULL);
1111 return 1;
1112 }
1113
1114 static MODCMD_FUNC(cmd_jupe)
1115 {
1116 extern int force_n2k;
1117 struct server *newsrv;
1118 unsigned int num;
1119 char numeric[COMBO_NUMERIC_LEN+1], srvdesc[SERVERDESCRIPTMAX+1];
1120
1121 num = atoi(argv[2]);
1122 if(num == 0) {
1123 reply("OSMSG_INVALID_NUMERIC");
1124 return 0;
1125 }
1126 if ((num < 64) && !force_n2k) {
1127 inttobase64(numeric, num, 1);
1128 inttobase64(numeric+1, 64*64-1, 2);
1129 } else {
1130 inttobase64(numeric, num, 2);
1131 inttobase64(numeric+2, 64*64*64-1, 3);
1132 }
1133 #ifdef WITH_PROTOCOL_P10
1134 if (GetServerN(numeric)) {
1135 reply("OSMSG_NUMERIC_COLLIDE", num, numeric);
1136 return 0;
1137 }
1138 #endif
1139 if (GetServerH(argv[1])) {
1140 reply("OSMSG_NAME_COLLIDE");
1141 return 0;
1142 }
1143 snprintf(srvdesc, sizeof(srvdesc), "JUPE %s", unsplit_string(argv+3, argc-3, NULL));
1144 if(!strchr(argv[1], '.')) {
1145 reply("OSMSG_INVALID_SERVERNAME");
1146 return 0;
1147 }
1148 newsrv = AddServer(self, argv[1], 1, now, now, numeric, srvdesc);
1149 if (!newsrv) {
1150 reply("OSMSG_SRV_CREATE_FAILED");
1151 return 0;
1152 }
1153 irc_server(newsrv);
1154 reply("OSMSG_SERVER_JUPED", argv[1]);
1155 return 1;
1156 }
1157
1158 static MODCMD_FUNC(cmd_unjupe)
1159 {
1160 struct server *srv;
1161 char *reason;
1162
1163 srv = GetServerH(argv[1]);
1164 if (!srv) {
1165 reply("MSG_SERVER_UNKNOWN", argv[1]);
1166 return 0;
1167 }
1168 if (strncmp(srv->description, "JUPE", 4)) {
1169 reply("OSMSG_SERVER_NOT_JUPE");
1170 return 0;
1171 }
1172 reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : "Unjuping server";
1173 DelServer(srv, 1, reason);
1174 reply("OSMSG_SERVER_UNJUPED");
1175 return 1;
1176 }
1177
1178 static MODCMD_FUNC(cmd_jump)
1179 {
1180 extern struct cManagerNode cManager;
1181 void uplink_select(char *name);
1182 struct uplinkNode *uplink_find(char *name);
1183 struct uplinkNode *uplink;
1184 char *target;
1185
1186 target = unsplit_string(argv+1, argc-1, NULL);
1187
1188 if (!strcmp(cManager.uplink->name, target)) {
1189 reply("OSMSG_CURRENT_UPLINK", cManager.uplink->name);
1190 return 0;
1191 }
1192
1193 uplink = uplink_find(target);
1194 if (!uplink) {
1195 reply("OSMSG_INVALID_UPLINK", target);
1196 return 0;
1197 }
1198 if (uplink->flags & UPLINK_UNAVAILABLE) {
1199 reply("OSMSG_UPLINK_DISABLED", uplink->name);
1200 return 0;
1201 }
1202
1203 reply("OSMSG_UPLINK_CONNECTING", uplink->name, uplink->host, uplink->port);
1204 uplink_select(target);
1205 irc_squit(self, "Reconnecting.", NULL);
1206 return 1;
1207 }
1208
1209 static MODCMD_FUNC(cmd_die)
1210 {
1211 char *reason, *text;
1212
1213 text = unsplit_string(argv+1, argc-1, NULL);
1214 reason = alloca(strlen(text) + strlen(user->nick) + 20);
1215 sprintf(reason, "Disconnected by %s [%s]", user->nick, text);
1216 irc_squit(self, reason, text);
1217 quit_services = 1;
1218 return 1;
1219 }
1220
1221 static MODCMD_FUNC(cmd_restart)
1222 {
1223 extern int services_argc;
1224 extern char **services_argv;
1225 char **restart_argv, *reason, *text;
1226
1227 text = unsplit_string(argv+1, argc-1, NULL);
1228 reason = alloca(strlen(text) + strlen(user->nick) + 17);
1229 sprintf(reason, "Restarted by %s [%s]", user->nick, text);
1230 irc_squit(self, reason, text);
1231
1232 /* Append a NULL to the end of argv[]. */
1233 restart_argv = (char **)alloca((services_argc + 1) * sizeof(char *));
1234 memcpy(restart_argv, services_argv, services_argc * sizeof(char *));
1235 restart_argv[services_argc] = NULL;
1236
1237 call_exit_funcs();
1238
1239 /* Don't blink. */
1240 execv(services_argv[0], restart_argv);
1241
1242 /* If we're still here, that means something went wrong. Reconnect. */
1243 return 1;
1244 }
1245
1246 static struct gline *
1247 opserv_block(struct userNode *target, char *src_handle, char *reason, unsigned long duration, int silent)
1248 {
1249 char mask[IRC_NTOP_MAX_SIZE+3] = { '*', '@', '\0' };
1250 irc_ntop(mask + 2, sizeof(mask) - 2, &target->ip);
1251 if (!reason)
1252 snprintf(reason = alloca(MAXLEN), MAXLEN,
1253 "G-line requested by %s.", src_handle);
1254 if (!duration)
1255 duration = opserv_conf.block_gline_duration;
1256 return gline_add(src_handle, mask, duration, reason, now, 1, silent ? 1 : 0);
1257 }
1258
1259 static MODCMD_FUNC(cmd_block)
1260 {
1261 struct userNode *target;
1262 struct gline *gline;
1263 char *reason;
1264
1265 target = GetUserH(argv[1]);
1266 if (!target) {
1267 reply("MSG_NICK_UNKNOWN", argv[1]);
1268 return 0;
1269 }
1270 if (IsService(target)) {
1271 reply("MSG_SERVICE_IMMUNE", target->nick);
1272 return 0;
1273 }
1274 reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : NULL;
1275 gline = opserv_block(target, user->handle_info->handle, reason, 0, 0);
1276 reply("OSMSG_GLINE_ISSUED", gline->target);
1277 return 1;
1278 }
1279
1280 static MODCMD_FUNC(cmd_gline)
1281 {
1282 unsigned long duration;
1283 char *reason;
1284 struct gline *gline;
1285
1286 reason = unsplit_string(argv+3, argc-3, NULL);
1287 if (!is_gline(argv[1]) && !IsChannelName(argv[1]) && (argv[1][0] != '&')) {
1288 reply("MSG_INVALID_GLINE", argv[1]);
1289 return 0;
1290 }
1291 if (!argv[1][strspn(argv[1], "#&*?@.")] && (strlen(argv[1]) < 10)) {
1292 reply("OSMSG_STUPID_GLINE", argv[1]);
1293 return 0;
1294 }
1295 duration = ParseInterval(argv[2]);
1296 if (!duration) {
1297 reply("MSG_INVALID_DURATION", argv[2]);
1298 return 0;
1299 }
1300 gline = gline_add(user->handle_info->handle, argv[1], duration, reason, now, 1, 0);
1301 reply("OSMSG_GLINE_ISSUED", gline->target);
1302 return 1;
1303 }
1304
1305 static MODCMD_FUNC(cmd_ungline)
1306 {
1307 if (gline_remove(argv[1], 1))
1308 reply("OSMSG_GLINE_REMOVED", argv[1]);
1309 else
1310 reply("OSMSG_GLINE_FORCE_REMOVED", argv[1]);
1311 return 1;
1312 }
1313
1314 static MODCMD_FUNC(cmd_refreshg)
1315 {
1316 if (argc > 1) {
1317 unsigned int count;
1318 dict_iterator_t it;
1319 struct server *srv;
1320
1321 for (it=dict_first(servers), count=0; it; it=iter_next(it)) {
1322 srv = iter_data(it);
1323 if ((srv == self) || !match_ircglob(srv->name, argv[1]))
1324 continue;
1325 gline_refresh_server(srv);
1326 reply("OSMSG_GLINES_ONE_REFRESHED", srv->name);
1327 count++;
1328 }
1329 if (!count) {
1330 reply("MSG_SERVER_UNKNOWN", argv[1]);
1331 return 0;
1332 }
1333 } else {
1334 gline_refresh_all();
1335 reply("OSMSG_GLINES_REFRESHED");
1336 }
1337 return 1;
1338 }
1339
1340 static struct shun *
1341 opserv_shun(struct userNode *target, char *src_handle, char *reason, unsigned long duration)
1342 {
1343 char *mask;
1344 mask = alloca(MAXLEN);
1345 snprintf(mask, MAXLEN, "*@%s", target->hostname);
1346 if (!reason) {
1347 reason = alloca(MAXLEN);
1348 snprintf(reason, MAXLEN, "Shun requested by %s.", src_handle);
1349 }
1350 if (!duration) duration = opserv_conf.block_shun_duration;
1351 return shun_add(src_handle, mask, duration, reason, now, 1);
1352 }
1353
1354 static MODCMD_FUNC(cmd_sblock)
1355 {
1356 struct userNode *target;
1357 struct shun *shun;
1358 char *reason;
1359
1360 target = GetUserH(argv[1]);
1361 if (!target) {
1362 reply("MSG_NICK_UNKNOWN", argv[1]);
1363 return 0;
1364 }
1365 if (IsService(target)) {
1366 reply("MSG_SERVICE_IMMUNE", target->nick);
1367 return 0;
1368 }
1369 reason = (argc > 2) ? unsplit_string(argv+2, argc-2, NULL) : NULL;
1370 shun = opserv_shun(target, user->handle_info->handle, reason, 0);
1371 reply("OSMSG_SHUN_ISSUED", shun->target);
1372 return 1;
1373 }
1374
1375 static MODCMD_FUNC(cmd_shun)
1376 {
1377 unsigned long duration;
1378 char *reason;
1379 struct shun *shun;
1380
1381 reason = unsplit_string(argv+3, argc-3, NULL);
1382 if (!is_shun(argv[1]) && !IsChannelName(argv[1]) && (argv[1][0] != '&')) {
1383 reply("MSG_INVALID_SHUN", argv[1]);
1384 return 0;
1385 }
1386 if (!argv[1][strspn(argv[1], "#&*?@.")] && (strlen(argv[1]) < 10)) {
1387 reply("OSMSG_STUPID_SHUN", argv[1]);
1388 return 0;
1389 }
1390 duration = ParseInterval(argv[2]);
1391 if (!duration) {
1392 reply("MSG_INVALID_DURATION", argv[2]);
1393 return 0;
1394 }
1395 shun = shun_add(user->handle_info->handle, argv[1], duration, reason, now, 1);
1396 reply("OSMSG_SHUN_ISSUED", shun->target);
1397 return 1;
1398 }
1399
1400 static MODCMD_FUNC(cmd_unshun)
1401 {
1402 if (shun_remove(argv[1], 1))
1403 reply("OSMSG_SHUN_REMOVED", argv[1]);
1404 else
1405 reply("OSMSG_SHUN_FORCE_REMOVED", argv[1]);
1406 return 1;
1407 }
1408
1409 static MODCMD_FUNC(cmd_refreshs)
1410 {
1411 if (argc > 1) {
1412 unsigned int count;
1413 dict_iterator_t it;
1414 struct server *srv;
1415
1416 for (it=dict_first(servers), count=0; it; it=iter_next(it)) {
1417 srv = iter_data(it);
1418 if ((srv == self) || !match_ircglob(srv->name, argv[1]))
1419 continue;
1420 shun_refresh_server(srv);
1421 reply("OSMSG_SHUNS_ONE_REFRESHED", srv->name);
1422 count++;
1423 }
1424 if (!count) {
1425 reply("MSG_SERVER_UNKNOWN", argv[1]);
1426 return 0;
1427 }
1428 } else {
1429 shun_refresh_all();
1430 reply("OSMSG_SHUNS_REFRESHED");
1431 }
1432 return 1;
1433 }
1434
1435 static void
1436 opserv_ison(struct userNode *tell, struct userNode *target, const char *message)
1437 {
1438 struct modeNode *mn;
1439 unsigned int count, here_len, n, maxlen;
1440 char buff[MAXLEN];
1441
1442 maxlen = tell->handle_info ? tell->handle_info->screen_width : 0;
1443 if (!maxlen)
1444 maxlen = MAX_LINE_SIZE;
1445 for (n=count=0; n<target->channels.used; n++) {
1446 mn = target->channels.list[n];
1447 here_len = strlen(mn->channel->name);
1448 if ((count + here_len + 4) > maxlen) {
1449 buff[count] = 0;
1450 send_message(tell, opserv, message, buff);
1451 count = 0;
1452 }
1453 if (mn->modes & MODE_CHANOP)
1454 buff[count++] = '@';
1455 if (mn->modes & MODE_HALFOP)
1456 buff[count++] = '%';
1457 if (mn->modes & MODE_VOICE)
1458 buff[count++] = '+';
1459 memcpy(buff+count, mn->channel->name, here_len);
1460 count += here_len;
1461 buff[count++] = ' ';
1462 }
1463 if (count) {
1464 buff[count] = 0;
1465 send_message(tell, opserv, message, buff);
1466 }
1467 }
1468
1469 static MODCMD_FUNC(cmd_inviteme)
1470 {
1471 struct userNode *target;
1472
1473 if (argc < 2) {
1474 target = user;
1475 } else {
1476 target = GetUserH(argv[1]);
1477 if (!target) {
1478 reply("MSG_NICK_UNKNOWN", argv[1]);
1479 return 0;
1480 }
1481 }
1482 if (opserv_conf.debug_channel == NULL) {
1483 reply("OSMSG_NO_DEBUG_CHANNEL");
1484 return 0;
1485 }
1486 if (GetUserMode(opserv_conf.debug_channel, user)) {
1487 reply("OSMSG_ALREADY_THERE", opserv_conf.debug_channel->name);
1488 return 0;
1489 }
1490 irc_invite(cmd->parent->bot, target, opserv_conf.debug_channel);
1491 if (target != user)
1492 reply("OSMSG_INVITE_DONE", target->nick, opserv_conf.debug_channel->name);
1493 return 1;
1494 }
1495
1496 static MODCMD_FUNC(cmd_invite)
1497 {
1498 if (GetUserMode(channel, user)) {
1499 reply("OSMSG_ALREADY_THERE", channel->name);
1500 return 0;
1501 }
1502 irc_invite(cmd->parent->bot, user, channel);
1503 return 1;
1504 }
1505
1506 static MODCMD_FUNC(cmd_join)
1507 {
1508 struct userNode *bot = cmd->parent->bot;
1509
1510 if (!IsChannelName(argv[1])) {
1511 reply("MSG_NOT_CHANNEL_NAME");
1512 return 0;
1513 } else if (!(channel = GetChannel(argv[1]))) {
1514 channel = AddChannel(argv[1], now, NULL, NULL, NULL);
1515 AddChannelUser(bot, channel)->modes |= MODE_CHANOP;
1516 } else if (GetUserMode(channel, bot)) {
1517 reply("OSMSG_ALREADY_JOINED", channel->name);
1518 return 0;
1519 } else {
1520 struct mod_chanmode change;
1521 mod_chanmode_init(&change);
1522 change.argc = 1;
1523 change.args[0].mode = MODE_CHANOP;
1524 change.args[0].u.member = AddChannelUser(bot, channel);
1525 modcmd_chanmode_announce(&change);
1526 }
1527 irc_fetchtopic(bot, channel->name);
1528 reply("OSMSG_JOIN_DONE", channel->name);
1529 return 1;
1530 }
1531
1532 static MODCMD_FUNC(cmd_kick)
1533 {
1534 struct userNode *target;
1535 char *reason;
1536
1537 if (argc < 3) {
1538 reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1539 sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1540 } else {
1541 reason = unsplit_string(argv+2, argc-2, NULL);
1542 }
1543 target = GetUserH(argv[1]);
1544 if (!target) {
1545 reply("MSG_NICK_UNKNOWN", argv[1]);
1546 return 0;
1547 }
1548 if (!GetUserMode(channel, target)) {
1549 reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
1550 return 0;
1551 }
1552 KickChannelUser(target, channel, cmd->parent->bot, reason);
1553 return 1;
1554 }
1555
1556 static MODCMD_FUNC(cmd_kickall)
1557 {
1558 unsigned int limit, n, inchan;
1559 struct modeNode *mn;
1560 char *reason;
1561 struct userNode *bot = cmd->parent->bot;
1562
1563 /* ircu doesn't let servers KICK users, so if OpServ's not in the
1564 * channel, we have to join it in temporarily. */
1565 if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
1566 struct mod_chanmode change;
1567 mod_chanmode_init(&change);
1568 change.args[0].mode = MODE_CHANOP;
1569 change.args[0].u.member = AddChannelUser(bot, channel);
1570 modcmd_chanmode_announce(&change);
1571 }
1572 if (argc < 2) {
1573 reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1574 sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1575 } else {
1576 reason = unsplit_string(argv+1, argc-1, NULL);
1577 }
1578 limit = user->handle_info->opserv_level;
1579 for (n=channel->members.used; n>0;) {
1580 mn = channel->members.list[--n];
1581 if (IsService(mn->user)
1582 || (mn->user->handle_info
1583 && (mn->user->handle_info->opserv_level >= limit))) {
1584 continue;
1585 }
1586 KickChannelUser(mn->user, channel, bot, reason);
1587 }
1588 if (!inchan)
1589 DelChannelUser(bot, channel, "My work here is done", 0);
1590 reply("OSMSG_KICKALL_DONE", channel->name);
1591 return 1;
1592 }
1593
1594 static MODCMD_FUNC(cmd_kickban)
1595 {
1596 struct mod_chanmode change;
1597 struct userNode *target;
1598 char *reason;
1599 char *mask;
1600
1601 if (argc == 2) {
1602 reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1603 sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1604 } else {
1605 reason = unsplit_string(argv+2, argc-2, NULL);
1606 }
1607 target = GetUserH(argv[1]);
1608 if (!target) {
1609 reply("MSG_NICK_UNKNOWN", argv[1]);
1610 return 0;
1611 }
1612 if (!GetUserMode(channel, target)) {
1613 reply("OSMSG_NOT_ON_CHANNEL", target->nick, channel->name);
1614 return 0;
1615 }
1616 mod_chanmode_init(&change);
1617 change.argc = 1;
1618 change.args[0].mode = MODE_BAN;
1619 change.args[0].u.hostmask = mask = generate_hostmask(target, 0);
1620 modcmd_chanmode_announce(&change);
1621 KickChannelUser(target, channel, cmd->parent->bot, reason);
1622 free(mask);
1623 return 1;
1624 }
1625
1626 static MODCMD_FUNC(cmd_kickbanall)
1627 {
1628 struct modeNode *mn;
1629 struct userNode *bot = cmd->parent->bot;
1630 struct mod_chanmode *change;
1631 char *reason;
1632 unsigned int limit, n, inchan;
1633
1634 /* ircu doesn't let servers KICK users, so if OpServ's not in the
1635 * channel, we have to join it in temporarily. */
1636 if (!(inchan = GetUserMode(channel, bot) ? 1 : 0)) {
1637 change = mod_chanmode_alloc(2);
1638 change->args[0].mode = MODE_CHANOP;
1639 change->args[0].u.member = AddChannelUser(bot, channel);
1640 change->args[1].mode = MODE_BAN;
1641 change->args[1].u.hostmask = "*!*@*";
1642 } else {
1643 change = mod_chanmode_alloc(1);
1644 change->args[0].mode = MODE_BAN;
1645 change->args[0].u.hostmask = "*!*@*";
1646 }
1647 modcmd_chanmode_announce(change);
1648 mod_chanmode_free(change);
1649 if (argc < 2) {
1650 reason = alloca(strlen(OSMSG_KICK_REQUESTED)+strlen(user->nick)+1);
1651 sprintf(reason, OSMSG_KICK_REQUESTED, user->nick);
1652 } else {
1653 reason = unsplit_string(argv+1, argc-1, NULL);
1654 }
1655 /* now kick them */
1656 limit = user->handle_info->opserv_level;
1657 for (n=channel->members.used; n>0; ) {
1658 mn = channel->members.list[--n];
1659 if (IsService(mn->user)
1660 || (mn->user->handle_info
1661 && (mn->user->handle_info->opserv_level >= limit))) {
1662 continue;
1663 }
1664 KickChannelUser(mn->user, channel, bot, reason);
1665 }
1666 if (!inchan)
1667 DelChannelUser(bot, channel, "My work here is done", 0);
1668 reply("OSMSG_KICKALL_DONE", channel->name);
1669 return 1;
1670 }
1671
1672 static MODCMD_FUNC(cmd_part)
1673 {
1674 char *reason;
1675
1676 if (!IsChannelName(argv[1])) {
1677 reply("MSG_NOT_CHANNEL_NAME");
1678 return 0;
1679 }
1680 if ((channel = GetChannel(argv[1]))) {
1681 if (!GetUserMode(channel, cmd->parent->bot)) {
1682 reply("OSMSG_NOT_ON_CHANNEL", cmd->parent->bot->nick, channel->name);
1683 return 0;
1684 }
1685 reason = (argc < 3) ? "Leaving." : unsplit_string(argv+2, argc-2, NULL);
1686 reply("OSMSG_LEAVING", channel->name);
1687 DelChannelUser(cmd->parent->bot, channel, reason, 0);
1688 }
1689 return 1;
1690 }
1691
1692 static MODCMD_FUNC(cmd_mode)
1693 {
1694 if (!modcmd_chanmode(argv+1, argc-1, MCP_ALLOW_OVB|MCP_KEY_FREE|MC_ANNOUNCE)) {
1695 reply("MSG_INVALID_MODES", unsplit_string(argv+1, argc-1, NULL));
1696 return 0;
1697 }
1698 reply("OSMSG_MODE_SET", channel->name);
1699 return 1;
1700 }
1701
1702 static MODCMD_FUNC(cmd_op)
1703 {
1704 struct mod_chanmode *change;
1705 unsigned int arg, count;
1706
1707 change = mod_chanmode_alloc(argc-1);
1708 for (arg = 1, count = 0; arg < argc; ++arg) {
1709 struct userNode *victim;
1710 struct modeNode *mn;
1711 if (!(victim = GetUserH(argv[arg])))
1712 continue;
1713 if (!(mn = GetUserMode(channel, victim)))
1714 continue;
1715 if (mn->modes & MODE_CHANOP)
1716 continue;
1717 change->args[count].mode = MODE_CHANOP;
1718 change->args[count++].u.member = mn;
1719 }
1720 if (count) {
1721 change->argc = count;
1722 modcmd_chanmode_announce(change);
1723 }
1724 mod_chanmode_free(change);
1725 reply("OSMSG_OP_DONE");
1726 return 1;
1727 }
1728
1729 static MODCMD_FUNC(cmd_hop)
1730 {
1731 struct mod_chanmode *change;
1732 unsigned int arg, count;
1733
1734 change = mod_chanmode_alloc(argc-1);
1735 for (arg = 1, count = 0; arg < argc; ++arg) {
1736 struct userNode *victim;
1737 struct modeNode *mn;
1738 if (!(victim = GetUserH(argv[arg])))
1739 continue;
1740 if (!(mn = GetUserMode(channel, victim)))
1741 continue;
1742 if (mn->modes & MODE_HALFOP)
1743 continue;
1744 change->args[count].mode = MODE_HALFOP;
1745 change->args[count++].u.member = mn;
1746 }
1747 if (count) {
1748 change->argc = count;
1749 modcmd_chanmode_announce(change);
1750 }
1751 mod_chanmode_free(change);
1752 reply("OSMSG_HOP_DONE");
1753 return 1;
1754 }
1755
1756 static MODCMD_FUNC(cmd_opall)
1757 {
1758 struct mod_chanmode *change;
1759 unsigned int ii, count;
1760
1761 change = mod_chanmode_alloc(channel->members.used);
1762 for (ii = count = 0; ii < channel->members.used; ++ii) {
1763 struct modeNode *mn = channel->members.list[ii];
1764 if (mn->modes & MODE_CHANOP)
1765 continue;
1766 change->args[count].mode = MODE_CHANOP;
1767 change->args[count++].u.member = mn;
1768 }
1769 if (count) {
1770 change->argc = count;
1771 modcmd_chanmode_announce(change);
1772 }
1773 mod_chanmode_free(change);
1774 reply("OSMSG_OPALL_DONE", channel->name);
1775 return 1;
1776 }
1777
1778 static MODCMD_FUNC(cmd_hopall)
1779 {
1780 struct mod_chanmode *change;
1781 unsigned int ii, count;
1782
1783 change = mod_chanmode_alloc(channel->members.used);
1784 for (ii = count = 0; ii < channel->members.used; ++ii) {
1785 struct modeNode *mn = channel->members.list[ii];
1786 if (mn->modes & MODE_HALFOP)
1787 continue;
1788 change->args[count].mode = MODE_HALFOP;
1789 change->args[count++].u.member = mn;
1790 }
1791 if (count) {
1792 change->argc = count;
1793 modcmd_chanmode_announce(change);
1794 }
1795 mod_chanmode_free(change);
1796 reply("OSMSG_HOPALL_DONE", channel->name);
1797 return 1;
1798 }
1799
1800 static MODCMD_FUNC(cmd_whois)
1801 {
1802 struct userNode *target;
1803 char buffer[128];
1804 int bpos, herelen;
1805
1806 #ifdef WITH_PROTOCOL_P10
1807 if (argv[1][0] == '*')
1808 target = GetUserN(argv[1]+1);
1809 else
1810 #endif
1811 target = GetUserH(argv[1]);
1812 if (!target) {
1813 reply("MSG_NICK_UNKNOWN", argv[1]);
1814 return 0;
1815 }
1816 reply("OSMSG_WHOIS_NICK", target->nick);
1817 reply("OSMSG_WHOIS_HOST", target->ident, target->hostname);
1818 if (IsFakeHost(target))
1819 reply("OSMSG_WHOIS_FAKEHOST", target->fakehost);
1820 reply("OSMSG_WHOIS_CRYPT_HOST", target->crypthost);
1821 reply("OSMSG_WHOIS_CRYPT_IP", target->cryptip);
1822 reply("OSMSG_WHOIS_IP", irc_ntoa(&target->ip));
1823
1824 if (target->city) {
1825 reply("OSMSG_WHOIS_COUNTRY", target->country_name);
1826 reply("OSMSG_WHOIS_COUNTRY_CODE", target->country_code);
1827 reply("OSMSG_WHOIS_CITY", target->city);
1828 reply("OSMSG_WHOIS_REGION", target->region);
1829
1830 reply("OSMSG_WHOIS_POSTAL_CODE", target->postal_code);
1831 reply("OSMSG_WHOIS_LATITUDE", target->latitude);
1832 reply("OSMSG_WHOIS_LONGITUDE", target->longitude);
1833 /* Only show a map url if we have a city, latitude and longitude.
1834 * Theres not much point of latitude and longitude coordinates are
1835 * returned but no city, the coordinates are useless.
1836 */
1837 if (target->latitude && target->longitude && target->city) {
1838 char map_url[MAXLEN];
1839 snprintf(map_url, sizeof(map_url), "http://www.mapquest.com/maps/map.adp?searchtype=address&formtype=address&latlongtype=decimal&latitude=%f&longitude=%f",
1840 target->latitude, target->longitude);
1841 reply("OSMSG_WHOIS_MAP", map_url);
1842 }
1843 reply("OSMSG_WHOIS_DMA_CODE", target->dma_code);
1844 reply("OSMSG_WHOIS_AREA_CODE", target->area_code);
1845 } else if (target->country_name) {
1846 reply("OSMSG_WHOIS_COUNTRY", target->country_name);
1847 }
1848
1849 if (target->modes) {
1850 bpos = 0;
1851 #define buffer_cat(str) (herelen = strlen(str), memcpy(buffer+bpos, str, herelen), bpos += herelen)
1852 if (IsInvisible(target)) buffer[bpos++] = 'i';
1853 if (IsWallOp(target)) buffer[bpos++] = 'w';
1854 if (IsOper(target)) buffer[bpos++] = 'o';
1855 if (IsGlobal(target)) buffer[bpos++] = 'g';
1856 if (IsServNotice(target)) buffer[bpos++] = 's';
1857
1858 // sethost - reed/apples
1859 // if (IsHelperIrcu(target)) buffer[bpos++] = 'h';
1860 if (IsSetHost(target)) buffer[bpos++] = 'h';
1861
1862 if (IsService(target)) buffer[bpos++] = 'k';
1863 if (IsDeaf(target)) buffer[bpos++] = 'd';
1864 if (target->handle_info) buffer[bpos++] = 'r';
1865 if (IsHiddenHost(target)) buffer[bpos++] = 'x';
1866 if (IsGagged(target)) buffer_cat(" (gagged)");
1867 if (IsRegistering(target)) buffer_cat(" (registered account)");
1868 buffer[bpos] = 0;
1869 if (bpos > 0)
1870 reply("OSMSG_WHOIS_MODES", buffer);
1871 }
1872 reply("OSMSG_WHOIS_INFO", target->info);
1873 #ifdef WITH_PROTOCOL_P10
1874 reply("OSMSG_WHOIS_NUMERIC", target->numeric);
1875 #endif
1876 reply("OSMSG_WHOIS_SERVER", target->uplink->name);
1877 reply("OSMSG_WHOIS_ACCOUNT", (target->handle_info ? target->handle_info->handle : "Not authenticated"));
1878
1879 reply("OSMSG_WHOIS_PRIVS", client_report_privs(target));
1880
1881 intervalString(buffer, now - target->timestamp, user->handle_info);
1882 reply("OSMSG_WHOIS_NICK_AGE", buffer);
1883 if (target->channels.used <= MAX_CHANNELS_WHOIS)
1884 opserv_ison(user, target, "OSMSG_WHOIS_CHANNELS");
1885 else
1886 reply("OSMSG_WHOIS_HIDECHANS");
1887 return 1;
1888 }
1889
1890 static MODCMD_FUNC(cmd_unban)
1891 {
1892 struct mod_chanmode change;
1893 mod_chanmode_init(&change);
1894 change.argc = 1;
1895 change.args[0].mode = MODE_REMOVE | MODE_BAN;
1896 change.args[0].u.hostmask = argv[1];
1897 modcmd_chanmode_announce(&change);
1898 reply("OSMSG_UNBAN_DONE", channel->name);
1899 return 1;
1900 }
1901
1902 static MODCMD_FUNC(cmd_voiceall)
1903 {
1904 struct mod_chanmode *change;
1905 unsigned int ii, count;
1906
1907 change = mod_chanmode_alloc(channel->members.used);
1908 for (ii = count = 0; ii < channel->members.used; ++ii) {
1909 struct modeNode *mn = channel->members.list[ii];
1910 if (mn->modes & (MODE_CHANOP|MODE_HALFOP|MODE_VOICE))
1911 continue;
1912 change->args[count].mode = MODE_VOICE;
1913 change->args[count++].u.member = mn;
1914 }
1915 if (count) {
1916 change->argc = count;
1917 modcmd_chanmode_announce(change);
1918 }
1919 mod_chanmode_free(change);
1920 reply("OSMSG_CHANNEL_VOICED", channel->name);
1921 return 1;
1922 }
1923
1924 static MODCMD_FUNC(cmd_devoiceall)
1925 {
1926 struct mod_chanmode *change;
1927 unsigned int ii, count;
1928
1929 change = mod_chanmode_alloc(channel->members.used);
1930 for (ii = count = 0; ii < channel->members.used; ++ii) {
1931 struct modeNode *mn = channel->members.list[ii];
1932 if (!(mn->modes & MODE_VOICE))
1933 continue;
1934 change->args[count].mode = MODE_REMOVE | MODE_VOICE;
1935 change->args[count++].u.member = mn;
1936 }
1937 if (count) {
1938 change->argc = count;
1939 modcmd_chanmode_announce(change);
1940 }
1941 mod_chanmode_free(change);
1942 reply("OSMSG_CHANNEL_DEVOICED", channel->name);
1943 return 1;
1944 }
1945
1946 static MODCMD_FUNC(cmd_stats_bad) {
1947 dict_iterator_t it;
1948 unsigned int ii, end, here_len;
1949 char buffer[400];
1950
1951 /* Show the bad word list.. */
1952 /* TODO: convert nonprinting chars like bold to $b etc in a usable way */
1953 for (ii=end=0; ii<opserv_bad_words->used; ii++) {
1954 here_len = strlen(opserv_bad_words->list[ii]);
1955 /* If the line is full output it & start again */
1956 if ((end + here_len + 2) > sizeof(buffer)) {
1957 buffer[end] = 0;
1958 reply("OSMSG_BADWORD_LIST", buffer);
1959 end = 0;
1960 }
1961 memcpy(buffer+end, opserv_bad_words->list[ii], here_len);
1962 end += here_len;
1963 buffer[end++] = ' ';
1964 }
1965 buffer[end] = 0;
1966 reply("OSMSG_BADWORD_LIST", buffer);
1967
1968 /* Show the exemption list.. */
1969 for (it=dict_first(opserv_exempt_channels), end=0; it; it=iter_next(it)) {
1970 here_len = strlen(iter_key(it));
1971 if ((end + here_len + 2) > sizeof(buffer)) {
1972 buffer[end] = 0;
1973 reply("OSMSG_EXEMPTED_LIST", buffer);
1974 end = 0;
1975 }
1976 memcpy(buffer+end, iter_key(it), here_len);
1977 end += here_len;
1978 buffer[end++] = ' ';
1979 }
1980 buffer[end] = 0;
1981 reply("OSMSG_EXEMPTED_LIST", buffer);
1982 return 1;
1983 }
1984
1985 static MODCMD_FUNC(cmd_stats_glines) {
1986 reply("OSMSG_GLINE_COUNT", gline_count());
1987 return 1;
1988 }
1989
1990 static MODCMD_FUNC(cmd_stats_shuns) {
1991 reply("OSMSG_SHUN_COUNT", shun_count());
1992 return 1;
1993 }
1994
1995 static void
1996 trace_links(struct userNode *bot, struct userNode *user, struct server *server, unsigned int depth) {
1997 unsigned int nn, pos;
1998 char buffer[400];
1999
2000 for (nn=1; nn<=depth; nn<<=1) ;
2001 for (pos=0, nn>>=1; nn>1; ) {
2002 nn >>= 1;
2003 buffer[pos++] = (depth & nn) ? ((nn == 1) ? '`' : ' ') : '|';
2004 buffer[pos++] = (nn == 1) ? '-': ' ';
2005 }
2006 buffer[pos] = 0;
2007 send_message(user, bot, "OSMSG_LINKS_SERVER", buffer, server->name, server->clients, server->description);
2008 if (!server->children.used)
2009 return;
2010 for (nn=0; nn<server->children.used-1; nn++) {
2011 trace_links(bot, user, server->children.list[nn], depth<<1);
2012 }
2013 trace_links(bot, user, server->children.list[nn], (depth<<1)|1);
2014 }
2015
2016 static MODCMD_FUNC(cmd_stats_links) {
2017 trace_links(cmd->parent->bot, user, self, 1);
2018 return 1;
2019 }
2020
2021
2022 static MODCMD_FUNC(cmd_stats_max) {
2023 reply("OSMSG_MAX_CLIENTS", max_clients, asctime(localtime(&max_clients_time)));
2024 return 1;
2025 }
2026
2027 static MODCMD_FUNC(cmd_stats_network) {
2028 struct helpfile_table tbl;
2029 unsigned int nn, tot_clients;
2030 dict_iterator_t it;
2031
2032 tot_clients = dict_size(clients);
2033 reply("OSMSG_NETWORK_INFO", tot_clients, invis_clients, curr_opers.used);
2034 tbl.length = dict_size(servers)+1;
2035 tbl.width = 3;
2036 tbl.flags = TABLE_NO_FREE;
2037 tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
2038 tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
2039 tbl.contents[0][0] = "Server Name";
2040 tbl.contents[0][1] = "Clients";
2041 tbl.contents[0][2] = "Load";
2042 for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
2043 struct server *server = iter_data(it);
2044 char *buffer = malloc(32);
2045 tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
2046 tbl.contents[nn][0] = server->name;
2047 tbl.contents[nn][1] = buffer;
2048 sprintf(buffer, "%u", server->clients);
2049 tbl.contents[nn][2] = buffer + 16;
2050 sprintf(buffer+16, "%3.3g%%", ((double)server->clients/tot_clients)*100);
2051 nn++;
2052 }
2053 table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
2054 for (nn=1; nn<tbl.length; nn++) {
2055 free((char*)tbl.contents[nn][1]);
2056 free(tbl.contents[nn]);
2057 }
2058 free(tbl.contents[0]);
2059 free(tbl.contents);
2060 return 1;
2061 }
2062
2063 static MODCMD_FUNC(cmd_stats_network2) {
2064 struct helpfile_table tbl;
2065 unsigned int nn;
2066 dict_iterator_t it;
2067
2068 tbl.length = dict_size(servers)+1;
2069 tbl.width = 3;
2070 tbl.flags = TABLE_NO_FREE;
2071 tbl.contents = calloc(tbl.length, sizeof(*tbl.contents));
2072 tbl.contents[0] = calloc(tbl.width, sizeof(**tbl.contents));
2073 tbl.contents[0][0] = "Server Name";
2074 tbl.contents[0][1] = "Numeric";
2075 tbl.contents[0][2] = "Link Time";
2076 for (it=dict_first(servers), nn=1; it; it=iter_next(it)) {
2077 struct server *server = iter_data(it);
2078 char *buffer = malloc(64);
2079 int ofs;
2080
2081 tbl.contents[nn] = calloc(tbl.width, sizeof(**tbl.contents));
2082 tbl.contents[nn][0] = server->name;
2083 #ifdef WITH_PROTOCOL_P10
2084 sprintf(buffer, "%s (%ld)", server->numeric, base64toint(server->numeric, strlen(server->numeric)));
2085 #else
2086 buffer[0] = 0;
2087 #endif
2088 tbl.contents[nn][1] = buffer;
2089 ofs = strlen(buffer) + 1;
2090 intervalString(buffer + ofs, now - server->link, user->handle_info);
2091 if (server->self_burst)
2092 strcat(buffer + ofs, " Bursting");
2093 tbl.contents[nn][2] = buffer + ofs;
2094 nn++;
2095 }
2096 table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
2097 for (nn=1; nn<tbl.length; nn++) {
2098 free((char*)tbl.contents[nn][1]);
2099 free(tbl.contents[nn]);
2100 }
2101 free(tbl.contents[0]);
2102 free(tbl.contents);
2103 return 1;
2104 }
2105
2106 static MODCMD_FUNC(cmd_stats_reserved) {
2107 dict_iterator_t it;
2108
2109 reply("OSMSG_RESERVED_LIST");
2110 for (it = dict_first(opserv_reserved_nick_dict); it; it = iter_next(it))
2111 send_message_type(4, user, cmd->parent->bot, "%s", iter_key(it));
2112 return 1;
2113 }
2114
2115 static MODCMD_FUNC(cmd_stats_trusted) {
2116 dict_iterator_t it;
2117 struct trusted_host *th;
2118 char length[INTERVALLEN], issued[INTERVALLEN], limit[32];
2119
2120 reply("OSMSG_TRUSTED_LIST");
2121 reply("OSMSG_TRUSTED_LIST_BAR");
2122 reply("OSMSG_TRUSTED_LIST_HEADER");
2123 reply("OSMSG_TRUSTED_LIST_BAR");
2124 if (argc > 1) {
2125 th = dict_find(opserv_trusted_hosts, argv[1], NULL);
2126 if (th) {
2127 if (th->issued)
2128 intervalString(issued, now - th->issued, user->handle_info);
2129 if (th->expires)
2130 intervalString(length, th->expires - now, user->handle_info);
2131 if (th->limit)
2132 sprintf(limit, "%lu", th->limit);
2133 reply("OSMSG_HOST_IS_TRUSTED",
2134 th->ipaddr,
2135 (th->limit ? limit : "none"),
2136 (th->issuer ? th->issuer : "<unknown>"),
2137 (th->issued ? issued : "some time"),
2138 (th->expires ? length : "never"));
2139 reply("OSMSG_HOST_IS_TRUSTED_DESC", (th->reason ? th->reason : "<unknown>"));
2140 } else {
2141 reply("OSMSG_HOST_NOT_TRUSTED", argv[1]);
2142 }
2143 } else {
2144 for (it = dict_first(opserv_trusted_hosts); it; it = iter_next(it)) {
2145 th = iter_data(it);
2146 if (th->issued)
2147 intervalString(issued, now - th->issued, user->handle_info);
2148 if (th->expires)
2149 intervalString(length, th->expires - now, user->handle_info);
2150 if (th->limit)
2151 sprintf(limit, "%lu", th->limit);
2152 reply("OSMSG_HOST_IS_TRUSTED", iter_key(it),
2153 (th->limit ? limit : "none"),
2154 (th->issuer ? th->issuer : "<unknown>"),
2155 (th->issued ? issued : "some time"),
2156 (th->expires ? length : "never"));
2157 reply("OSMSG_HOST_IS_TRUSTED_DESC", (th->reason ? th->reason : "<unknown>"));
2158 }
2159 }
2160 reply("OSMSG_TRUSTED_LIST_END");
2161 return 1;
2162 }
2163
2164 static MODCMD_FUNC(cmd_stats_uplink) {
2165 extern struct cManagerNode cManager;
2166 struct uplinkNode *uplink;
2167
2168 uplink = cManager.uplink;
2169 reply("OSMSG_UPLINK_START", uplink->name);
2170 reply("OSMSG_UPLINK_ADDRESS", uplink->host, uplink->port);
2171 return 1;
2172 }
2173
2174 static MODCMD_FUNC(cmd_stats_uptime) {
2175 char uptime[INTERVALLEN];
2176 struct tms buf;
2177 extern time_t boot_time;
2178 extern int lines_processed;
2179 static long clocks_per_sec;
2180
2181 if (!clocks_per_sec) {
2182 #if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
2183 clocks_per_sec = sysconf(_SC_CLK_TCK);
2184 if (clocks_per_sec <= 0)
2185 #endif
2186 {
2187 log_module(OS_LOG, LOG_ERROR, "Unable to query sysconf(_SC_CLK_TCK), output of 'stats uptime' will be wrong");
2188 clocks_per_sec = CLOCKS_PER_SEC;
2189 }
2190 }
2191 intervalString(uptime, time(NULL)-boot_time, user->handle_info);
2192 times(&buf);
2193 reply("OSMSG_UPTIME_STATS",
2194 uptime, lines_processed,
2195 buf.tms_utime/(double)clocks_per_sec,
2196 buf.tms_stime/(double)clocks_per_sec);
2197 return 1;
2198 }
2199
2200 static MODCMD_FUNC(cmd_stats_alerts) {
2201 dict_iterator_t it;
2202 struct opserv_user_alert *alert;
2203 const char *reaction;
2204
2205 reply("OSMSG_ALERTS_LIST");
2206 reply("OSMSG_ALERTS_BAR");
2207 reply("OSMSG_ALERTS_HEADER");
2208 reply("OSMSG_ALERTS_BAR");
2209 for (it = dict_first(opserv_user_alerts); it; it = iter_next(it)) {
2210 alert = iter_data(it);
2211 switch (alert->reaction) {
2212 case REACT_NOTICE: reaction = "notice"; break;
2213 case REACT_KILL: reaction = "kill"; break;
2214 // case REACT_SILENT: reaction = "silent"; break;
2215 case REACT_GLINE: reaction = "gline"; break;
2216 case REACT_TRACK: reaction = "track"; break;
2217 case REACT_SHUN: reaction = "shun"; break;
2218 default: reaction = "<unknown>"; break;
2219 }
2220 reply("OSMSG_ALERT_IS", iter_key(it), reaction, alert->owner);
2221 reply("OSMSG_ALERTS_DESC", alert->text_discrim);
2222 }
2223 reply("OSMSG_ALERT_END");
2224 return 1;
2225 }
2226
2227 static MODCMD_FUNC(cmd_stats_gags) {
2228 struct gag_entry *gag;
2229 struct helpfile_table table;
2230 unsigned int nn;
2231
2232 if (!gagList) {
2233 reply("OSMSG_NO_GAGS");
2234 return 1;
2235 }
2236 for (nn=0, gag=gagList; gag; nn++, gag=gag->next) ;
2237 table.length = nn+1;
2238 table.width = 4;
2239 table.flags = TABLE_NO_FREE;
2240 table.contents = calloc(table.length, sizeof(char**));
2241 table.contents[0] = calloc(table.width, sizeof(char*));
2242 table.contents[0][0] = "Mask";
2243 table.contents[0][1] = "Owner";
2244 table.contents[0][2] = "Expires";
2245 table.contents[0][3] = "Reason";
2246 for (nn=1, gag=gagList; gag; nn++, gag=gag->next) {
2247 char expstr[INTERVALLEN];
2248 if (gag->expires)
2249 intervalString(expstr, gag->expires - now, user->handle_info);
2250 else
2251 strcpy(expstr, "Never");
2252 table.contents[nn] = calloc(table.width, sizeof(char*));
2253 table.contents[nn][0] = gag->mask;
2254 table.contents[nn][1] = gag->owner;
2255 table.contents[nn][2] = strdup(expstr);
2256 table.contents[nn][3] = gag->reason;
2257 }
2258 table_send(cmd->parent->bot, user->nick, 0, NULL, table);
2259 for (nn=1; nn<table.length; nn++) {
2260 free((char*)table.contents[nn][2]);
2261 free(table.contents[nn]);
2262 }
2263 free(table.contents[0]);
2264 free(table.contents);
2265 return 1;
2266 }
2267
2268 static MODCMD_FUNC(cmd_stats_timeq) {
2269 reply("OSMSG_TIMEQ_INFO", timeq_size(), timeq_next()-now);
2270 return 1;
2271 }
2272
2273 /*
2274 static MODCMD_FUNC(cmd_stats_warn) {
2275 dict_iterator_t it;
2276
2277 reply("OSMSG_WARN_LISTSTART");
2278 for (it=dict_first(opserv_chan_warn); it; it=iter_next(it))
2279 reply("OSMSG_WARN_LISTENTRY", iter_key(it), (char*)iter_data(it));
2280 reply("OSMSG_WARN_LISTEND");
2281 return 1;
2282 }
2283 */
2284
2285 #if defined(WITH_MALLOC_X3)
2286 static MODCMD_FUNC(cmd_stats_memory) {
2287 extern unsigned long alloc_count, alloc_size;
2288 send_message_type(MSG_TYPE_NOXLATE, user, cmd->parent->bot,
2289 "%u allocations totalling %u bytes.",
2290 alloc_count, alloc_size);
2291 return 1;
2292 }
2293 #elif defined(WITH_MALLOC_SLAB)
2294 static MODCMD_FUNC(cmd_stats_memory) {
2295 extern unsigned long slab_alloc_count, slab_count, slab_alloc_size;
2296 extern unsigned long big_alloc_count, big_alloc_size;
2297 send_message_type(MSG_TYPE_NOXLATE, user, cmd->parent->bot,
2298 "%u allocations in %u slabs totalling %u bytes.",
2299 slab_alloc_count, slab_count, slab_alloc_size);
2300 send_message_type(MSG_TYPE_NOXLATE, user, cmd->parent->bot,
2301 "%u big allocations totalling %u bytes.",
2302 big_alloc_count, big_alloc_size);
2303 return 1;
2304 }
2305 #endif
2306
2307 static MODCMD_FUNC(cmd_dump)
2308 {
2309 char linedup[MAXLEN], original[MAXLEN];
2310
2311 unsplit_string(argv+1, argc-1, original);
2312 safestrncpy(linedup, original, sizeof(linedup));
2313 /* assume it's only valid IRC if we can parse it */
2314 if (parse_line(linedup, 1)) {
2315 irc_raw(original);
2316 reply("OSMSG_LINE_DUMPED");
2317 } else
2318 reply("OSMSG_RAW_PARSE_ERROR");
2319 return 1;
2320 }
2321
2322 static MODCMD_FUNC(cmd_raw)
2323 {
2324 char linedup[MAXLEN], original[MAXLEN];
2325
2326 unsplit_string(argv+1, argc-1, original);
2327 safestrncpy(linedup, original, sizeof(linedup));
2328 /* Try to parse the line before sending it; if it's too wrong,
2329 * maybe it will core us instead of our uplink. */
2330 parse_line(linedup, 1);
2331 irc_raw(original);
2332 reply("OSMSG_LINE_DUMPED");
2333 return 1;
2334 }
2335
2336 static struct userNode *
2337 opserv_add_reserve(struct svccmd *cmd, struct userNode *user, const char *nick, const char *ident, const char *host, const char *desc)
2338 {
2339 struct userNode *resv = GetUserH(nick);
2340 if (resv) {
2341 if (IsService(resv)) {
2342 reply("MSG_SERVICE_IMMUNE", resv->nick);
2343 return NULL;
2344 }
2345 if (resv->handle_info
2346 && resv->handle_info->opserv_level > user->handle_info->opserv_level) {
2347 reply("OSMSG_LEVEL_TOO_LOW");
2348 return NULL;
2349 }
2350 }
2351 if ((resv = AddClone(nick, ident, host, desc))) {
2352 dict_insert(opserv_reserved_nick_dict, resv->nick, resv);
2353 }
2354 return resv;
2355 }
2356
2357 static MODCMD_FUNC(cmd_collide)
2358 {
2359 struct userNode *resv;
2360
2361 resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
2362 if (resv) {
2363 reply("OSMSG_COLLIDED_NICK", resv->nick);
2364 return 1;
2365 } else {
2366 reply("OSMSG_CLONE_FAILED", argv[1]);
2367 return 0;
2368 }
2369 }
2370
2371 static MODCMD_FUNC(cmd_reserve)
2372 {
2373 struct userNode *resv;
2374
2375 resv = opserv_add_reserve(cmd, user, argv[1], argv[2], argv[3], unsplit_string(argv+4, argc-4, NULL));
2376 if (resv) {
2377 resv->modes |= FLAGS_PERSISTENT;
2378 reply("OSMSG_RESERVED_NICK", resv->nick);
2379 return 1;
2380 } else {
2381 reply("OSMSG_CLONE_FAILED", argv[1]);
2382 return 0;
2383 }
2384 }
2385
2386 static int
2387 free_reserve(char *nick)
2388 {
2389 struct userNode *resv;
2390 unsigned int rlen;
2391 char *reason;
2392
2393 resv = dict_find(opserv_reserved_nick_dict, nick, NULL);
2394 if (!resv)
2395 return 0;
2396
2397 rlen = strlen(resv->nick)+strlen(OSMSG_PART_REASON);
2398 reason = alloca(rlen);
2399 snprintf(reason, rlen, OSMSG_PART_REASON, resv->nick);
2400 DelUser(resv, NULL, 1, reason);
2401 dict_remove(opserv_reserved_nick_dict, nick);
2402 return 1;
2403 }
2404
2405 static MODCMD_FUNC(cmd_unreserve)
2406 {
2407 if (free_reserve(argv[1]))
2408 reply("OSMSG_NICK_UNRESERVED", argv[1]);
2409 else
2410 reply("OSMSG_NOT_RESERVED", argv[1]);
2411 return 1;
2412 }
2413
2414 static void
2415 opserv_part_channel(void *data)
2416 {
2417 DelChannelUser(opserv, data, "Leaving.", 0);
2418 }
2419
2420 static int alert_check_user(const char *key, void *data, void *extra);
2421
2422 static int
2423 opserv_new_user_check(struct userNode *user)
2424 {
2425 struct opserv_hostinfo *ohi;
2426 struct gag_entry *gag;
2427 char addr[IRC_NTOP_MAX_SIZE];
2428
2429 /* Check to see if we should ignore them entirely. */
2430 if (IsLocal(user) || IsService(user))
2431 return 0;
2432
2433 /* Check for alerts, and stop if we find one that kills them. */
2434 if (dict_foreach(opserv_user_alerts, alert_check_user, user))
2435 return 1;
2436
2437 /* Gag them if appropriate. */
2438 for (gag = gagList; gag; gag = gag->next) {
2439 if (user_matches_glob(user, gag->mask, MATCH_USENICK)) {
2440 gag_helper_func(user, NULL);
2441 break;
2442 }
2443 }
2444
2445 /* Add to host info struct */
2446 irc_ntop(addr, sizeof(addr), &user->ip);
2447 if (!(ohi = dict_find(opserv_hostinfo_dict, addr, NULL))) {
2448 ohi = calloc(1, sizeof(*ohi));
2449 dict_insert(opserv_hostinfo_dict, strdup(addr), ohi);
2450 userList_init(&ohi->clients);
2451 }
2452 userList_append(&ohi->clients, user);
2453
2454 /* Only warn of new user floods outside of bursts. */
2455 if (!user->uplink->burst) {
2456 if (!policer_conforms(&opserv_conf.new_user_policer, now, 10)) {
2457 if (!new_user_flood) {
2458 new_user_flood = 1;
2459 opserv_alert("Warning: Possible new-user flood.");
2460 }
2461 } else {
2462 new_user_flood = 0;
2463 }
2464 }
2465
2466 if (checkDefCon(DEFCON_NO_NEW_CLIENTS)) {
2467 irc_kill(opserv, user, DefConGlineReason);
2468 return 0;
2469 }
2470
2471 if ( (checkDefCon(DEFCON_GLINE_NEW_CLIENTS) || checkDefCon(DEFCON_SHUN_NEW_CLIENTS)) && !IsOper(user)) {
2472 char target[IRC_NTOP_MAX_SIZE + 3] = { '*', '@', '\0' };
2473
2474 strcpy(target + 2, user->hostname);
2475 if (checkDefCon(DEFCON_GLINE_NEW_CLIENTS))
2476 gline_add(opserv->nick, target, DefConGlineExpire, DefConGlineReason, now, 1, 0);
2477 else if (checkDefCon(DEFCON_SHUN_NEW_CLIENTS))
2478 shun_add(opserv->nick, target, DefConGlineExpire, DefConGlineReason, now, 1);
2479
2480 return 0;
2481 }
2482
2483 /* Only warn or G-line if there's an untrusted max and their IP is sane. */
2484 if (opserv_conf.untrusted_max
2485 && irc_in_addr_is_valid(user->ip)
2486 && !irc_in_addr_is_loopback(user->ip)) {
2487 struct trusted_host *th = dict_find(opserv_trusted_hosts, addr, NULL);
2488 unsigned int limit = th ? th->limit : opserv_conf.untrusted_max;
2489
2490 if (checkDefCon(DEFCON_REDUCE_SESSION) && !th)
2491 limit = DefConSessionLimit;
2492
2493 if (!limit) {
2494 /* 0 means unlimited hosts */
2495 } else if (ohi->clients.used == limit) {
2496 unsigned int nn;
2497 for (nn=0; nn<ohi->clients.used; nn++)
2498 send_message(ohi->clients.list[nn], opserv, "OSMSG_CLONE_WARNING");
2499 } else if (ohi->clients.used > limit) {
2500 char target[IRC_NTOP_MAX_SIZE + 3] = { '*', '@', '\0' };
2501 strcpy(target + 2, addr);
2502 gline_add(opserv->nick, target, opserv_conf.clone_gline_duration, "Excessive connections from a single host.", now, 1, 1);
2503 }
2504 }
2505
2506 return 0;
2507 }
2508
2509 static void
2510 opserv_user_cleanup(struct userNode *user, UNUSED_ARG(struct userNode *killer), UNUSED_ARG(const char *why))
2511 {
2512 struct opserv_hostinfo *ohi;
2513 char addr[IRC_NTOP_MAX_SIZE];
2514
2515 if (IsLocal(user)) {
2516 /* Try to remove it from the reserved nick dict without
2517 * calling free_reserve, because that would call DelUser(),
2518 * and we'd loop back to here. */
2519 dict_remove(opserv_reserved_nick_dict, user->nick);
2520 return;
2521 }
2522 irc_ntop(addr, sizeof(addr), &user->ip);
2523 if ((ohi = dict_find(opserv_hostinfo_dict, addr, NULL))) {
2524 userList_remove(&ohi->clients, user);
2525 if (ohi->clients.used == 0)
2526 dict_remove(opserv_hostinfo_dict, addr);
2527 }
2528 }
2529
2530 int
2531 opserv_bad_channel(const char *name)
2532 {
2533 unsigned int found;
2534 int present;
2535
2536 dict_find(opserv_exempt_channels, name, &present);
2537 if (present)
2538 return 0;
2539
2540 if (gline_find(name))
2541 return 1;
2542
2543 for (found=0; found<opserv_bad_words->used; ++found)
2544 if (irccasestr(name, opserv_bad_words->list[found]))
2545 return 1;
2546
2547 return 0;
2548 }
2549
2550 static void
2551 opserv_shutdown_channel(struct chanNode *channel, const char *reason)
2552 {
2553 struct mod_chanmode *change;
2554 unsigned int nn;
2555
2556 change = mod_chanmode_alloc(2);
2557 change->modes_set = MODE_SECRET | MODE_INVITEONLY;
2558 change->args[0].mode = MODE_CHANOP;
2559 change->args[0].u.member = AddChannelUser(opserv, channel);
2560 change->args[1].mode = MODE_BAN;
2561 change->args[1].u.hostmask = "*!*@*";
2562 mod_chanmode_announce(opserv, channel, change);
2563 mod_chanmode_free(change);
2564 for (nn=channel->members.used; nn>0; ) {
2565 struct modeNode *mNode = channel->members.list[--nn];
2566 if (IsService(mNode->user))
2567 continue;
2568 KickChannelUser(mNode->user, channel, opserv, user_find_message(mNode->user, reason));
2569 }
2570 timeq_add(now + opserv_conf.purge_lock_delay, opserv_part_channel, channel);
2571 }
2572
2573 static void
2574 opserv_channel_check(struct chanNode *newchan)
2575 {
2576 /*char *warning; */
2577
2578 if (!newchan->join_policer.params) {
2579 newchan->join_policer.last_req = now;
2580 newchan->join_policer.params = opserv_conf.join_policer_params;
2581 }
2582 /*
2583 if ((warning = dict_find(opserv_chan_warn, newchan->name, NULL))) {
2584 global_message_args(MESSAGE_RECIPIENT_OPERS, "OSMSG_CHANNEL_ACTIVITY_WARN", newchan->name, warning);
2585 }
2586 */
2587
2588 /* Wait until the join check to shut channels down. */
2589 newchan->bad_channel = opserv_bad_channel(newchan->name);
2590 }
2591
2592 static void
2593 opserv_channel_delete(struct chanNode *chan)
2594 {
2595 timeq_del(0, opserv_part_channel, chan, TIMEQ_IGNORE_WHEN);
2596 }
2597
2598 static int
2599 opserv_join_check(struct modeNode *mNode)
2600 {
2601 struct userNode *user = mNode->user;
2602 struct chanNode *channel = mNode->channel;
2603 const char *msg;
2604
2605 if (IsService(user))
2606 return 0;
2607
2608 dict_foreach(opserv_channel_alerts, alert_check_user, user);
2609
2610 if (channel->bad_channel) {
2611 opserv_debug("Found $b%s$b in bad-word channel $b%s$b; removing the user.", user->nick, channel->name);
2612 if (channel->name[0] != '#')
2613 DelUser(user, opserv, 1, "OSMSG_ILLEGAL_KILL_REASON");
2614 else if (!GetUserMode(channel, opserv))
2615 opserv_shutdown_channel(channel, "OSMSG_ILLEGAL_REASON");
2616 else {
2617 send_message(user, opserv, "OSMSG_ILLEGAL_CHANNEL", channel->name);
2618 msg = user_find_message(user, "OSMSG_ILLEGAL_REASON");
2619 KickChannelUser(user, channel, opserv, msg);
2620 }
2621 return 1;
2622 }
2623
2624 if (user->uplink->burst)
2625 return 0;
2626 if (policer_conforms(&channel->join_policer, now, 1.0)) {
2627 channel->join_flooded = 0;
2628 return 0;
2629 }
2630 if (!channel->join_flooded) {
2631 /* Don't moderate the channel unless it is activated and
2632 the number of users in the channel is over the threshold. */
2633 struct mod_chanmode change;
2634 mod_chanmode_init(&change);
2635 channel->join_flooded = 1;
2636 if (opserv_conf.join_flood_moderate && (channel->members.used > opserv_conf.join_flood_moderate_threshold)) {
2637 if (!GetUserMode(channel, opserv)) {
2638 /* If we aren't in the channel, join it. */
2639 change.args[0].mode = MODE_CHANOP;
2640 change.args[0].u.member = AddChannelUser(opserv, channel);
2641 change.argc++;
2642 }
2643 if (!(channel->modes & MODE_MODERATED))
2644 change.modes_set |= MODE_MODERATED;
2645 if (change.modes_set || change.argc)
2646 mod_chanmode_announce(opserv, channel, &change);
2647 send_target_message(0, channel->name, opserv, "OSMSG_FLOOD_MODERATE");
2648 opserv_alert("Warning: Possible join flood in %s (currently %d users; channel moderated).", channel->name, channel->members.used);
2649 } else {
2650 opserv_alert("Warning: Possible join flood in %s (currently %d users).", channel->name, channel->members.used);
2651 }
2652 }
2653 log_module(OS_LOG, LOG_INFO, "Join to %s during flood: "IDENT_FORMAT, channel->name, IDENT_DATA(user));
2654 return 0;
2655 }
2656
2657 static int
2658 opserv_add_bad_word(struct svccmd *cmd, struct userNode *user, const char *new_bad) {
2659 unsigned int bad_idx;
2660
2661 for (bad_idx = 0; bad_idx < opserv_bad_words->used; ++bad_idx) {
2662 char *orig_bad = opserv_bad_words->list[bad_idx];
2663 if (irccasestr(new_bad, orig_bad)) {
2664 if (user)
2665 reply("OSMSG_BAD_REDUNDANT", new_bad, orig_bad);
2666 return 0;
2667 } else if (irccasestr(orig_bad, new_bad)) {
2668 if (user)
2669 reply("OSMSG_BAD_GROWING", orig_bad, new_bad);
2670 free(orig_bad);
2671 opserv_bad_words->list[bad_idx] = strdup(new_bad);
2672 for (bad_idx++; bad_idx < opserv_bad_words->used; bad_idx++) {
2673 orig_bad = opserv_bad_words->list[bad_idx];
2674 if (!irccasestr(orig_bad, new_bad))
2675 continue;
2676 if (user)
2677 reply("OSMSG_BAD_NUKING", orig_bad);
2678 string_list_delete(opserv_bad_words, bad_idx);
2679 bad_idx--;
2680 free(orig_bad);
2681 }
2682 return 1;
2683 }
2684 }
2685 string_list_append(opserv_bad_words, strdup(new_bad));
2686 if (user)
2687 reply("OSMSG_ADDED_BAD", new_bad);
2688 return 1;
2689 }
2690
2691 static int
2692 opserv_routing_plan_add_server(struct routingPlan *rp, const char *name, const char *uplink, const unsigned int port, int karma, const char *second, const unsigned int offline)
2693 {
2694 struct routingPlanServer *rps;
2695 rps = calloc(1, sizeof(*rps));
2696 if(!rps)
2697 return 0;
2698 /* duplicate servers replace */
2699 rps->uplink = strdup(uplink);
2700 if(second)
2701 rps->secondaryuplink = strdup(second);
2702 else
2703 rps->secondaryuplink = NULL;
2704 rps->port = port ? port : 4400; /* lame hardcodede default port. maybe get from config file somewhere? */
2705 rps->karma = karma;
2706 rps->offline = offline; /* 1 = yes, 0 = no */
2707 dict_insert(rp->servers, strdup(name), rps);
2708 log_module(OS_LOG, LOG_DEBUG, "Adding rp server %s with uplink %s", name, uplink);
2709 return 1;
2710 }
2711
2712 static void
2713 free_routing_plan_server(void *data)
2714 {
2715 struct routingPlanServer *rps = data;
2716 free(rps->uplink);
2717 if(rps->secondaryuplink)
2718 free(rps->secondaryuplink);
2719 free(rps);
2720 }
2721
2722 struct routingPlan*
2723 opserv_add_routing_plan(const char *name)
2724 {
2725 struct routingPlan *rp;
2726 rp = calloc(1, sizeof(*rp));
2727 if (!rp)
2728 return NULL;
2729 if(dict_find(opserv_routing_plans, name, NULL))
2730 return NULL; /* plan already exists */
2731 rp->servers = dict_new();
2732 dict_set_free_data(rp->servers, free_routing_plan_server);
2733
2734 dict_insert(opserv_routing_plans, strdup(name), rp);
2735 /* TODO: check for duplicate */
2736 return rp;
2737 }
2738
2739 static void
2740 free_routing_plan(void *data)
2741 {
2742 struct routingPlan *rp = data;
2743 /* delete all the servers attached to this plan */
2744 dict_delete(rp->servers);
2745 /* free the plan struct */
2746 free(rp);
2747 }
2748
2749 /*************************************************
2750 * Functions to handle the active routing struct */
2751
2752 struct routeList
2753 *find_routeList_server(struct route *route, const char *server)
2754 {
2755 struct routeList *rptr;
2756 if(!server)
2757 return(NULL);
2758 for(rptr = route->servers;rptr;rptr=rptr->next) {
2759 if(!strcasecmp(rptr->server, server))
2760 return(rptr);
2761 }
2762 return(NULL);
2763 }
2764
2765 /* Wipes out the routing structure, freeing properly.
2766 * note: does NOT free itself, we just re-use it usually.*/
2767 void
2768 wipe_route_list(struct route *route) {
2769 struct routeList *nextptr, *rptr;
2770 if(!route)
2771 return;
2772 for(rptr = opserv_route->servers; rptr; rptr=nextptr)
2773 {
2774 nextptr = rptr->next;
2775 free(rptr->server);
2776 if(rptr->uplink)
2777 free(rptr->uplink);
2778 if(rptr->secondaryuplink)
2779 free(rptr->secondaryuplink);
2780 free(rptr);
2781 }
2782 route->centered = true;
2783 route->count = 0;
2784 route->maxdepth = 0;
2785 route->servers = NULL;
2786 }
2787
2788
2789 int
2790 rank_outside_rec(struct route *route, char *server, int count)
2791 {
2792 struct routeList *rptr;
2793 int n, max = 0;
2794 int i = 0;
2795 if(count > 256) { /* XXX: 256 becomes max # of servers this works with, whats the real #? */
2796 return -1;
2797 }
2798 for(rptr = route->servers; rptr; rptr = rptr->next) {
2799 i++;
2800 if(!strcasecmp(server, rptr->uplink)) {
2801 log_module(MAIN_LOG, LOG_DEBUG, "%d:%d: rank_outside_rec(%s) calling rank_outside_rec(%s)", count, i, rptr->server, rptr->uplink);
2802 n = rank_outside_rec(route, rptr->server, count +1);
2803 if(n < 0) /* handle error condition */
2804 return n;
2805 if(n > max)
2806 max = n;
2807 }
2808 }
2809 if((rptr = find_routeList_server(route, server))) {
2810 rptr->outsideness = max;
2811 return(max + 1);
2812 }
2813 else {
2814 log_module(MAIN_LOG, LOG_ERROR, "routing struct rank_outsideness() couldnt find %s", server);
2815 return 0;
2816 }
2817 }
2818
2819 int
2820 rank_outsideness(struct route *route)
2821 {
2822 log_module(MAIN_LOG, LOG_DEBUG, "rank_outsideness(): Running...");
2823 route->maxdepth = rank_outside_rec(route, self->uplink->name, 0) - 1;
2824 if(route->maxdepth < 0) { /* if the rank failed, remove route */
2825 log_module(MAIN_LOG, LOG_WARNING, "The active routing plan has a loop! auto routing disabled.");
2826 wipe_route_list(route);
2827 return false;
2828 }
2829 return true;
2830 }
2831
2832
2833 /* Add servers to the routing structure */
2834 void
2835 add_routestruct_server(struct route *route, const char *server, unsigned int port, char *uplink, char *secondary)
2836 {
2837 struct routeList *rptr;
2838 char *hname;
2839 if(find_routeList_server(route, server))
2840 {
2841 log_module(MAIN_LOG, LOG_WARNING, "Routing structure add server Skipping duplicate [%s]. This should never really be possible.", server);
2842 return;
2843 }
2844 rptr = calloc(1, sizeof(*rptr));
2845 rptr->server = strdup(server);
2846 rptr->port = port;
2847 if(!uplink) {
2848 hname = conf_get_data("server/hostname", RECDB_QSTRING);
2849 uplink = hname;
2850 }
2851 rptr->uplink = strdup(uplink);
2852 if(secondary)
2853 rptr->secondaryuplink = strdup(secondary);
2854 /* tack this server on the front of the list */
2855 rptr->next = route->servers;
2856 route->servers = rptr;
2857 route->count++;
2858
2859 #ifdef notdef /* I dont quite get this. there could be uncentered things
2860 * added after our own uplink, and this function doesnt center
2861 * as it adds. -Rubin */
2862 /* If the map hasnt been centered yet... */
2863 if(route->centered == false) {
2864 /* AND we just added our own uplink to it... */
2865 if(!strcasecmp(server, self->uplink->name)) {
2866 change_route_uplinks(route); /* recenter it, n mark it centered. */
2867 }
2868 }
2869 #endif
2870 }
2871
2872 /* Recenter the routing struct around our current uplink */
2873 int
2874 change_route_uplinks(struct route *route)
2875 {
2876 struct routeList *rptr;
2877 char lastserver[MAXLEN];
2878 char nextserver[MAXLEN];
2879
2880 if(!route->servers)
2881 return false; /* no map to recenter */
2882 log_module(MAIN_LOG, LOG_DEBUG, "change_route_uplinks(): running...");
2883 char *servicename = conf_get_data("server/hostname", RECDB_QSTRING);
2884 strcpy(lastserver, servicename);
2885 rptr = find_routeList_server(route, self->uplink->name);
2886 if(!rptr) {
2887 log_module(MAIN_LOG, LOG_ERROR, "Cannot convert routing map to center: My uplink is not on the map! Marking map as uncentered.");
2888 route->centered = false;
2889 return false;
2890 }
2891 if(!strcasecmp(rptr->uplink, servicename)) {
2892 log_module(MAIN_LOG, LOG_DEBUG, "Already centered");
2893 }
2894 else { /* else, center it */
2895 while(rptr) {
2896 strcpy(nextserver, rptr->uplink);
2897 log_module(MAIN_LOG, LOG_DEBUG, "change_route_uplinks() changing %s uplink to %s.", rptr->server, lastserver);
2898 free(rptr->uplink);
2899 rptr->uplink = strdup(lastserver);
2900 strcpy(lastserver, rptr->server);
2901 rptr = find_routeList_server(route, nextserver);
2902 }
2903 }
2904 if(rank_outsideness(route) > 0) {
2905 route->centered = true;
2906 return true;
2907 }
2908 else
2909 return false;
2910 }
2911
2912 int
2913 activate_routing(struct svccmd *cmd, struct userNode *user, char *plan_name)
2914 {
2915 static struct routingPlan *rp;
2916 dict_iterator_t it;
2917 char *karma;
2918
2919 if(plan_name) { /* make this the new active plan */
2920 if(!strcmp(plan_name, "*")) {
2921 /* disable routing */
2922 dict_remove(opserv_routing_plan_options, "ACTIVE");
2923 plan_name = NULL;
2924 }
2925 else {
2926 rp = dict_find(opserv_routing_plans, plan_name, NULL);
2927 if(!rp) {
2928 if(cmd && user)
2929 reply("OSMSG_PLAN_NOT_FOUND", plan_name);
2930 else {
2931 /* since it doesnt exist, remove the active setting */
2932 dict_remove(opserv_routing_plan_options, plan_name);
2933 }
2934 log_module(MAIN_LOG, LOG_ERROR, "activate_routing() couldnt find active routing plan!");
2935 return 0;
2936 }
2937 }
2938 }
2939 else { /* find the active plan in settings */
2940 plan_name = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
2941 }
2942 if(!plan_name) { /* deactivated, or no plan was set active */
2943 /* TODO: delete routing map if it exists */
2944 wipe_route_list(opserv_route);
2945 return 1;
2946 }
2947
2948 karma = dict_find(opserv_routing_plan_options, "KARMA", NULL);
2949
2950 rp = dict_find(opserv_routing_plans, plan_name, NULL);
2951
2952 /* this should really be done during opserv init */
2953 if(!opserv_route)
2954 opserv_route = calloc(1, sizeof(*opserv_route));
2955
2956 /* Delete the existing active route */
2957 wipe_route_list(opserv_route);
2958
2959 for(it = dict_first(rp->servers); it; it = iter_next(it)) {
2960 const char* servername = iter_key(it);
2961 struct routingPlanServer *rps = iter_data(it),
2962 *rp_uplink, *rp_second = NULL;
2963 char *uplink = rps->uplink;
2964 rp_uplink = dict_find(rp->servers, rps->uplink, NULL);
2965 if(rps->secondaryuplink)
2966 rp_second = dict_find(rp->servers, rps->secondaryuplink, NULL);
2967
2968 /* If the normal uplink has bad karma, don't use it as a hub,
2969 * switch to the secondary uplink.
2970 */
2971 if(karma && enabled_string(karma) && rp_uplink && rp_uplink->karma < 0) {
2972 if(rps->secondaryuplink) {
2973 uplink = rps->secondaryuplink;
2974 /* unless the secondary uplinks karma is worse than the uplink. */
2975 if((rp_second = dict_find(rp->servers, uplink, NULL)) && rp_second->karma < rp_uplink->karma)
2976 uplink = rps->uplink;
2977 }
2978 }
2979 /*
2980 * If _WE_ have bad karma, don't link us to our normal uplink, maybe
2981 * its a bad route. switch to secondary. Important: dont neg karma when we arnt on
2982 * our primary uplink, or we'll get stuck on secondary when THAT link is worse.
2983 */
2984 if(karma && enabled_string(karma) && (rps->karma < 0 || rps->offline) ) {
2985 if(rps->secondaryuplink) {
2986 uplink = rps->secondaryuplink;
2987 }
2988 }
2989 log_module(MAIN_LOG, LOG_DEBUG, "activate_routing() adding %s:%d %s", servername, rps->port, uplink);
2990 add_routestruct_server(opserv_route, servername, rps->port, uplink, NULL);
2991 }
2992 if(change_route_uplinks(opserv_route))
2993 return 1;
2994 else if(user) {
2995 reply("OSMSG_ROUTING_ACTIVATION_ERROR");
2996 activate_routing(cmd, user, "*");
2997 return 0;
2998 }
2999 return 1;
3000 }
3001
3002 /*******************************************************
3003 * Functions to handle online route configuration via opserv
3004 */
3005 static void route_show_option(struct svccmd *cmd, struct userNode *user, char *name)
3006 {
3007 char *value = dict_find(opserv_routing_plan_options, name, NULL);
3008 if(value) {
3009 if(!strcmp("RETRY_PERIOD", name)) { /* Show as an interval */
3010 char buff[INTERVALLEN+1];
3011 reply("OSMSG_ROUTINGPLAN_OPTION", name, intervalString(buff, atoi(value), user->handle_info));
3012 }
3013 else if(!strcmp("ACTIVE", name)) {
3014 if(opserv_route && opserv_route->servers)
3015 reply("OSMSG_ROUTINGPLAN_ACTIVE", value);
3016 else
3017 reply("OSMSG_ROUTINGPLAN_OPTION_NOT_SET", name);
3018 }
3019 else {
3020 reply("OSMSG_ROUTINGPLAN_OPTION", name, value);
3021 }
3022 }
3023 else {
3024 reply("OSMSG_ROUTINGPLAN_OPTION_NOT_SET", name);
3025 }
3026 }
3027
3028 static void route_show_options(struct svccmd *cmd, struct userNode *user)
3029 {
3030 char *options[] = {"ACTIVE", "RETRY_PERIOD", "CONN_PINGOUT", "CONN_READERROR", "KARMA", "DEFAULT_PORT", NULL};
3031 int i;
3032 for(i = 0; options[i]; i++) {
3033 route_show_option(cmd, user, options[i]);
3034 }
3035 }
3036
3037 /* called from timeq */
3038 void routing_connect_timeout(void *data)
3039 {
3040 struct waitingConnection *wc = data;
3041 struct server *target = GetServerH(wc->target);
3042 if(!target) {
3043 dict_remove(opserv_waiting_connections, wc->server);
3044 return; /* server we wanted to connect new server to is gone, just give up */
3045 }
3046 routing_handle_connect_failure(target, wc->server, "Connection timed out");
3047 /* the following invalidates server variable! */
3048 dict_remove(opserv_waiting_connections, wc->server);
3049 }
3050
3051 void routing_delete_connect_timer(char *server)
3052 {
3053 struct waitingConnection *wc = dict_find(opserv_waiting_connections, server, 0);
3054 if(wc) {
3055 timeq_del(0, routing_connect_timeout, wc, TIMEQ_IGNORE_WHEN);
3056 dict_remove(opserv_waiting_connections, server);
3057 }
3058 }
3059
3060
3061 void
3062 routing_connect_server(char *server, int port, struct server *to)
3063 {
3064 struct waitingConnection *wc = calloc(sizeof(*wc), 1);
3065
3066 wc->server = strdup(server);
3067 wc->target = strdup(to->name);
3068 /* Just to make sure there isn't one left hanging
3069 * if 2 connections are attempted at once..
3070 * */
3071 routing_delete_connect_timer(server);
3072 dict_insert(opserv_waiting_connections, strdup(server), wc);
3073 timeq_add(now + ROUTING_CONNECT_TIMEOUT, routing_connect_timeout, wc);
3074
3075 irc_connect(opserv, server, port, to);
3076 }
3077
3078 int
3079 routing_connect_one(struct route *route, char *server)
3080 {
3081 struct routeList *rptr;
3082 struct server *sptr, *suptr;
3083 for(rptr = route->servers; rptr; rptr = rptr->next) {
3084 if(!strcasecmp(rptr->server, server)) {
3085 /* this is the one, connect it */
3086 suptr = GetServerH(rptr->uplink);
3087 sptr = GetServerH(rptr->server);
3088 if(sptr)
3089 return 1; /* already linked */
3090 if(suptr) {
3091 routing_connect_server(rptr->server, rptr->port, suptr);
3092 return 1; /* attempted link */
3093 }
3094 return 0; /* its uplink isnt here to link to */
3095 }
3096 }
3097 log_module(MAIN_LOG, LOG_DEBUG, "Tried to link %s but its not in the active routing struct!", server);
3098 return 0; /* server wasnt found in active route struct. */
3099 }
3100
3101 int routing_connect_children(struct route *route, char *server)
3102 {
3103 struct routeList *rptr;
3104 struct server *sptr, *suptr;
3105 for(rptr = route->servers; rptr; rptr = rptr->next) {
3106 if(!strcasecmp(rptr->uplink, server)) {
3107 /* this is the one, connect it */
3108 suptr = GetServerH(rptr->uplink);
3109 sptr = GetServerH(rptr->server);
3110 if(sptr)
3111 continue; /* already linked */
3112 if(suptr) {
3113 routing_connect_server(rptr->server, rptr->port, suptr);
3114 continue; /* attempted link */
3115 }
3116 continue; /* its uplink isnt here to link to */
3117 }
3118 }
3119 return 1; /* server wasnt found in active route struct ?! */
3120 }
3121
3122 int reroute(struct route *route, struct userNode *user, struct svccmd *cmd, char *directive)
3123 {
3124 struct routeList *rptr;
3125 struct server *sptr, *suptr;
3126 int connect = 0, move = 0, missing = 0, i;
3127 char d = toupper(*directive);
3128
3129 if(!route || !route->servers) {
3130 reply("OSMSG_REROUTING_NOTCONFIGURED");
3131 return 0;
3132 }
3133 if(user) {
3134 if(d == 'N') { /* normal */
3135 irc_wallops("%s", "Attempting a reroute of the network according to loaded map...");
3136 reply("OSMSG_REROUTING_ACC_MAP");
3137 }
3138 else if(d == 'C') { /* only connect */
3139 reply("OSMSG_CONNECTING_MISSING_ONLY");
3140 }
3141 else if(d == 'T') { /* test */
3142 reply("OSMSG_TESTING_REROUTE");
3143 }
3144 else
3145 {
3146 reply("OSMSG_INVALID_DIRECTIVE", directive);
3147 return 0;
3148 }
3149 }
3150 for(i = 0; i <= route->maxdepth-1; i++) {
3151 for(rptr = route->servers; rptr; rptr = rptr->next) {
3152 if(rptr->outsideness == i) {
3153 /* debugging */
3154 if(user && d=='T')
3155 reply("OSMSG_INSPECTING_SERVER", rptr->server);
3156 suptr = GetServerH(rptr->uplink);
3157 if(!suptr) {
3158 if(rptr->secondaryuplink && (suptr = GetServerH(rptr->secondaryuplink))) {
3159 if(user)
3160 reply("OSMSG_COULDNT_FIND_SERVER", rptr->uplink, rptr->secondaryuplink, rptr->server);
3161 }
3162 }
3163 if(suptr) { /* if the proper uplink is connected.. */
3164 sptr = GetServerH(rptr->server);
3165 if(d == 'C' && sptr) {
3166 continue; /* Already linked */
3167 }
3168 /* If server is missing or the uplinks are not the same then... */
3169 else if(!sptr || strcasecmp(sptr->uplink->name, rptr->uplink)) {
3170 if(!sptr) {
3171 connect++;
3172 }
3173 else { /* Server is already connected somewhere */
3174 if(strcasecmp(sptr->uplink->name, rptr->uplink)) {
3175 if(d != 'T') { /* do it for real */
3176 irc_squit_route(sptr, "%s issued reroute.", user ? user->nick : opserv->nick);
3177 }
3178 else { /* just pretend */
3179 reply("OSMSG_SQUIT", rptr->server);
3180 }
3181 move++;
3182 }
3183 }
3184 if(d != 'T') /* do the real thing */
3185 routing_connect_server(rptr->server, rptr->port, suptr);
3186 else /* just pretend */
3187 reply("OSMSG_CONNECT", rptr->server, rptr->port, suptr->name);
3188 }
3189 }
3190 else {
3191 log_module(MAIN_LOG, LOG_DEBUG, "server uplink %s was not found, cant connect %s", rptr->uplink, rptr->server);
3192 missing++;
3193 }
3194 } /* outsideness = 1 */
3195 } /* rptr */
3196 } /* maxdepth */
3197 if(user) { /* report on what we did */
3198 if(!strcasecmp(directive, "C")) {
3199 if(connect > 0)
3200 reply("OSMSG_CONNECTING_MISSING", connect);
3201 else
3202 reply("OSMSG_NO_SERVERS_MISSING");
3203 }
3204 else {
3205 if(move+connect > 0)
3206 reply("OSMSG_REROUTE_COMPLETE", move, connect, move+connect);
3207 else
3208 reply("OSMSG_NO_ROUTING_NECESSARY");
3209 if(missing > 0)
3210 reply("OSMSG_UPLINKS_MISSING", missing);
3211 }
3212 }
3213 return(move+connect);
3214 }
3215
3216 static MODCMD_FUNC(cmd_reroute) {
3217 char* upper;
3218 upper = argv[1];
3219 if(reroute(opserv_route, user, cmd, upper))
3220 return 1;
3221 else
3222 return 0;
3223 }
3224
3225 /* reroute_timer(run)
3226 * run - if it is null, just setup the timer
3227 * but dont run reroute now. otherwise reroute
3228 * and setup timer.
3229 */
3230 void reroute_timer(void *data) {
3231 if(!opserv_route || !opserv_route->servers)
3232 return; /* no active route */
3233 char *retry_period = dict_find(opserv_routing_plan_options, "RETRY_PERIOD", NULL);
3234 if(!retry_period)
3235 return; /* retry_period invalid */
3236 unsigned int freq = atoi(retry_period);
3237 if(freq < 1)
3238 return; /* retry_period set to 0, disable */
3239
3240 /* Do the reroute C attempt */
3241 if(data)
3242 reroute(opserv_route, NULL, NULL, "C");
3243
3244 /* Re-add ourselves to the timer queue */
3245 timeq_add(now + freq, reroute_timer, "run");
3246 }
3247
3248 void routing_change_karma(struct routingPlanServer *rps, const char *server, int change) {
3249
3250 int oldkarma = rps->karma;
3251 rps->karma += change;
3252 if(rps->karma < KARMA_MIN)
3253 rps->karma = KARMA_MIN;
3254 if(rps->karma > KARMA_MAX)
3255 rps->karma = KARMA_MAX;
3256 log_module(MAIN_LOG, LOG_DEBUG, "Changing %s karma by %d. new karma %d.", server, change, rps->karma);
3257 if(oldkarma > 0 && rps->karma < 0) {
3258 /* we just crossed over to negitive */
3259 log_module(MAIN_LOG, LOG_INFO, "Server %s just went negitive karma!", server);
3260 activate_routing(NULL, NULL, NULL);
3261 }
3262 else if(oldkarma < 0 && rps->karma > 0) {
3263 /* we just crossed over to positive */
3264 log_module(MAIN_LOG, LOG_INFO, "Server %s just went back positive karma.", server);
3265 activate_routing(NULL, NULL, NULL);
3266 }
3267 }
3268
3269 void routing_karma_timer(void *data) {
3270 time_t next;
3271 time_t timer_init = data ? atoi(data) : 0;
3272 char buf[MAXLEN];
3273
3274 log_module(MAIN_LOG, LOG_DEBUG, "routing_karma_timer() is running. timer_init=%d.", (unsigned int) timer_init);
3275
3276 /* If theres a time passed in, dont run unless that time is overdue. */
3277 if(!timer_init || (timer_init < now)) {
3278 if(opserv_route && opserv_route->servers) {
3279 char *active = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
3280 struct routingPlan *rp;
3281 if(active && (rp = dict_find(opserv_routing_plans, active, NULL))) {
3282 dict_iterator_t it;
3283 /* Walk through each server in the active routing plan.. */
3284 for(it = dict_first(rp->servers); it; it = iter_next(it)) {
3285 struct routingPlanServer *rps = iter_data(it);
3286 struct server *server = GetServerH(iter_key(it));
3287 /* Give everyone +KARMA_ENTROPE just for nothing */
3288 routing_change_karma(rps, iter_key(it), KARMA_ENTROPE);
3289 /* give an additonal +KARMA_RELIABLE to servers that
3290 * have been linked at least KARMA_TIMER seconds. */
3291 if(server && (server->link < (now - KARMA_TIMER) ) ) {
3292 routing_change_karma(rps, iter_key(it), KARMA_RELIABLE);
3293 }
3294 }
3295 }
3296 }
3297 }
3298 if(timer_init > now) /* loading a saved value */
3299 next = timer_init;
3300 else /* no scheduled timer, or we missed it. start from now */
3301 next = now + KARMA_TIMER;
3302 /* Save when karma_timer should run again in case we restart before then */
3303 log_module(MAIN_LOG, LOG_DEBUG, "routing_karma_timer() scheduling self to run again at %d", (unsigned int) next);
3304 sprintf(buf, "%u", (unsigned int) next);
3305 dict_insert(opserv_routing_plan_options, "KARMA_TIMER", strdup(buf));
3306 /* add a timer to run this again .. */
3307 timeq_add(next, routing_karma_timer, NULL);
3308 }
3309
3310 void routing_handle_neg_karma(char *server, char *uplink, int change)
3311 {
3312 /* if server's primary uplink is uplink, OR, uplink's primary uplink is server,
3313 * then whichever one, gets its karma changed. */
3314 char *active = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
3315 struct routingPlan *rp;
3316 struct routingPlanServer *rps;
3317 if(!active)
3318 return;
3319 if(!(rp = dict_find(opserv_routing_plans, active, NULL)))
3320 return;
3321 if((rps = dict_find(rp->servers, server, NULL))) {
3322 if(!strcasecmp(rps->uplink, uplink)) {
3323 /* server's uplink is uplink */
3324 routing_change_karma(rps, server, change);
3325 return;
3326 }
3327 }
3328 if((rps = dict_find(rp->servers, uplink, NULL))) {
3329 if(!strcasecmp(rps->uplink, server)) {
3330 /* uplink's uplink is server */
3331 routing_change_karma(rps, uplink, change);
3332 return;
3333 }
3334 }
3335 }
3336
3337 void
3338 routing_handle_squit(char *server, char *uplink, char *message)
3339 {
3340 log_module(MAIN_LOG, LOG_DEBUG, "Routing_handle_squit(%s, %s)", server, message);
3341
3342 char *val;
3343
3344 if(match_ircglob(message, "Ping timeout")) {
3345 routing_handle_neg_karma(server, uplink, KARMA_PINGOUT);
3346 /* if conn_pingout is true, try to reconnect it obaying karma rules. */
3347
3348 val = dict_find(opserv_routing_plan_options, "CONN_PINGOUT", 0);
3349 if(val && enabled_string(val))
3350 routing_connect_one(opserv_route, server);
3351 }
3352 else if(match_ircglob(message, "Read error:*")) {
3353 routing_handle_neg_karma(server, uplink, KARMA_READERROR);
3354 /* if conn_readerror is true, try to reconnect it obaying karma rules. */
3355 val = dict_find(opserv_routing_plan_options, "CONN_READERROR", 0);
3356 if(val && enabled_string(val))
3357 routing_connect_one(opserv_route, server);
3358 }
3359 /* Else whats the message (an oper squit it?) dont interfere */
3360 }
3361
3362 void
3363 routing_handle_connect(char *server, char *uplink)
3364 {
3365 char *active;
3366 struct routingPlan *rp;
3367 struct routingPlanServer *rps;
3368 dict_iterator_t it;
3369
3370 log_module(MAIN_LOG, LOG_DEBUG, "routing_handle_connect(%s, %s)", server, uplink);
3371 /* delete a pending connection timer, if any */
3372 routing_delete_connect_timer(server);
3373 /* check if routing is active... */
3374 active = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
3375 if(!active)
3376 return;
3377 rp = dict_find(opserv_routing_plans, active, NULL);
3378 if(!rp)
3379 return;
3380
3381 /* If its offline, mark it online again.. */
3382 if((rps = dict_find(rp->servers, server, NULL))) {
3383 if(rps->offline == true) {
3384 rps->offline = false;
3385 if(rps->secondaryuplink) {
3386 /* re-activate to move it back to its primary */
3387 activate_routing(NULL, NULL, NULL);
3388 }
3389 }
3390 /* if there are any servers missing who have this server as uplink try to connect them. */
3391 routing_connect_children(opserv_route, server);
3392 }
3393 /* foreach server x3 knows about, if the uplink is this server, call this function on the child. */
3394 for (it=dict_first(servers); it; it=iter_next(it)) {
3395 struct server *sptr = iter_data(it);
3396 if(sptr && sptr->uplink && !strcasecmp(server, sptr->uplink->name)) {
3397 log_module(MAIN_LOG, LOG_DEBUG, "routing_handle_connect calling self on %s's leaf %s", server, sptr->name);
3398 routing_handle_connect(sptr->name, sptr->uplink->name);
3399 }
3400 }
3401 }
3402
3403 /* Handle a failed attempt at connecting servers
3404 * - we should only get here regarding servers X3 attempted to link, other
3405 * opers link messages go to them not to us
3406 */
3407 void
3408 routing_handle_connect_failure(struct server *source, char *server, char *message)
3409 {
3410 char *active;
3411 struct routingPlan *rp;
3412 struct routingPlanServer *rps;
3413 log_module(MAIN_LOG, LOG_ERROR, "Failed to connect %s to %s: %s", server, source->name, message);
3414 /* remove the waiting connection n timeq */
3415 routing_delete_connect_timer(server);
3416 /* check if routing is active.. */
3417 active = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
3418 if(!active)
3419 return;
3420 rp = dict_find(opserv_routing_plans, active, NULL);
3421 if(!rp)
3422 return;
3423
3424 if( ((rps = dict_find(rp->servers, server, NULL)) && !strcasecmp(rps->uplink, source->name))) {
3425 /* failed to connect to its primary uplink */
3426 if(rps->offline == false) {
3427 rps->offline = true;
3428 if(rps->secondaryuplink) {
3429 /* re-activate routing so the secondary
3430 * becomes its uplink, and try again */
3431 activate_routing(NULL, NULL, NULL);
3432 /* attempt to link it again. */
3433 routing_connect_one(opserv_route, server);
3434 /* TODO: reconnect any missing servers who
3435 * normally connect to server, using their backups.
3436 * Probably should just issue a reroute C here. */
3437 }
3438 }
3439 }
3440 }
3441
3442 /* Delete any existing timers, and start the timer again
3443 * using the passed time for the first run.
3444 * - this is called during a retry_period change
3445 * before it has saved the new value. */
3446 void reroute_timer_reset(unsigned int time)
3447 {
3448 timeq_del(0, reroute_timer, NULL, TIMEQ_IGNORE_DATA & TIMEQ_IGNORE_WHEN);
3449 timeq_add(now + time, reroute_timer, "run");
3450 }
3451
3452 static MODCMD_FUNC(cmd_routing_set)
3453 {
3454 char *option = argv[1];
3455 char *options[] = {"ACTIVE", "RETRY_PERIOD", "CONN_PINGOUT", "CONN_READERROR", "KARMA", "DEFAULT_PORT", NULL};
3456 int i;
3457 if(argc < 2) {
3458 route_show_options(cmd, user);
3459 }
3460 else {
3461 char *found_option = NULL;
3462 for(i = 0; options[i]; i++) {
3463 if(!strcasecmp(options[i], option))
3464 found_option = options[i];
3465 }
3466 if(!found_option) {
3467 reply("OSMSG_ROUTINGPLAN_OPTION_NOT_FOUND", option);
3468 return 0;
3469 }
3470 if(argc > 2) {
3471 char *value = argv[2];
3472 char buff[MAXLEN]; /* whats the max length of unsigned int as printf'd? */
3473 if(!strcmp(found_option, "ACTIVE")) { /* must be an existing route. */
3474 if(disabled_string(value) || false_string(value)) {
3475 /* make none of the maps active */
3476 activate_routing(cmd, user, "*");
3477 reply("OSMSG_ROUTING_DISABLED");
3478 return 1;
3479 }
3480 else if(!activate_routing(cmd, user, value)) {
3481 /* neg reply handled in activate_routing */
3482 return 0;
3483 }
3484 }
3485 if(!strcmp(found_option, "CONN_READERROR") || !strcmp(found_option, "CONN_PINGOUT") ||
3486 !strcmp(found_option, "KARMA") ) {
3487 if( enabled_string(value)) {
3488 value = "ENABLED";
3489 }
3490 else if( disabled_string(value) ) {
3491 value = "DISABLED";
3492 }
3493 else {
3494 reply("MSG_INVALID_BINARY", value);
3495 return 0;
3496 }
3497 }
3498 if(!strcmp(found_option, "RETRY_PERIOD")) {
3499 unsigned int duration = ParseInterval(value);
3500 sprintf(buff, "%d", duration);
3501 value = buff;
3502 reroute_timer_reset(duration);
3503 }
3504 /* set the value here */
3505 dict_remove(opserv_routing_plan_options, found_option);
3506 dict_insert(opserv_routing_plan_options, strdup(found_option), strdup(value));
3507 route_show_option(cmd, user, found_option);
3508 }
3509 else {
3510 /* show the current value */
3511 route_show_option(cmd, user, found_option);
3512 }
3513 }
3514 return 1;
3515 }
3516
3517 static MODCMD_FUNC(cmd_stats_routing_plans) {
3518 dict_iterator_t rpit;
3519 dict_iterator_t it;
3520 struct routingPlan *rp;
3521 reply("OSMSG_ROUTINGPLAN_LIST");
3522 reply("OSMSG_ROUTINGPLAN_BAR");
3523 for(rpit = dict_first(opserv_routing_plans); rpit; rpit = iter_next(rpit)) {
3524 const char* name = iter_key(rpit);
3525 rp = iter_data(rpit);
3526 reply("OSMSG_ROUTINGPLAN_NAME", name);
3527 for(it = dict_first(rp->servers); it; it = iter_next(it)) {
3528 const char* servername = iter_key(it);
3529 struct routingPlanServer *rps = iter_data(it);
3530 reply("OSMSG_ROUTINGPLAN_SERVER", servername, rps->port, rps->uplink, rps->karma, rps->offline? "offline" : "online", rps->secondaryuplink ? rps->secondaryuplink : "None");
3531 }
3532
3533 }
3534 reply("OSMSG_ROUTINGPLAN_END");
3535 route_show_options(cmd, user);
3536 return 1;
3537 }
3538
3539
3540 static MODCMD_FUNC(cmd_routing_addplan)
3541 {
3542 char *name;
3543 name = argv[1];
3544 /* dont allow things like 'off', 'false', '0' because thats how we disable routing. */
3545 if(*name && !disabled_string(name) && !false_string(name)) {
3546 if(opserv_add_routing_plan(name)) {
3547 reply("OSMSG_ADDPLAN_SUCCESS", name);
3548 return 1;
3549 }
3550 else {
3551 reply("OSMSG_ADDPLAN_FAILED", name);
3552 return 0;
3553 }
3554 }
3555 else
3556 {
3557 reply("OSMSG_INVALID_PLAN");
3558 return 0;
3559 }
3560 }
3561
3562 static MODCMD_FUNC(cmd_routing_delplan)
3563 {
3564 char *name = argv[1];
3565 if( dict_remove(opserv_routing_plans, name) ) {
3566 char *active = dict_find(opserv_routing_plan_options, "ACTIVE", NULL);
3567 if(active && !strcasecmp(active, name)) {
3568 /* if this was the active plan, disable routing */
3569 activate_routing(cmd, user, "*");
3570 reply("OSMSG_ROUTING_DISABLED");
3571 }
3572 reply("OSMSG_PLAN_DELETED");
3573 return 1;
3574 }
3575 else {
3576 reply("OSMSG_PLAN_NOT_FOUND", name);
3577 return 0;
3578 }
3579 }
3580
3581 static MODCMD_FUNC(cmd_routing_addserver)
3582 {
3583 char *plan;
3584 char *server;
3585 char *portstr;
3586 char *uplink;
3587 char *second;
3588 unsigned int port;
3589 struct routingPlan *rp;
3590
3591 plan = argv[1];
3592 server = strdup(argv[2]);
3593 server = strtok(server, ":");
3594 portstr = strtok(NULL, ":");
3595 if(portstr)
3596 port = atoi(portstr);
3597 else {
3598 char *str = dict_find(opserv_routing_plan_options, "DEFAULT_PORT", NULL);
3599 uplink = argv[3];
3600 port = str ? atoi(str) : 0;
3601 }
3602 uplink = argv[3];
3603 if(argc > 4)
3604 second = argv[4];
3605 else
3606 second = NULL;
3607
3608 if( (rp = dict_find(opserv_routing_plans, plan, 0))) {
3609 char *active;
3610 opserv_routing_plan_add_server(rp, server, uplink, port, KARMA_DEFAULT, second, 0);
3611 reply("OSMSG_PLAN_SERVER_ADDED", server);
3612 if((active = dict_find(opserv_routing_plan_options, "ACTIVE", 0)) && !strcasecmp(plan, active)) {
3613 /* re-activate routing with new info */
3614 activate_routing(cmd, user, NULL);
3615 }
3616
3617 free(server);
3618 return 1;
3619 }
3620 else {
3621 reply("OSMSG_PLAN_NOT_FOUND", plan);
3622 free(server);
3623 return 0;
3624 }
3625 }
3626
3627 static MODCMD_FUNC(cmd_routing_delserver)
3628 {
3629 char *plan;
3630 char *server;
3631 struct routingPlan *rp;
3632 plan = argv[1];
3633 server = argv[2];
3634 if( (rp = dict_find(opserv_routing_plans, plan, 0))) {
3635 if(dict_remove(rp->servers, server)) {
3636 char *active;
3637 reply("OSMSG_PLAN_SERVER_DELETED");
3638 if((active = dict_find(opserv_routing_plan_options, "ACTIVE", 0)) && !strcasecmp(plan, active)) {
3639 /* re-activate routing with new info */
3640 activate_routing(cmd, user, NULL);
3641 }
3642
3643 return 1;
3644 }
3645 else {
3646 reply("OSMSG_PLAN_SERVER_NOT_FOUND", server);
3647 return 0;
3648 }
3649 }
3650 else {
3651 reply("OSMSG_PLAN_NOT_FOUND", plan);
3652 return 0;
3653 }
3654 }
3655
3656
3657 /*************************************************
3658 * Functions to deal with 'route map' command */
3659
3660 /* Figures out how many downlinks there are for proper
3661 * drawing of the route map */
3662 int
3663 num_route_downlinks(struct route *route, char *name)
3664 {
3665 struct routeList *rptr;
3666 int num = 0;
3667 rptr = route->servers;
3668 while(rptr) {
3669 if(!strcasecmp(rptr->uplink, name))
3670 num++;
3671 rptr = rptr->next;
3672 }
3673 return num;
3674 }
3675
3676 void
3677 show_route_downlinks(struct svccmd *cmd, struct route *route, struct userNode *user, char *name, char *prevpre, char *arrowchar, int reset)
3678 {
3679 struct routeList *servPtr;
3680 struct server *sptr;
3681 int j;
3682 char pre[MAXLEN];
3683 char *nextpre;
3684 char *status;
3685 int num = 0;
3686 static int depth = 0;
3687
3688 if(reset)
3689 depth = 0;
3690
3691 nextpre = malloc(MAXLEN);
3692 strcpy(pre, prevpre);
3693
3694 sptr = GetServerH(name);
3695 if((servPtr = find_routeList_server(route, name))) {
3696 if(!sptr)
3697 status = " ";
3698 else if (!strcasecmp(sptr->uplink->name, servPtr->uplink))
3699 status = "X";
3700 else if(servPtr->secondaryuplink && !strcasecmp(sptr->name, servPtr->secondaryuplink))
3701 status = "/";
3702 else
3703 status = "!";
3704 reply("OSMSG_DOWNLINKS_FORMAT_A", pre, arrowchar, name, status);
3705 }
3706 else
3707 reply("OSMSG_DOWNLINKS_FORMAT_B", self->name);
3708 j = num_route_downlinks(route, name);
3709 servPtr = route->servers;
3710 while(servPtr) {
3711 if(!strcasecmp(servPtr->uplink, name)) {
3712 strcpy(nextpre, pre);
3713 if(depth++ > 0) {
3714 if(arrowchar[0] == '`')
3715 strcat(nextpre, " ");
3716 else
3717 strcat(nextpre, "| ");
3718 }
3719 if(j > ++num) {
3720 show_route_downlinks(cmd, route, user, servPtr->server, nextpre, "|", 0);
3721 }
3722 else {
3723 show_route_downlinks(cmd, route, user, servPtr->server, nextpre, "`", 0);
3724 }
3725 }
3726 servPtr = servPtr->next;
3727 }
3728 free(nextpre);
3729 }
3730
3731 int
3732 show_route_map(struct route *route, struct userNode *user, struct svccmd *cmd)
3733 {
3734 if(!route || !route->servers) {
3735 reply("OSMSG_ROUTELIST_EMPTY");
3736 return 0;
3737 }
3738
3739 char *serviceName = conf_get_data("server/hostname", RECDB_QSTRING);
3740 reply("OSMSG_ROUTELIST_AS_PLANNED");
3741 show_route_downlinks(cmd, route, user, serviceName, "", "`", 1);
3742 reply("OSMSG_MAP_CENTERED", route->centered ? "is" : "is not", route->maxdepth);
3743 return 1;
3744 }
3745
3746 static MODCMD_FUNC(cmd_routing_map)
3747 {
3748 show_route_map(opserv_route, user, cmd);
3749 return 1;
3750 }
3751
3752
3753
3754
3755 /* End of auto routing functions *
3756 *********************************/
3757
3758 static MODCMD_FUNC(cmd_addbad)
3759 {
3760 unsigned int arg, count;
3761 dict_iterator_t it;
3762 int bad_found, exempt_found;
3763
3764 /* Create the bad word if it doesn't exist. */
3765 bad_found = !opserv_add_bad_word(cmd, user, argv[1]);
3766
3767 /* Look for exception modifiers. */
3768 for (arg=2; arg<argc; arg++) {
3769 if (!irccasecmp(argv[arg], "except")) {
3770 reply("MSG_DEPRECATED_COMMAND", "addbad ... except", "addexempt");
3771 if (++arg > argc) {
3772 reply("MSG_MISSING_PARAMS", "except");
3773 break;
3774 }
3775 for (count = 0; (arg < argc) && IsChannelName(argv[arg]); arg++) {
3776 dict_find(opserv_exempt_channels, argv[arg], &exempt_found);
3777 if (!exempt_found) {
3778 dict_insert(opserv_exempt_channels, strdup(argv[arg]), NULL);
3779 count++;
3780 }
3781 }
3782 reply("OSMSG_ADDED_EXEMPTIONS", count);
3783 } else {
3784 reply("MSG_DEPRECATED_COMMAND", "addbad (with modifiers)", "addbad");
3785 reply("OSMSG_BAD_MODIFIER", argv[arg]);
3786 }
3787 }
3788
3789 /* Scan for existing channels that match the new bad word. */
3790 if (!bad_found) {
3791 for (it = dict_first(channels); it; it = iter_next(it)) {
3792 struct chanNode *channel = iter_data(it);
3793
3794 if (!opserv_bad_channel(channel->name))
3795 continue;
3796 channel->bad_channel = 1;
3797 if (channel->name[0] == '#')
3798 opserv_shutdown_channel(channel, "OSMSG_ILLEGAL_REASON");
3799 else {
3800 unsigned int nn;
3801 for (nn=0; nn<channel->members.used; nn++) {
3802 struct userNode *user = channel->members.list[nn]->user;
3803 DelUser(user, cmd->parent->bot, 1, "OSMSG_ILLEGAL_KILL_REASON");
3804 }
3805 }
3806 }
3807 }
3808
3809 return 1;
3810 }
3811
3812 static MODCMD_FUNC(cmd_delbad)
3813 {
3814 dict_iterator_t it;
3815 unsigned int nn;
3816
3817 for (nn=0; nn<opserv_bad_words->used; nn++) {
3818 if (!irccasecmp(opserv_bad_words->list[nn], argv[1])) {
3819 string_list_delete(opserv_bad_words, nn);
3820 for (it = dict_first(channels); it; it = iter_next(it)) {
3821 channel = iter_data(it);
3822 if (irccasestr(channel->name, argv[1])
3823 && !opserv_bad_channel(channel->name)) {
3824 DelChannelUser(cmd->parent->bot, channel, "Channel name no longer contains a bad word.", 1);
3825 timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
3826 channel->bad_channel = 0;
3827 }
3828 }
3829 reply("OSMSG_REMOVED_BAD", argv[1]);
3830 return 1;
3831 }
3832 }
3833 reply("OSMSG_NOT_BAD_WORD", argv[1]);
3834 return 0;
3835 }
3836
3837 static MODCMD_FUNC(cmd_addexempt)
3838 {
3839 const char *chanName;
3840
3841 if ((argc > 1) && IsChannelName(argv[1])) {
3842 chanName = argv[1];
3843 } else {
3844 reply("MSG_NOT_CHANNEL_NAME");
3845 OPSERV_SYNTAX();
3846 return 0;
3847 }
3848 dict_insert(opserv_exempt_channels, strdup(chanName), NULL);
3849 channel = GetChannel(chanName);
3850 if (channel) {
3851 if (channel->bad_channel) {
3852 DelChannelUser(cmd->parent->bot, channel, "Channel is now exempt from bad-word checking.", 1);
3853 timeq_del(0, opserv_part_channel, channel, TIMEQ_IGNORE_WHEN);
3854 }
3855 channel->bad_channel = 0;
3856 }
3857 reply("OSMSG_ADDED_EXEMPTION", chanName);
3858 return 1;
3859 }
3860
3861 static MODCMD_FUNC(cmd_delexempt)
3862 {
3863 const char *chanName;
3864
3865 if ((argc > 1) && IsChannelName(argv[1])) {
3866 chanName = argv[1];
3867 } else {
3868 reply("MSG_NOT_CHANNEL_NAME");
3869 OPSERV_SYNTAX();
3870 return 0;
3871 }
3872 if (!dict_remove(opserv_exempt_channels, chanName)) {
3873 reply("OSMSG_NOT_EXEMPT", chanName);
3874 return 0;
3875 }
3876 reply("OSMSG_REMOVED_EXEMPTION", chanName);
3877 return 1;
3878 }
3879
3880 static void
3881 opserv_expire_trusted_host(void *data)
3882 {
3883 struct trusted_host *th = data;
3884 dict_remove(opserv_trusted_hosts, th->ipaddr);
3885 }
3886
3887 static void
3888 opserv_add_trusted_host(const char *ipaddr, unsigned int limit, const char *issuer, time_t issued, time_t expires, const char *reason)
3889 {
3890 struct trusted_host *th;
3891 th = calloc(1, sizeof(*th));
3892 if (!th)
3893 return;
3894 th->ipaddr = strdup(ipaddr);
3895 th->reason = reason ? strdup(reason) : NULL;
3896 th->issuer = issuer ? strdup(issuer) : NULL;
3897 th->issued = issued;
3898 th->limit = limit;
3899 th->expires = expires;
3900 dict_insert(opserv_trusted_hosts, th->ipaddr, th);
3901 if (th->expires)
3902 timeq_add(th->expires, opserv_expire_trusted_host, th);
3903 }
3904
3905 static void
3906 free_trusted_host(void *data)
3907 {
3908 struct trusted_host *th = data;
3909 free(th->ipaddr);
3910 free(th->reason);
3911 free(th->issuer);
3912 free(th);
3913 }
3914
3915 static MODCMD_FUNC(cmd_addtrust)
3916 {
3917 unsigned long interval;
3918 char *reason, *tmp;
3919 irc_in_addr_t tmpaddr;
3920 unsigned int count;
3921
3922 if (dict_find(opserv_trusted_hosts, argv[1], NULL)) {
3923 reply("OSMSG_ALREADY_TRUSTED", argv[1]);
3924 return 0;
3925 }
3926
3927 if (!irc_pton(&tmpaddr, NULL, argv[1])) {
3928 reply("OSMSG_BAD_IP", argv[1]);
3929 return 0;
3930 }
3931
3932 count = strtoul(argv[2], &tmp, 10);
3933 if (*tmp != '\0') {
3934 reply("OSMSG_BAD_NUMBER", argv[2]);
3935 return 0;
3936 }
3937
3938 interval = ParseInterval(argv[3]);
3939 if (!interval && strcmp(argv[3], "0")) {
3940 reply("MSG_INVALID_DURATION", argv[3]);
3941 return 0;
3942 }
3943
3944 reason = unsplit_string(argv+4, argc-4, NULL);
3945 opserv_add_trusted_host(argv[1], count, user->handle_info->handle, now, interval ? (now + interval) : 0, reason);
3946 reply("OSMSG_ADDED_TRUSTED");
3947 return 1;
3948 }
3949
3950 static MODCMD_FUNC(cmd_edittrust)
3951 {
3952 unsigned long interval;
3953 struct trusted_host *th;
3954 char *reason, *tmp;
3955 unsigned int count;
3956
3957 th = dict_find(opserv_trusted_hosts, argv[1], NULL);
3958 if (!th) {
3959 reply("OSMSG_NOT_TRUSTED", argv[1]);
3960 return 0;
3961 }
3962 count = strtoul(argv[2], &tmp, 10);
3963 if (!count || *tmp) {
3964 reply("OSMSG_BAD_NUMBER", argv[2]);
3965 return 0;
3966 }
3967 interval = ParseInterval(argv[3]);
3968 if (!interval && strcmp(argv[3], "0")) {
3969 reply("MSG_INVALID_DURATION", argv[3]);
3970 return 0;
3971 }
3972 reason = unsplit_string(argv+4, argc-4, NULL);
3973 if (th->expires)
3974 timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
3975
3976 free(th->reason);
3977 th->reason = strdup(reason);
3978 free(th->issuer);
3979 th->issuer = strdup(user->handle_info->handle);
3980 th->issued = now;
3981 th->limit = count;
3982 if (interval) {
3983 th->expires = now + interval;
3984 timeq_add(th->expires, opserv_expire_trusted_host, th);
3985 } else
3986 th->expires = 0;
3987 reply("OSMSG_UPDATED_TRUSTED", th->ipaddr);
3988 return 1;
3989 }
3990
3991 static MODCMD_FUNC(cmd_deltrust)
3992 {
3993 unsigned int n;
3994
3995 for (n=1; n<argc; n++) {
3996 struct trusted_host *th = dict_find(opserv_trusted_hosts, argv[n], NULL);
3997 if (!th)
3998 continue;
3999 if (th->expires)
4000 timeq_del(th->expires, opserv_expire_trusted_host, th, 0);
4001 dict_remove(opserv_trusted_hosts, argv[n]);
4002 }
4003 reply("OSMSG_REMOVED_TRUSTED");
4004 return 1;
4005 }
4006
4007 /* This doesn't use dict_t because it's a little simpler to open-code the
4008 * comparisons (and simpler arg-passing for the ADD subcommand).
4009 */
4010 static MODCMD_FUNC(cmd_clone)
4011 {
4012 int i;
4013 struct userNode *clone;
4014
4015 clone = GetUserH(argv[2]);
4016 if (!irccasecmp(argv[1], "ADD")) {
4017 char *userinfo;
4018 char ident[USERLEN+1];
4019
4020 if (argc < 5) {
4021 reply("MSG_MISSING_PARAMS", argv[1]);
4022 OPSERV_SYNTAX();
4023 return 0;
4024 }
4025 if (clone) {
4026 reply("OSMSG_CLONE_EXISTS", argv[2]);
4027 return 0;
4028 }
4029 userinfo = unsplit_string(argv+4, argc-4, NULL);
4030 for (i=0; argv[3][i] && (i<USERLEN); i++) {
4031 if (argv[3][i] == '@') {
4032 ident[i++] = 0;
4033 break;
4034 } else {
4035 ident[i] = argv[3][i];
4036 }
4037 }
4038 if (!argv[3][i] || (i==USERLEN)) {
4039 reply("OSMSG_NOT_A_HOSTMASK");
4040 return 0;
4041 }
4042 if (!(clone = AddClone(argv[2], ident, argv[3]+i, userinfo))) {
4043 reply("OSMSG_CLONE_FAILED", argv[2]);
4044 return 0;
4045 }
4046 reply("OSMSG_CLONE_ADDED", clone->nick);
4047 return 1;
4048 }
4049 if (!clone) {
4050 reply("MSG_NICK_UNKNOWN", argv[2]);
4051 return 0;
4052 }
4053 if (clone->uplink != self || IsService(clone)) {
4054 reply("OSMSG_NOT_A_CLONE", clone->nick);
4055 return 0;
4056 }
4057 if (!irccasecmp(argv[1], "REMOVE")) {
4058 const char *reason;
4059 if (argc > 3) {
4060 reason = unsplit_string(argv+3, argc-3, NULL);
4061 } else {
4062 char *tmp;
4063 tmp = alloca(strlen(clone->nick) + strlen(OSMSG_PART_REASON));
4064 sprintf(tmp, OSMSG_PART_REASON, clone->nick);
4065 reason = tmp;
4066 }
4067 DelUser(clone, NULL, 1, reason);
4068 reply("OSMSG_CLONE_REMOVED", argv[2]);
4069 return 1;
4070 }
4071 if (argc < 4) {
4072 reply("MSG_MISSING_PARAMS", argv[1]);
4073 OPSERV_SYNTAX();
4074 return 0;
4075 }
4076 channel = GetChannel(argv[3]);
4077 if (!irccasecmp(argv[1], "JOIN")) {
4078 if (!channel
4079 && !(channel = AddChannel(argv[3], now, NULL, NULL, NULL))) {
4080 reply("MSG_CHANNEL_UNKNOWN", argv[3]);
4081 return 0;
4082 }
4083 AddChannelUser(clone, channel);
4084 reply("OSMSG_CLONE_JOINED", clone->nick, channel->name);
4085 return 1;
4086 }
4087 if (!irccasecmp(argv[1], "PART")) {
4088 if (!channel) {
4089 reply("MSG_CHANNEL_UNKNOWN", argv[3]);
4090 return 0;
4091 }
4092 if (!GetUserMode(channel, clone)) {
4093 reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
4094 return 0;
4095 }
4096 reply("OSMSG_CLONE_PARTED", clone->nick, channel->name);
4097 DelChannelUser(clone, channel, "Leaving.", 0);
4098 return 1;
4099 }
4100 if (!irccasecmp(argv[1], "OP")) {
4101 struct mod_chanmode change;
4102 if (!channel) {
4103 reply("MSG_CHANNEL_UNKNOWN", argv[3]);
4104 return 0;
4105 }
4106 mod_chanmode_init(&change);
4107 change.argc = 1;
4108 change.args[0].mode = MODE_CHANOP;
4109 change.args[0].u.member = GetUserMode(channel, clone);
4110 if (!change.args[0].u.member) {
4111 reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
4112 return 0;
4113 }
4114 modcmd_chanmode_announce(&change);
4115 reply("OSMSG_OPS_GIVEN", channel->name, clone->nick);
4116 return 1;
4117 }
4118 if (!irccasecmp(argv[1], "HOP")) {
4119 struct mod_chanmode change;
4120 if (!channel) {
4121 reply("MSG_CHANNEL_UNKNOWN", argv[3]);
4122 return 0;
4123 }
4124 mod_chanmode_init(&change);
4125 change.argc = 1;
4126 change.args[0].mode = MODE_HALFOP;
4127 change.args[0].u.member = GetUserMode(channel, clone);
4128 if (!change.args[0].u.member) {
4129 reply("OSMSG_NOT_ON_CHANNEL", clone->nick, channel->name);
4130 return 0;
4131 }
4132 modcmd_chanmode_announce(&change);
4133 reply("OSMSG_HOPS_GIVEN", channel->name, clone->nick);
4134 return 1;
4135 }
4136 if (argc < 5) {
4137 reply("MSG_MISSING_PARAMS", argv[1]);
4138 OPSERV_SYNTAX();
4139 return 0;
4140 }
4141 if (!irccasecmp(argv[1], "SAY")) {
4142 char *text = unsplit_string(argv+4, argc-4, NULL);
4143 irc_privmsg(clone, argv[3], text);
4144 reply("OSMSG_CLONE_SAID", clone->nick, argv[3]);
4145 return 1;
4146 }
4147 reply("OSMSG_UNKNOWN_SUBCOMMAND", argv[1], argv[0]);
4148 return 0;
4149 }
4150
4151 static struct helpfile_expansion
4152 opserv_help_expand(const char *variable)
4153 {
4154 extern struct userNode *message_source;
4155 struct helpfile_expansion exp;
4156 struct service *service;
4157 struct svccmd *cmd;
4158 dict_iterator_t it;
4159 int row;
4160 unsigned int level;
4161
4162 if (!(service = service_find(message_source->nick))) {
4163 exp.type = HF_STRING;
4164 exp.value.str = NULL;
4165 } else if (!irccasecmp(variable, "index")) {
4166 exp.type = HF_TABLE;
4167 exp.value.table.length = 1;
4168 exp.value.table.width = 2;
4169 exp.value.table.flags = TABLE_REPEAT_HEADERS | TABLE_REPEAT_ROWS;
4170 exp.value.table.contents = calloc(dict_size(service->commands)+1, sizeof(char**));
4171 exp.value.table.contents[0] = calloc(exp.value.table.width, sizeof(char*));
4172 exp.value.table.contents[0][0] = "Command";
4173 exp.value.table.contents[0][1] = "Level";
4174 for (it=dict_first(service->commands); it; it=iter_next(it)) {
4175 cmd = iter_data(it);
4176 row = exp.value.table.length++;
4177 exp.value.table.contents[row] = calloc(exp.value.table.width, sizeof(char*));
4178 exp.value.table.contents[row][0] = iter_key(it);
4179 level = cmd->min_opserv_level;
4180 if (!level_strings[level]) {
4181 level_strings[level] = malloc(16);
4182 snprintf(level_strings[level], 16, "%3d", level);
4183 }
4184 exp.value.table.contents[row][1] = level_strings[level];
4185 }
4186 } else if (!strncasecmp(variable, "level", 5)) {
4187 cmd = dict_find(service->commands, variable+6, NULL);
4188 exp.type = HF_STRING;
4189 if (cmd) {
4190 level = cmd->min_opserv_level;
4191 exp.value.str = malloc(16);
4192 snprintf(exp.value.str, 16, "%3d", level);
4193 } else {
4194 exp.value.str = NULL;
4195 }
4196 } else {
4197 exp.type = HF_STRING;
4198 exp.value.str = NULL;
4199 }
4200 return exp;
4201 }
4202
4203 struct modcmd *
4204 opserv_define_func(const char *name, modcmd_func_t *func, int min_level, int reqchan, int min_argc)
4205 {
4206 char buf[16], *flags = NULL;
4207 unsigned int iflags = 0;
4208 sprintf(buf, "%d", min_level);
4209 switch (reqchan) {
4210 case 1: flags = "+acceptchan"; break;
4211 case 3: flags = "+acceptpluschan"; /* fall through */
4212 case 2: iflags = MODCMD_REQUIRE_CHANNEL; break;
4213 }
4214 if (flags) {
4215 return modcmd_register(opserv_module, name, func, min_argc, iflags, "level", buf, "flags", flags, "flags", "+oper", NULL);
4216 } else {
4217 return modcmd_register(opserv_module, name, func, min_argc, iflags, "level", buf, "flags", "+oper", NULL);
4218 }
4219 }
4220
4221 int add_reserved(const char *key, void *data, void *extra)
4222 {
4223 struct chanNode *chan;
4224 struct record_data *rd = data;
4225 const char *ident, *hostname, *desc;
4226 unsigned int i;
4227 struct userNode *reserve;
4228 ident = database_get_data(rd->d.object, KEY_IDENT, RECDB_QSTRING);
4229 if (!ident) {
4230 log_module(OS_LOG, LOG_ERROR, "Missing ident for reserve of %s", key);
4231 return 0;
4232 }
4233 hostname = database_get_data(rd->d.object, KEY_HOSTNAME, RECDB_QSTRING);
4234 if (!hostname) {
4235 log_module(OS_LOG, LOG_ERROR, "Missing hostname for reserve of %s", key);
4236 return 0;
4237 }
4238 desc = database_get_data(rd->d.object, KEY_DESC, RECDB_QSTRING);
4239 if (!desc) {
4240 log_module(OS_LOG, LOG_ERROR, "Missing description for reserve of %s", key);
4241 return 0;
4242 }
4243 if ((reserve = AddClone(key, ident, hostname, desc))) {
4244 reserve->modes |= FLAGS_PERSISTENT;
4245 dict_insert(extra, reserve->nick, reserve);
4246 }
4247
4248 if (autojoin_channels && reserve) {
4249 for (i = 0; i < autojoin_channels->used; i++) {
4250 chan = AddChannel(autojoin_channels->list[i], now, "+nt", NULL, NULL);
4251 AddChannelUser(reserve, chan)->modes |= MODE_VOICE;
4252 }
4253 }
4254
4255 return 0;
4256 }
4257
4258 static unsigned int
4259 foreach_matching_user(const char *hostmask, discrim_search_func func, void *extra)
4260 {
4261 discrim_t discrim;
4262 char *dupmask;
4263 unsigned int matched;
4264
4265 if (!self->uplink) return 0;
4266 discrim = calloc(1, sizeof(*discrim));
4267 discrim->limit = dict_size(clients);
4268 discrim->max_level = ~0;
4269 discrim->max_ts = now;
4270 discrim->max_channels = INT_MAX;
4271 discrim->authed = -1;
4272 discrim->info_space = -1;
4273 discrim->intra_scmp = 0;
4274 discrim->intra_dcmp = 0;
4275 discrim->use_regex = 0;
4276 discrim->silent = 0;
4277 dupmask = strdup(hostmask);
4278 if (split_ircmask(dupmask, &discrim->mask_nick, &discrim->mask_ident, &discrim->mask_host)) {
4279 if (!irc_pton(&discrim->ip_mask, &discrim->ip_mask_bits, discrim->mask_host))
4280 discrim->ip_mask_bits = 0;
4281 matched = opserv_discrim_search(discrim, func, extra);
4282 } else {
4283 log_module(OS_LOG, LOG_ERROR, "Couldn't split IRC mask for gag %s!", hostmask);
4284 matched = 0;
4285 }
4286 free(discrim);
4287 free(dupmask);
4288 return matched;
4289 }
4290
4291 static unsigned int
4292 gag_free(struct gag_entry *gag)
4293 {
4294 unsigned int ungagged;
4295
4296 /* Remove from gag list */
4297 if (gagList == gag) {
4298 gagList = gag->next;
4299 } else {
4300 struct gag_entry *prev;
4301 for (prev = gagList; prev->next != gag; prev = prev->next) ;
4302 prev->next = gag->next;
4303 }
4304
4305 ungagged = foreach_matching_user(gag->mask, ungag_helper_func, NULL);
4306
4307 /* Deallocate storage */
4308 free(gag->reason);
4309 free(gag->owner);
4310 free(gag->mask);
4311 free(gag);
4312
4313 return ungagged;
4314 }
4315
4316 static void
4317 gag_expire(void *data)
4318 {
4319 gag_free(data);
4320 }
4321
4322 unsigned int
4323 gag_create(const char *mask, const char *owner, const char *reason, time_t expires)
4324 {
4325 struct gag_entry *gag;
4326
4327 /* Create gag and put it into linked list */
4328 gag = calloc(1, sizeof(*gag));
4329 gag->mask = strdup(mask);
4330 gag->owner = strdup(owner ? owner : "<unknown>");
4331 gag->reason = strdup(reason ? reason : "<unknown>");
4332 gag->expires = expires;
4333 if (gag->expires)
4334 timeq_add(gag->expires, gag_expire, gag);
4335 gag->next = gagList;
4336 gagList = gag;
4337
4338 /* If we're linked, see if who the gag applies to */
4339 return foreach_matching_user(mask, gag_helper_func, gag);
4340 }
4341
4342 static int
4343 add_gag_helper(const char *key, void *data, UNUSED_ARG(void *extra))
4344 {
4345 struct record_data *rd = data;
4346 char *owner, *reason, *expstr;
4347 time_t expires;
4348
4349 owner = database_get_data(rd->d.object, KEY_OWNER, RECDB_QSTRING);
4350 reason = database_get_data(rd->d.object, KEY_REASON, RECDB_QSTRING);
4351 expstr = database_get_data(rd->d.object, KEY_EXPIRES, RECDB_QSTRING);
4352 expires = expstr ? strtoul(expstr, NULL, 0) : 0;
4353 gag_create(key, owner, reason, expires);
4354
4355 return 0;
4356 }
4357
4358 static struct opserv_user_alert *
4359 opserv_add_user_alert(struct userNode *req, const char *name, opserv_alert_reaction reaction, const char *text_discrim)
4360 {
4361 unsigned int wordc;
4362 char *wordv[MAXNUMPARAMS], *discrim_copy;
4363 struct opserv_user_alert *alert;
4364 char *name_dup;
4365
4366 if (dict_find(opserv_user_alerts, name, NULL)) {
4367 send_message(req, opserv, "OSMSG_ALERT_EXISTS", name);
4368 return NULL;
4369 }
4370 alert = malloc(sizeof(*alert));
4371 alert->owner = strdup(req->handle_info ? req->handle_info->handle : req->nick);
4372 alert->text_discrim = strdup(text_discrim);
4373 discrim_copy = strdup(text_discrim); /* save a copy of the discrim */
4374 wordc = split_line(discrim_copy, false, ArrayLength(wordv), wordv);
4375 alert->discrim = opserv_discrim_create(req, opserv, wordc, wordv, 0);
4376 if (!alert->discrim) {
4377 free(alert->text_discrim);
4378 free(discrim_copy);
4379 free(alert);
4380 return NULL;
4381 }
4382 alert->split_discrim = discrim_copy;
4383 name_dup = strdup(name);
4384 if (!alert->discrim->reason)
4385 alert->discrim->reason = strdup(name);
4386 alert->reaction = reaction;
4387 dict_insert(opserv_user_alerts, name_dup, alert);
4388 /* Stick the alert into the appropriate additional alert dict(s).
4389 * For channel alerts, we only use channels and min_channels;
4390 * max_channels would have to be checked on /part, which we do not
4391 * yet do, and which seems of questionable value.
4392 */
4393 if (alert->discrim->channel || alert->discrim->min_channels)
4394 dict_insert(opserv_channel_alerts, name_dup, alert);
4395 if (alert->discrim->mask_nick)
4396 dict_insert(opserv_nick_based_alerts, name_dup, alert);
4397 return alert;
4398 }
4399
4400 /*
4401 static int
4402 add_chan_warn(const char *key, void *data, UNUSED_ARG(void *extra))
4403 {
4404 struct record_data *rd = data;
4405 char *reason = GET_RECORD_QSTRING(rd);
4406
4407 * i hope this can't happen *
4408 if (!reason)
4409 reason = "No Reason";
4410
4411 dict_insert(opserv_chan_warn, strdup(key), strdup(reason));
4412 return 0;
4413 }
4414 */
4415
4416
4417 static int
4418 add_user_alert(const char *key, void *data, UNUSED_ARG(void *extra))
4419 {
4420 dict_t alert_dict;
4421 const char *discrim, *react, *owner;
4422 opserv_alert_reaction reaction;
4423 struct opserv_user_alert *alert;
4424
4425 if (!(alert_dict = GET_RECORD_OBJECT((struct record_data *)data))) {
4426 log_module(OS_LOG, LOG_ERROR, "Bad type (not a record) for alert %s.", key);
4427 return 1;
4428 }
4429 discrim = database_get_data(alert_dict, KEY_DISCRIM, RECDB_QSTRING);
4430 react = database_get_data(alert_dict, KEY_REACTION, RECDB_QSTRING);
4431 if (!react || !irccasecmp(react, "notice"))
4432 reaction = REACT_NOTICE;
4433 else if (!irccasecmp(react, "kill"))
4434 reaction = REACT_KILL;
4435 /*
4436 else if (!irccasecmp(react, "silent"))
4437 reaction = REACT_SILENT;
4438 */
4439 else if (!irccasecmp(react, "gline"))
4440 reaction = REACT_GLINE;
4441 else if (!irccasecmp(react, "track"))
4442 reaction = REACT_TRACK;
4443 else if (!irccasecmp(react, "shun"))
4444 reaction = REACT_SHUN;
4445 else {
4446 log_module(OS_LOG, LOG_ERROR, "Invalid reaction %s for alert %s.", react, key);
4447 return 0;
4448 }
4449 alert = opserv_add_user_alert(opserv, key, reaction, discrim);
4450 if (!alert) {
4451 log_module(OS_LOG, LOG_ERROR, "Unable to create alert %s from database.", key);
4452 return 0;
4453 }
4454 owner = database_get_data(alert_dict, KEY_OWNER, RECDB_QSTRING);
4455 free(alert->owner);
4456 alert->owner = strdup(owner ? owner : "<unknown>");
4457 return 0;
4458 }
4459
4460 static int
4461 trusted_host_read(const char *host, void *data, UNUSED_ARG(void *extra))
4462 {
4463 struct record_data *rd = data;
4464 const char *limit, *str, *reason, *issuer;
4465 time_t issued, expires;
4466
4467 if (rd->type == RECDB_QSTRING) {
4468 /* old style host by itself */
4469 limit = GET_RECORD_QSTRING(rd);
4470 issued = 0;
4471 issuer = NULL;
4472 expires = 0;
4473 reason = NULL;
4474 } else if (rd->type == RECDB_OBJECT) {
4475 dict_t obj = GET_RECORD_OBJECT(rd);
4476 /* new style structure */
4477 limit = database_get_data(obj, KEY_LIMIT, RECDB_QSTRING);
4478 str = database_get_data(obj, KEY_EXPIRES, RECDB_QSTRING);
4479 expires = str ? ParseInterval(str) : 0;
4480 reason = database_get_data(obj, KEY_REASON, RECDB_QSTRING);
4481 issuer = database_get_data(obj, KEY_ISSUER, RECDB_QSTRING);
4482 str = database_get_data(obj, KEY_ISSUED, RECDB_QSTRING);
4483 issued = str ? ParseInterval(str) : 0;
4484 } else
4485 return 0;
4486
4487 if (expires && (expires < now))
4488 return 0;
4489 opserv_add_trusted_host(host, (limit ? strtoul(limit, NULL, 0) : 0), issuer, issued, expires, reason);
4490 return 0;
4491 }
4492
4493 static int
4494 add_routing_plan_server(const char *name, void *data, void *rp)
4495 {
4496 struct record_data *rd = data;
4497 const char *uplink, *portstr, *karma, *second, *offline;
4498
4499 dict_t obj = GET_RECORD_OBJECT(rd);
4500 if(rd->type == RECDB_OBJECT) {
4501 uplink = database_get_data(obj, KEY_UPLINK, RECDB_QSTRING);
4502 second = database_get_data(obj, KEY_SECOND, RECDB_QSTRING);
4503 portstr = database_get_data(obj, KEY_PORT, RECDB_QSTRING);
4504 karma = database_get_data(obj, KEY_KARMA, RECDB_QSTRING);
4505 offline = database_get_data(obj, KEY_OFFLINE, RECDB_QSTRING);
4506 /* create routing plan server named key, with uplink uplink. */
4507 opserv_routing_plan_add_server(rp, name, uplink, portstr ? atoi(portstr) : 0,
4508 karma ? atoi(karma) : KARMA_DEFAULT, second,
4509 offline ? atoi(offline) : 0);
4510 }
4511 return 0;
4512
4513 }
4514
4515 static int
4516 routing_plan_set_option(const char *name, void *data, UNUSED_ARG(void *extra))
4517 {
4518 struct record_data *rd = data;
4519 if(rd->type == RECDB_QSTRING)
4520 {
4521 char *value = GET_RECORD_QSTRING(rd);
4522 dict_insert(opserv_routing_plan_options, strdup(name), strdup(value));
4523 }
4524 return 0;
4525 }
4526
4527 static int
4528 add_routing_plan(const char *name, void *data, UNUSED_ARG(void *extra))
4529 {
4530 struct record_data *rd = data;
4531 struct routingPlan *rp;
4532
4533 if(rd->type == RECDB_OBJECT) {
4534 dict_t obj = GET_RECORD_OBJECT(rd);
4535 rp = opserv_add_routing_plan(name);
4536 dict_foreach(obj, add_routing_plan_server, rp);
4537 }
4538 return 0;
4539 }
4540
4541 static int
4542 opserv_saxdb_read(struct dict *conf_db)
4543 {
4544 dict_t object;
4545 struct record_data *rd;
4546 dict_iterator_t it;
4547 unsigned int nn;
4548
4549 if ((object = database_get_data(conf_db, KEY_RESERVES, RECDB_OBJECT)))
4550 dict_foreach(object, add_reserved, opserv_reserved_nick_dict);
4551 if ((rd = database_get_path(conf_db, KEY_BAD_WORDS))) {
4552 switch (rd->type) {
4553 case RECDB_STRING_LIST:
4554 /* Add words one by one just in case there are overlaps from an old DB. */
4555 for (nn=0; nn<rd->d.slist->used; ++nn)
4556 opserv_add_bad_word(NULL, NULL, rd->d.slist->list[nn]);
4557 break;
4558 case RECDB_OBJECT:
4559 for (it=dict_first(rd->d.object); it; it=iter_next(it)) {
4560 opserv_add_bad_word(NULL, NULL, iter_key(it));
4561 rd = iter_data(it);
4562 if (rd->type == RECDB_STRING_LIST)
4563 for (nn=0; nn<rd->d.slist->used; nn++)
4564 dict_insert(opserv_exempt_channels, strdup(rd->d.slist->list[nn]), NULL);
4565 }
4566 break;
4567 default:
4568 /* do nothing */;
4569 }
4570 }
4571 if ((rd = database_get_path(conf_db, KEY_EXEMPT_CHANNELS))
4572 && (rd->type == RECDB_STRING_LIST)) {
4573 for (nn=0; nn<rd->d.slist->used; ++nn)
4574 dict_insert(opserv_exempt_channels, strdup(rd->d.slist->list[nn]), NULL);
4575 }
4576 if ((object = database_get_data(conf_db, KEY_MAX_CLIENTS, RECDB_OBJECT))) {
4577 char *str;
4578 if ((str = database_get_data(object, KEY_MAX, RECDB_QSTRING)))
4579 max_clients = atoi(str);
4580 if ((str = database_get_data(object, KEY_TIME, RECDB_QSTRING)))
4581 max_clients_time = atoi(str);
4582 }
4583 if ((object = database_get_data(conf_db, KEY_TRUSTED_HOSTS, RECDB_OBJECT)))
4584 dict_foreach(object, trusted_host_read, opserv_trusted_hosts);
4585 if ((object = database_get_data(conf_db, KEY_GAGS, RECDB_OBJECT)))
4586 dict_foreach(object, add_gag_helper, NULL);
4587 if ((object = database_get_data(conf_db, KEY_ALERTS, RECDB_OBJECT)))
4588 dict_foreach(object, add_user_alert, NULL);
4589 /*
4590 if ((object = database_get_data(conf_db, KEY_WARN, RECDB_OBJECT)))
4591 dict_foreach(object, add_chan_warn, NULL);
4592 */
4593
4594 if ((object = database_get_data(conf_db, KEY_ROUTINGPLAN, RECDB_OBJECT)))
4595 dict_foreach(object, add_routing_plan, NULL);
4596
4597 if ((object = database_get_data(conf_db, KEY_ROUTINGPLAN_OPTIONS, RECDB_OBJECT)))
4598 dict_foreach(object, routing_plan_set_option, NULL);
4599
4600 return 0;
4601 }
4602
4603 static int
4604 opserv_saxdb_write(struct saxdb_context *ctx)
4605 {
4606 struct string_list *slist;
4607 dict_iterator_t it;
4608
4609 /* reserved nicks */
4610 if (dict_size(opserv_reserved_nick_dict)) {
4611 saxdb_start_record(ctx, KEY_RESERVES, 1);
4612 for (it = dict_first(opserv_reserved_nick_dict); it; it = iter_next(it)) {
4613 struct userNode *user = iter_data(it);
4614 if (!IsPersistent(user)) continue;
4615 saxdb_start_record(ctx, iter_key(it), 0);
4616 saxdb_write_string(ctx, KEY_IDENT, user->ident);
4617 saxdb_write_string(ctx, KEY_HOSTNAME, user->hostname);
4618 saxdb_write_string(ctx, KEY_DESC, user->info);
4619 saxdb_end_record(ctx);
4620 }
4621 saxdb_end_record(ctx);
4622 }
4623 /* bad word set */
4624 if (opserv_bad_words->used) {
4625 saxdb_write_string_list(ctx, KEY_BAD_WORDS, opserv_bad_words);
4626 }
4627 /* routing plan options */
4628 if (dict_size(opserv_routing_plan_options)) {
4629 saxdb_start_record(ctx, KEY_ROUTINGPLAN_OPTIONS, 1);
4630 for(it = dict_first(opserv_routing_plan_options); it; it = iter_next(it)) {
4631 saxdb_write_string(ctx, iter_key(it), iter_data(it));
4632 }
4633 saxdb_end_record(ctx);
4634 }
4635 /* routing plans */
4636 if (dict_size(opserv_routing_plans)) {
4637 dict_iterator_t svrit;
4638 struct routingPlan *rp;
4639 struct routingPlanServer *rps;
4640 saxdb_start_record(ctx, KEY_ROUTINGPLAN, 1);
4641 for (it = dict_first(opserv_routing_plans); it; it = iter_next(it)) {
4642 rp = iter_data(it);
4643 saxdb_start_record(ctx, iter_key(it), 0);
4644 for(svrit = dict_first(rp->servers); svrit; svrit = iter_next(svrit)) {
4645 char buf[MAXLEN];
4646 rps = iter_data(svrit);
4647 saxdb_start_record(ctx, iter_key(svrit), 0);
4648 saxdb_write_string(ctx, KEY_UPLINK, rps->uplink);
4649 if(rps->secondaryuplink)
4650 saxdb_write_string(ctx, KEY_SECOND, rps->secondaryuplink);
4651 sprintf(buf, "%d", rps->port);
4652 saxdb_write_string(ctx, KEY_PORT, buf);
4653 sprintf(buf, "%d", rps->karma);
4654 saxdb_write_string(ctx, KEY_KARMA, buf);
4655 sprintf(buf, "%d", rps->offline);
4656 saxdb_write_string(ctx, KEY_OFFLINE, buf);
4657 saxdb_end_record(ctx);
4658 }
4659 saxdb_end_record(ctx);
4660 }
4661 saxdb_end_record(ctx);
4662 }
4663 /* insert exempt channel names */
4664 if (dict_size(opserv_exempt_channels)) {
4665 slist = alloc_string_list(dict_size(opserv_exempt_channels));
4666 for (it=dict_first(opserv_exempt_channels); it; it=iter_next(it)) {
4667 string_list_append(slist, strdup(iter_key(it)));
4668 }
4669 saxdb_write_string_list(ctx, KEY_EXEMPT_CHANNELS, slist);
4670 free_string_list(slist);
4671 }
4672 /* trusted hosts takes a little more work */
4673 if (dict_size(opserv_trusted_hosts)) {
4674 saxdb_start_record(ctx, KEY_TRUSTED_HOSTS, 1);
4675 for (it = dict_first(opserv_trusted_hosts); it; it = iter_next(it)) {
4676 struct trusted_host *th = iter_data(it);
4677 saxdb_start_record(ctx, iter_key(it), 0);
4678 if (th->limit) saxdb_write_int(ctx, KEY_LIMIT, th->limit);
4679 if (th->expires) saxdb_write_int(ctx, KEY_EXPIRES, th->expires);
4680 if (th->issued) saxdb_write_int(ctx, KEY_ISSUED, th->issued);
4681 if (th->issuer) saxdb_write_string(ctx, KEY_ISSUER, th->issuer);
4682 if (th->reason) saxdb_write_string(ctx, KEY_REASON, th->reason);
4683 saxdb_end_record(ctx);
4684 }
4685 saxdb_end_record(ctx);
4686 }
4687 /* gags */
4688 if (gagList) {
4689 struct gag_entry *gag;
4690 saxdb_start_record(ctx, KEY_GAGS, 1);
4691 for (gag = gagList; gag; gag = gag->next) {
4692 saxdb_start_record(ctx, gag->mask, 0);
4693 saxdb_write_string(ctx, KEY_OWNER, gag->owner);
4694 saxdb_write_string(ctx, KEY_REASON, gag->reason);
4695 if (gag->expires) saxdb_write_int(ctx, KEY_EXPIRES, gag->expires);
4696 saxdb_end_record(ctx);
4697 }
4698 saxdb_end_record(ctx);
4699 }
4700 /* channel warnings */
4701 /*
4702 if (dict_size(opserv_chan_warn)) {
4703 saxdb_start_record(ctx, KEY_WARN, 0);
4704 for (it = dict_first(opserv_chan_warn); it; it = iter_next(it)) {
4705 saxdb_write_string(ctx, iter_key(it), iter_data(it));
4706 }
4707 saxdb_end_record(ctx);
4708 }
4709 */
4710 /* alerts */
4711 if (dict_size(opserv_user_alerts)) {
4712 saxdb_start_record(ctx, KEY_ALERTS, 1);
4713 for (it = dict_first(opserv_user_alerts); it; it = iter_next(it)) {
4714 struct opserv_user_alert *alert = iter_data(it);
4715 const char *reaction;
4716 saxdb_start_record(ctx, iter_key(it), 0);
4717 saxdb_write_string(ctx, KEY_DISCRIM, alert->text_discrim);
4718 saxdb_write_string(ctx, KEY_OWNER, alert->owner);
4719 switch (alert->reaction) {
4720 case REACT_NOTICE: reaction = "notice"; break;
4721 case REACT_KILL: reaction = "kill"; break;
4722 // case REACT_SILENT: reaction = "silent"; break;
4723 case REACT_GLINE: reaction = "gline"; break;
4724 case REACT_TRACK: reaction = "track"; break;
4725 case REACT_SHUN: reaction = "shun"; break;
4726 default:
4727 reaction = NULL;
4728 log_module(OS_LOG, LOG_ERROR, "Invalid reaction type %d for alert %s (while writing database).", alert->reaction, iter_key(it));
4729 break;
4730 }
4731 if (reaction) saxdb_write_string(ctx, KEY_REACTION, reaction);
4732 saxdb_end_record(ctx);
4733 }
4734 saxdb_end_record(ctx);
4735 }
4736 /* max clients */
4737 saxdb_start_record(ctx, KEY_MAX_CLIENTS, 0);
4738 saxdb_write_int(ctx, KEY_MAX, max_clients);
4739 saxdb_write_int(ctx, KEY_TIME, max_clients_time);
4740 saxdb_end_record(ctx);
4741 return 0;
4742 }
4743
4744 static int
4745 query_keys_helper(const char *key, UNUSED_ARG(void *data), void *extra)
4746 {
4747 send_message_type(4, extra, opserv, "$b%s$b", key);
4748 return 0;
4749 }
4750
4751 static MODCMD_FUNC(cmd_query)
4752 {
4753 struct record_data *rd;
4754 unsigned int i;
4755 char *nodename;
4756
4757 if (argc < 2) {
4758 reply("OSMSG_OPTION_ROOT");
4759 conf_enum_root(query_keys_helper, user);
4760 return 1;
4761 }
4762
4763 nodename = unsplit_string(argv+1, argc-1, NULL);
4764 if (!(rd = conf_get_node(nodename))) {
4765 reply("OSMSG_UNKNOWN_OPTION", nodename);
4766 return 0;
4767 }
4768
4769 if (rd->type == RECDB_QSTRING)
4770 reply("OSMSG_OPTION_IS", nodename, rd->d.qstring);
4771 else if (rd->type == RECDB_STRING_LIST) {
4772 reply("OSMSG_OPTION_LIST", nodename);
4773 if (rd->d.slist->used)
4774 for (i=0; i<rd->d.slist->used; i++)
4775 send_message_type(4, user, cmd->parent->bot, "$b%s$b", rd->d.slist->list[i]);
4776 else
4777 reply("OSMSG_OPTION_LIST_EMPTY");
4778 } else if (rd->type == RECDB_OBJECT) {
4779 reply("OSMSG_OPTION_KEYS", nodename);
4780 dict_foreach(rd->d.object, query_keys_helper, user);
4781 }
4782
4783 return 1;
4784 }
4785
4786 static MODCMD_FUNC(cmd_set)
4787 {
4788 struct record_data *rd;
4789
4790 /* I originally wanted to be able to fully manipulate the config
4791 db with this, but i wussed out. feel free to fix this - you'll
4792 need to handle quoted strings which have been split, and likely
4793 invent a syntax for it. -Zoot */
4794
4795 if (!(rd = conf_get_node(argv[1]))) {
4796 reply("OSMSG_SET_NOT_SET", argv[1]);
4797 return 0;
4798 }
4799
4800 if (rd->type != RECDB_QSTRING) {
4801 reply("OSMSG_SET_BAD_TYPE", argv[1]);
4802 return 0;
4803 }
4804
4805 free(rd->d.qstring);
4806 rd->d.qstring = strdup(argv[2]);
4807 conf_call_reload_funcs();
4808 reply("OSMSG_SET_SUCCESS", argv[1], argv[2]);
4809 return 1;
4810 }
4811
4812 static MODCMD_FUNC(cmd_settime)
4813 {
4814 const char *srv_name_mask = "*";
4815 time_t new_time = now;
4816
4817 if (argc > 1)
4818 srv_name_mask = argv[1];
4819 if (argc > 2)
4820 new_time = time(NULL);
4821 irc_settime(srv_name_mask, new_time);
4822 reply("OSMSG_SETTIME_SUCCESS", srv_name_mask);
4823 return 1;
4824 }
4825
4826 static discrim_t
4827 opserv_discrim_create(struct userNode *user, struct userNode *bot, unsigned int argc, char *argv[], int allow_channel)
4828 {
4829 unsigned int i, j;
4830 discrim_t discrim;
4831
4832 discrim = calloc(1, sizeof(*discrim));
4833 discrim->limit = 250;
4834 discrim->max_level = ~0;
4835 discrim->max_ts = INT_MAX;
4836 discrim->domain_depth = 2;
4837 discrim->max_channels = INT_MAX;
4838 discrim->authed = -1;
4839 discrim->info_space = -1;
4840 discrim->intra_dcmp = 0;
4841 discrim->intra_scmp = 0;
4842 discrim->use_regex = 0;
4843 discrim->silent = 0;
4844
4845 for (i=0; i<argc; i++) {
4846 if (irccasecmp(argv[i], "log") == 0) {
4847 discrim->option_log = 1;
4848 continue;
4849 }
4850 /* Assume all other criteria require arguments. */
4851 if (i == argc - 1) {
4852 send_message(user, bot, "MSG_MISSING_PARAMS", argv[i]);
4853 goto fail;
4854 }
4855 if (argv[i+1][0] == '&') {
4856 /* Looking for intra-userNode matches */
4857 char *tmp = &(argv[i+1][1]);
4858 if (strcasecmp(tmp, argv[i]) != 0) { /* Don't allow "nick &nick" etc */
4859 if (!strcasecmp(tmp, "nick"))
4860 discrim->intra_dcmp = 1;
4861 else if (!strcasecmp(tmp, "ident"))
4862 discrim->intra_dcmp = 2;
4863 else if (!strcasecmp(tmp, "info"))
4864 discrim->intra_dcmp = 3;
4865 }
4866 }
4867 if (irccasecmp(argv[i], "mask") == 0) {
4868 if (!is_ircmask(argv[++i])) {
4869 send_message(user, bot, "OSMSG_INVALID_IRCMASK", argv[i]);
4870 goto fail;
4871 }
4872 if (!split_ircmask(argv[i],
4873 &discrim->mask_nick,
4874 &discrim->mask_ident,
4875 &discrim->mask_host)) {
4876 send_message(user, bot, "OSMSG_INVALID_IRCMASK", argv[i]);
4877 goto fail;
4878 }
4879 } else if (irccasecmp(argv[i], "nick") == 0) {
4880 i++;
4881 if (discrim->intra_dcmp > 0)
4882 discrim->intra_scmp = 1;
4883 else
4884 discrim->mask_nick = argv[i];
4885 } else if (irccasecmp(argv[i], "ident") == 0) {
4886 i++;
4887 if (discrim->intra_dcmp > 0)
4888 discrim->intra_scmp = 2;
4889 else
4890 discrim->mask_ident = argv[i];
4891 } else if (irccasecmp(argv[i], "host") == 0) {
4892 discrim->mask_host = argv[++i];
4893 } else if (irccasecmp(argv[i], "info") == 0) {
4894 i++;
4895 if (discrim->intra_dcmp > 0)
4896 discrim->intra_scmp = 3;
4897 else
4898 discrim->mask_info = argv[i];
4899 } else if (irccasecmp(argv[i], "server") == 0) {
4900 discrim->server = argv[++i];
4901 } else if (irccasecmp(argv[i], "ip") == 0) {
4902 j = irc_pton(&discrim->ip_mask, &discrim->ip_mask_bits, argv[++i]);
4903 if (!j) {
4904 send_message(user, bot, "OSMSG_BAD_IP", argv[i]);
4905 goto fail;
4906 }
4907 } else if (irccasecmp(argv[i], "account") == 0) {
4908 if (discrim->authed == 0) {
4909 send_message(user, bot, "OSMSG_ACCOUNTMASK_AUTHED");
4910 goto fail;
4911 }
4912 discrim->accountmask = argv[++i];
4913 discrim->authed = 1;
4914 } else if (irccasecmp(argv[i], "authed") == 0) {
4915 i++; /* true_string and false_string are macros! */
4916 if (true_string(argv[i])) {
4917 discrim->authed = 1;
4918 } else if (false_string(argv[i])) {
4919 if (discrim->accountmask) {
4920 send_message(user, bot, "OSMSG_ACCOUNTMASK_AUTHED");
4921 goto fail;
4922 }
4923 discrim->authed = 0;
4924 } else {
4925 send_message(user, bot, "MSG_INVALID_BINARY", argv[i]);
4926 goto fail;
4927 }
4928 } else if (irccasecmp(argv[i], "info_space") == 0) {
4929 /* XXX: A hack because you can't check explicitly for a space through
4930 * any other means */
4931 i++;
4932 if (true_string(argv[i])) {
4933 discrim->info_space = 1;
4934 } else if (false_string(argv[i])) {
4935 discrim->info_space = 0;
4936 } else {
4937 send_message(user, bot, "MSG_INVALID_BINARY", argv[i]);
4938 goto fail;
4939 }
4940 } else if (irccasecmp(argv[i], "regex") == 0) {
4941 i++;
4942 if (true_string(argv[i])) {
4943 discrim->use_regex = 1;
4944 } else if (false_string(argv[i])) {
4945 discrim->use_regex = 0;
4946 } else {
4947 send_message(user, bot, "MSG_INVALID_BINARY", argv[i]);
4948 goto fail;
4949 }
4950 } else if (irccasecmp(argv[i], "silent") == 0) {
4951 i++;
4952 if(user != opserv && !oper_has_access(user, opserv, opserv_conf.silent_level, 0)) {
4953 goto fail;
4954 } else if (true_string(argv[i])) {
4955 discrim->silent = 1;
4956 } else if (false_string(argv[i])) {
4957 discrim->silent = 0;
4958 } else {
4959 send_message(user, bot, "MSG_INVALID_BINARY", argv[i]);
4960 goto fail;
4961 }
4962 } else if (irccasecmp(argv[i], "duration") == 0) {
4963 discrim->duration = ParseInterval(argv[++i]);
4964 } else if (irccasecmp(argv[i], "channel") == 0) {
4965 for (j=0, i++; ; j++) {
4966 switch (argv[i][j]) {
4967 case '#':
4968 goto find_channel;
4969 case '-':
4970 discrim->chan_no_modes |= MODE_CHANOP | MODE_HALFOP | MODE_VOICE;
4971 break;
4972 case '+':
4973 discrim->chan_req_modes |= MODE_VOICE;
4974 discrim->chan_no_modes |= MODE_CHANOP;
4975 discrim->chan_no_modes |= MODE_HALFOP;
4976 break;
4977 case '%':
4978 discrim->chan_req_modes |= MODE_HALFOP;
4979 discrim->chan_no_modes |= MODE_CHANOP;
4980 discrim->chan_no_modes |= MODE_VOICE;
4981 break;
4982 case '@':
4983 discrim->chan_req_modes |= MODE_CHANOP;
4984 break;
4985 case '\0':
4986 send_message(user, bot, "MSG_NOT_CHANNEL_NAME");
4987 goto fail;
4988 }
4989 }
4990 find_channel:
4991 discrim->chan_no_modes &= ~discrim->chan_req_modes;
4992 if (!(discrim->channel = GetChannel(argv[i]+j))) {
4993 /* secretly "allow_channel" now means "if a channel name is
4994 * specified, require that it currently exist" */
4995 if (allow_channel) {
4996 send_message(user, bot, "MSG_CHANNEL_UNKNOWN", argv[i]);
4997 goto fail;
4998 } else {
4999 discrim->channel = AddChannel(argv[i]+j, now, NULL, NULL, NULL);
5000 }
5001 }
5002 LockChannel(discrim->channel);
5003 } else if (irccasecmp(argv[i], "numchannels") == 0) {
5004 discrim->min_channels = discrim->max_channels = strtoul(argv[++i], NULL, 10);
5005 } else if (irccasecmp(argv[i], "limit") == 0) {
5006 discrim->limit = strtoul(argv[++i], NULL, 10);
5007 } else if (irccasecmp(argv[i], "reason") == 0) {
5008 discrim->reason = strdup(unsplit_string(argv+i+1, argc-i-1, NULL));
5009 i = argc;
5010 } else if (irccasecmp(argv[i], "last") == 0) {
5011 discrim->min_ts = now - ParseInterval(argv[++i]);
5012 } else if ((irccasecmp(argv[i], "linked") == 0)
5013 || (irccasecmp(argv[i], "nickage") == 0)) {
5014 const char *cmp = argv[++i];
5015 if (cmp[0] == '<') {
5016 if (cmp[1] == '=') {
5017 discrim->min_ts = now - ParseInterval(cmp+2);
5018 } else {
5019 discrim->min_ts = now - (ParseInterval(cmp+1) - 1);
5020 }
5021 } else if (cmp[0] == '>') {
5022 if (cmp[1] == '=') {
5023 discrim->max_ts = now - ParseInterval(cmp+2);
5024 } else {
5025 discrim->max_ts = now - (ParseInterval(cmp+1) - 1);
5026 }
5027 } else {
5028 discrim->min_ts = now - ParseInterval(cmp+2);
5029 }
5030 } else if (irccasecmp(argv[i], "access") == 0) {
5031 const char *cmp = argv[++i];
5032 if (cmp[0] == '<') {
5033 if (discrim->min_level == 0) discrim->min_level = 1;
5034 if (cmp[1] == '=') {
5035 discrim->max_level = strtoul(cmp+2, NULL, 0);
5036 } else {
5037 discrim->max_level = strtoul(cmp+1, NULL, 0) - 1;
5038 }
5039 } else if (cmp[0] == '=') {
5040 discrim->min_level = discrim->max_level = strtoul(cmp+1, NULL, 0);
5041 } else if (cmp[0] == '>') {
5042 if (cmp[1] == '=') {
5043 discrim->min_level = strtoul(cmp+2, NULL, 0);
5044 } else {
5045 discrim->min_level = strtoul(cmp+1, NULL, 0) + 1;
5046 }
5047 } else {
5048 discrim->min_level = strtoul(cmp+2, NULL, 0);
5049 }
5050 } else if ((irccasecmp(argv[i], "abuse") == 0)
5051 && (irccasecmp(argv[++i], "opers") == 0)) {
5052 discrim->match_opers = 1;
5053 } else if (irccasecmp(argv[i], "depth") == 0) {
5054 discrim->domain_depth = strtoul(argv[++i], NULL, 0);
5055 } else if (irccasecmp(argv[i], "clones") == 0) {
5056 discrim->min_clones = strtoul(argv[++i], NULL, 0);
5057 } else {
5058 send_message(user, bot, "MSG_INVALID_CRITERIA", argv[i]);
5059 goto fail;
5060 }
5061 }
5062
5063 if (discrim->mask_nick && !strcmp(discrim->mask_nick, "*")) {
5064 discrim->mask_nick = 0;
5065 }
5066 if (discrim->mask_ident && !strcmp(discrim->mask_ident, "*")) {
5067 discrim->mask_ident = 0;
5068 }
5069 if (discrim->mask_info && !strcmp(discrim->mask_info, "*")) {
5070 discrim->mask_info = 0;
5071 }
5072 if (discrim->mask_host && !discrim->mask_host[strspn(discrim->mask_host, "*.")]) {
5073 discrim->mask_host = 0;
5074 }
5075
5076 if(discrim->use_regex)
5077 {
5078 if(discrim->mask_nick)
5079 {
5080 int err = regcomp(&discrim->regex_nick, discrim->mask_nick, REG_EXTENDED|REG_ICASE|REG_NOSUB);
5081 discrim->has_regex_nick = !err;
5082 if(err)
5083 {
5084 char buff[256];
5085 buff[regerror(err, &discrim->regex_nick, buff, sizeof(buff))] = 0;
5086
5087 send_message(user, bot, "OSMSG_INVALID_REGEX", discrim->mask_nick, buff, err);
5088 goto regfail;
5089 }
5090 }
5091
5092 if(discrim->mask_ident)
5093 {
5094 int err = regcomp(&discrim->regex_ident, discrim->mask_ident, REG_EXTENDED|REG_ICASE|REG_NOSUB);
5095 discrim->has_regex_ident = !err;
5096 if(err)
5097 {
5098 char buff[256];
5099 buff[regerror(err, &discrim->regex_ident, buff, sizeof(buff))] = 0;
5100
5101 send_message(user, bot, "OSMSG_INVALID_REGEX", discrim->mask_ident, buff, err);
5102 goto regfail;
5103 }
5104 }
5105
5106 if(discrim->mask_host)
5107 {
5108 int err = regcomp(&discrim->regex_host, discrim->mask_host, REG_EXTENDED|REG_ICASE|REG_NOSUB);
5109 discrim->has_regex_host = !err;
5110 if(err)
5111 {
5112 char buff[256];
5113 buff[regerror(err, &discrim->regex_host, buff, sizeof(buff))] = 0;
5114
5115 send_message(user, bot, "OSMSG_INVALID_REGEX", discrim->mask_host, buff, err);
5116 goto regfail;
5117 }
5118 }
5119
5120 if(discrim->mask_info)
5121 {
5122 int err = regcomp(&discrim->regex_info, discrim->mask_info, REG_EXTENDED|REG_ICASE|REG_NOSUB);
5123 discrim->has_regex_info = !err;
5124 if(err)
5125 {
5126 char buff[256];
5127 buff[regerror(err, &discrim->regex_info, buff, sizeof(buff))] = 0;
5128
5129 send_message(user, bot, "OSMSG_INVALID_REGEX", discrim->mask_info, buff, err);
5130 goto regfail;
5131 }
5132 }
5133 }
5134
5135 return discrim;
5136
5137 fail:
5138 free(discrim);
5139 return NULL;
5140
5141 regfail:
5142 if(discrim->has_regex_nick)
5143 regfree(&discrim->regex_nick);
5144 if(discrim->has_regex_ident)
5145 regfree(&discrim->regex_ident);
5146 if(discrim->has_regex_host)
5147 regfree(&discrim->regex_host);
5148 if(discrim->has_regex_info)
5149 regfree(&discrim->regex_info);
5150
5151 free(discrim);
5152 return NULL;
5153 }
5154
5155 static int
5156 discrim_match(discrim_t discrim, struct userNode *user)
5157 {
5158 unsigned int access;
5159 char *scmp=NULL, *dcmp=NULL;
5160
5161 if ((user->timestamp < discrim->min_ts)
5162 || (user->timestamp > discrim->max_ts)
5163 || (user->channels.used < discrim->min_channels)
5164 || (user->channels.used > discrim->max_channels)
5165 || (discrim->authed == 0 && user->handle_info)
5166 || (discrim->authed == 1 && !user->handle_info)
5167 || (discrim->info_space == 0 && user->info[0] == ' ')
5168 || (discrim->info_space == 1 && user->info[0] != ' ')
5169 || (discrim->server && !match_ircglob(user->uplink->name, discrim->server))
5170 || (discrim->accountmask && (!user->handle_info || !match_ircglob(user->handle_info->handle, discrim->accountmask)))
5171 || (discrim->ip_mask_bits && !irc_check_mask(&user->ip, &discrim->ip_mask, discrim->ip_mask_bits))
5172 )
5173 return 0;
5174
5175 if (discrim->channel && !GetUserMode(discrim->channel, user))
5176 return 0;
5177
5178 if(discrim->use_regex)
5179 {
5180 if((discrim->has_regex_nick && regexec(&discrim->regex_nick, user->nick, 0, 0, 0))
5181 || (discrim->has_regex_ident && regexec(&discrim->regex_ident, user->ident, 0, 0, 0))
5182 || (discrim->has_regex_host && regexec(&discrim->regex_host, user->hostname, 0, 0, 0))
5183 || (discrim->has_regex_info && regexec(&discrim->regex_info, user->info, 0, 0, 0))) {
5184 return 0;
5185 }
5186 }
5187 else
5188 {
5189 if ((discrim->mask_nick && !match_ircglob(user->nick, discrim->mask_nick))
5190 || (discrim->mask_ident && !match_ircglob(user->ident, discrim->mask_ident))
5191 || (discrim->mask_host && !match_ircglob(user->hostname, discrim->mask_host))
5192 || (discrim->mask_info && !match_ircglob(user->info, discrim->mask_info))) {
5193 return 0;
5194 }
5195 }
5196
5197 if ((discrim->intra_scmp > 0 && discrim->intra_dcmp > 0)) {
5198 switch(discrim->intra_scmp) {
5199 case 1: scmp=user->nick; break;
5200 case 2: scmp=user->ident; break;
5201 case 3:
5202 scmp=user->info;
5203 if (discrim->info_space == 1) scmp++;
5204 break;
5205 }
5206 switch(discrim->intra_dcmp) {
5207 case 1: dcmp=user->nick; break;
5208 case 2: dcmp=user->ident; break;
5209 case 3: /* When checking INFO, and info_space is enabled
5210 * ignore the first character in a search
5211 * XXX: Should we ignore ALL leading whitespace?
5212 * Also, what about ignoring ~ in ident?
5213 */
5214 dcmp=user->info;
5215 if (discrim->info_space == 1) dcmp++;
5216 break;
5217 }
5218 if (irccasecmp(scmp,dcmp))
5219 return 0;
5220 }
5221
5222 access = user->handle_info ? user->handle_info->opserv_level : 0;
5223 if ((access < discrim->min_level)
5224 || (access > discrim->max_level)) {
5225 return 0;
5226 }
5227 if (discrim->min_clones > 1) {
5228 struct opserv_hostinfo *ohi = dict_find(opserv_hostinfo_dict, irc_ntoa(&user->ip), NULL);
5229 if (!ohi || (ohi->clients.used < discrim->min_clones))
5230 return 0;
5231 }
5232 return 1;
5233 }
5234
5235 static unsigned int
5236 opserv_discrim_search(discrim_t discrim, discrim_search_func dsf, void *data)
5237 {
5238 unsigned int nn, count;
5239 struct userList matched;
5240
5241 userList_init(&matched);
5242 /* Try most optimized search methods first */
5243 if (discrim->channel) {
5244 for (nn=0;
5245 (nn < discrim->channel->members.used)
5246 && (matched.used < discrim->limit);
5247 nn++) {
5248 struct modeNode *mn = discrim->channel->members.list[nn];
5249 if (((mn->modes & discrim->chan_req_modes) != discrim->chan_req_modes)
5250 || ((mn->modes & discrim->chan_no_modes) != 0)) {
5251 continue;
5252 }
5253 if (discrim_match(discrim, mn->user)) {
5254 userList_append(&matched, mn->user);
5255 }
5256 }
5257 } else if (discrim->ip_mask_bits == 128) {
5258 struct opserv_hostinfo *ohi = dict_find(opserv_hostinfo_dict, irc_ntoa(&discrim->ip_mask), NULL);
5259 if (!ohi) {
5260 userList_clean(&matched);
5261 return 0;
5262 }
5263 for (nn=0; (nn<ohi->clients.used) && (matched.used < discrim->limit); nn++) {
5264 if (discrim_match(discrim, ohi->clients.list[nn])) {
5265 userList_append(&matched, ohi->clients.list[nn]);
5266 }
5267 }
5268 } else {
5269 dict_iterator_t it;
5270 for (it=dict_first(clients); it && (matched.used < discrim->limit); it=iter_next(it)) {
5271 if (discrim_match(discrim, iter_data(it))) {
5272 userList_append(&matched, iter_data(it));
5273 }
5274 }
5275 }
5276
5277 if (!matched.used) {
5278 userList_clean(&matched);
5279 return 0;
5280 }
5281
5282 if (discrim->option_log) {
5283 log_module(OS_LOG, LOG_INFO, "Logging matches for search:");
5284 }
5285 for (nn=0; nn<matched.used; nn++) {
5286 struct userNode *user = matched.list[nn];
5287 if (discrim->option_log) {
5288 log_module(OS_LOG, LOG_INFO, " %s!%s@%s", user->nick, user->ident, user->hostname);
5289 }
5290 if (dsf(user, data)) {
5291 /* If a search function returns true, it ran into a
5292 problem. Stop going through the list. */
5293 break;
5294 }
5295 }
5296 if (discrim->option_log) {
5297 log_module(OS_LOG, LOG_INFO, "End of matching users.");
5298 }
5299 count = matched.used;
5300 userList_clean(&matched);
5301 return count;
5302 }
5303
5304 static int
5305 trace_print_func(struct userNode *match, void *extra)
5306 {
5307 struct discrim_and_source *das = extra;
5308 if (match->handle_info) {
5309 send_message_type(4, das->source, das->destination, "%-15s\002 \002%10s\002@\002%s (%s)", match->nick, match->ident, match->hostname, match->handle_info->handle);
5310 } else {
5311 send_message_type(4, das->source, das->destination, "%-15s\002 \002%10s\002@\002%s", match->nick, match->ident, match->hostname);
5312 }
5313 return 0;
5314 }
5315
5316 static int
5317 trace_count_func(UNUSED_ARG(struct userNode *match), UNUSED_ARG(void *extra))
5318 {
5319 return 0;
5320 }
5321
5322 static int
5323 is_oper_victim(struct userNode *user, struct userNode *target, int match_opers)
5324 {
5325 return !(IsService(target)
5326 || (!match_opers && IsOper(target))
5327 || (target->handle_info
5328 && target->handle_info->opserv_level > user->handle_info->opserv_level));
5329 }
5330
5331 static int
5332 trace_gline_func(struct userNode *match, void *extra)
5333 {
5334 struct discrim_and_source *das = extra;
5335
5336 if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
5337 opserv_block(match, das->source->handle_info->handle, das->discrim->reason, das->discrim->duration, das->discrim->silent);
5338 }
5339
5340 return 0;
5341 }
5342
5343 static int
5344 trace_shun_func(struct userNode *match, void *extra)
5345 {
5346 struct discrim_and_source *das = extra;
5347
5348 if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
5349 opserv_shun(match, das->source->handle_info->handle, das->discrim->reason, das->discrim->duration);
5350 }
5351
5352 return 0;
5353 }
5354
5355 static int
5356 trace_kill_func(struct userNode *match, void *extra)
5357 {
5358 struct discrim_and_source *das = extra;
5359
5360 if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
5361 char *reason;
5362 if (das->discrim->reason) {
5363 reason = das->discrim->reason;
5364 } else {
5365 reason = alloca(strlen(OSMSG_KILL_REQUESTED)+strlen(das->source->nick)+1);
5366 sprintf(reason, OSMSG_KILL_REQUESTED, das->source->nick);
5367 }
5368 DelUser(match, opserv, 1, reason);
5369 }
5370
5371 return 0;
5372 }
5373
5374 static int
5375 is_gagged(char *mask)
5376 {
5377 struct gag_entry *gag;
5378
5379 for (gag = gagList; gag; gag = gag->next) {
5380 if (match_ircglobs(gag->mask, mask)) return 1;
5381 }
5382 return 0;
5383 }
5384
5385 static int
5386 trace_gag_func(struct userNode *match, void *extra)
5387 {
5388 struct discrim_and_source *das = extra;
5389
5390 if (is_oper_victim(das->source, match, das->discrim->match_opers)) {
5391 char *reason, *mask;
5392 int masksize;
5393 if (das->discrim->reason) {
5394 reason = das->discrim->reason;
5395 } else {
5396 reason = alloca(strlen(OSMSG_GAG_REQUESTED)+strlen(das->source->nick)+1);
5397 sprintf(reason, OSMSG_GAG_REQUESTED, das->source->nick);
5398 }
5399 masksize = 5+strlen(match->hostname);
5400 mask = alloca(masksize);
5401 snprintf(mask, masksize, "*!*@%s", match->hostname);
5402 if (!is_gagged(mask)) {
5403 gag_create(mask, das->source->handle_info->handle, reason,
5404 das->discrim->duration ? (now + das->discrim->duration) : 0);
5405 }
5406 }
5407
5408 return 0;
5409 }
5410
5411 static int
5412 trace_domains_func(struct userNode *match, void *extra)
5413 {
5414 struct discrim_and_source *das = extra;
5415 irc_in_addr_t ip;
5416 unsigned long *count;
5417 unsigned int depth;
5418 char *hostname;
5419 char ipmask[IRC_NTOP_MASK_MAX_SIZE];
5420
5421 if (irc_pton(&ip, NULL, match->hostname)) {
5422 if (irc_in_addr_is_ipv4(ip)) {
5423 unsigned long matchip = ntohl(ip.in6_32[3]);
5424 /* raw IP address.. use up to first three octets of IP */
5425 switch (das->discrim->domain_depth) {
5426 default:
5427 snprintf(ipmask, sizeof(ipmask), "%lu.%lu.%lu.*", (matchip>>24)&255, (matchip>>16)&255, (matchip>>8)&255);
5428 break;
5429 case 2:
5430 snprintf(ipmask, sizeof(ipmask), "%lu.%lu.*", (matchip>>24)&255, (matchip>>16)&255);
5431 break;
5432 case 1:
5433 snprintf(ipmask, sizeof(ipmask), "%lu.*", (matchip>>24)&255);
5434 break;
5435 }
5436 } else if (irc_in_addr_is_ipv6(ip)) {
5437 switch (das->discrim->domain_depth) {
5438 case 1: depth = 16; goto ipv6_pfx;
5439 case 2: depth = 24; goto ipv6_pfx;
5440 case 3: depth = 32; goto ipv6_pfx;
5441 default: depth = das->discrim->domain_depth;
5442 ipv6_pfx:
5443 irc_ntop_mask(ipmask, sizeof(ipmask), &ip, depth);
5444 }
5445 } else safestrncpy(ipmask, match->hostname, sizeof(ipmask));
5446 ipmask[sizeof(ipmask) - 1] = '\0';
5447 hostname = ipmask;
5448 } else {
5449 hostname = match->hostname + strlen(match->hostname);
5450 for (depth=das->discrim->domain_depth;
5451 depth && (hostname > match->hostname);
5452 depth--) {
5453 hostname--;
5454 while ((hostname > match->hostname) && (*hostname != '.')) hostname--;
5455 }
5456 if (*hostname == '.') hostname++; /* advance past last dot we saw */
5457 }
5458 if (!(count = dict_find(das->dict, hostname, NULL))) {
5459 count = calloc(1, sizeof(*count));
5460 dict_insert(das->dict, strdup(hostname), count);
5461 }
5462 (*count)++;
5463 return 0;
5464 }
5465
5466 static int
5467 opserv_show_hostinfo(const char *key, void *data, void *extra)
5468 {
5469 unsigned long *count = data;
5470 struct discrim_and_source *das = extra;
5471
5472 send_message_type(4, das->source, das->destination, "%s %lu", key, *count);
5473 return !--das->disp_limit;
5474 }
5475
5476 static MODCMD_FUNC(cmd_trace)
5477 {
5478 struct discrim_and_source das;
5479 discrim_search_func action;
5480 unsigned int matches;
5481 struct svccmd *subcmd;
5482 char buf[MAXLEN];
5483
5484 sprintf(buf, "trace %s", argv[1]);
5485 if (!(subcmd = dict_find(opserv_service->commands, buf, NULL))) {
5486 reply("OSMSG_BAD_ACTION", argv[1]);
5487 return 0;
5488 }
5489 if (!svccmd_can_invoke(user, opserv_service->bot, subcmd, channel, SVCCMD_NOISY))
5490 return 0;
5491 if (!irccasecmp(argv[1], "print"))
5492 action = trace_print_func;
5493 else if (!irccasecmp(argv[1], "count"))
5494 action = trace_count_func;
5495 else if (!irccasecmp(argv[1], "domains"))
5496 action = trace_domains_func;
5497 else if (!irccasecmp(argv[1], "gline"))
5498 action = trace_gline_func;
5499 else if (!irccasecmp(argv[1], "shun"))
5500 action = trace_shun_func;
5501 else if (!irccasecmp(argv[1], "kill"))
5502 action = trace_kill_func;
5503 else if (!irccasecmp(argv[1], "gag"))
5504 action = trace_gag_func;
5505 else {
5506 reply("OSMSG_BAD_ACTION", argv[1]);
5507 return 0;
5508 }
5509
5510 if (user->handle_info->opserv_level < subcmd->min_opserv_level) {
5511 reply("OSMSG_LEVEL_TOO_LOW");
5512 return 0;
5513 }
5514
5515 das.dict = NULL;
5516 das.source = user;
5517 das.destination = cmd->parent->bot;
5518 das.discrim = opserv_discrim_create(user, cmd->parent->bot, argc-2, argv+2, 1);
5519 if (!das.discrim)
5520 return 0;
5521
5522 if (action == trace_print_func)
5523 {
5524 reply("OSMSG_USER_SEARCH_RESULTS");
5525 reply("OSMSG_USER_SEARCH_BAR");
5526 reply("OSMSG_USER_SEARCH_HEADER");
5527 reply("OSMSG_USER_SEARCH_BAR");
5528 }
5529 else if (action == trace_count_func)
5530 das.discrim->limit = INT_MAX;
5531 else if ((action == trace_gline_func) && !das.discrim->duration)
5532 das.discrim->duration = opserv_conf.block_gline_duration;
5533 else if ((action == trace_shun_func) && !das.discrim->duration)
5534 das.discrim->duration = opserv_conf.block_shun_duration;
5535 else if (action == trace_domains_func) {
5536 das.dict = dict_new();
5537 dict_set_free_data(das.dict, free);
5538 dict_set_free_keys(das.dict, free);
5539 das.disp_limit = das.discrim->limit;
5540 das.discrim->limit = INT_MAX;
5541 }
5542 matches = opserv_discrim_search(das.discrim, action, &das);
5543
5544 if (action == trace_domains_func)
5545 dict_foreach(das.dict, opserv_show_hostinfo, &das);
5546
5547 if (matches)
5548 {
5549 if(action == trace_print_func)
5550 reply("OSMSG_USER_SEARCH_COUNT_BAR", matches);
5551 else
5552 reply("OSMSG_USER_SEARCH_COUNT", matches);
5553 }
5554 else
5555 reply("MSG_NO_MATCHES");
5556
5557 if (das.discrim->channel)
5558 UnlockChannel(das.discrim->channel);
5559 free(das.discrim->reason);
5560
5561 if(das.discrim->has_regex_nick)
5562 regfree(&das.discrim->regex_nick);
5563 if(das.discrim->has_regex_ident)
5564 regfree(&das.discrim->regex_ident);
5565 if(das.discrim->has_regex_host)
5566 regfree(&das.discrim->regex_host);
5567 if(das.discrim->has_regex_info)
5568 regfree(&das.discrim->regex_info);
5569
5570 free(das.discrim);
5571 dict_delete(das.dict);
5572 return 1;
5573 }
5574
5575 typedef void (*cdiscrim_search_func)(struct chanNode *match, void *data, struct userNode *bot);
5576
5577 typedef struct channel_discrim {
5578 char *name, *topic;
5579
5580 unsigned int min_users, max_users;
5581 time_t min_ts, max_ts;
5582 unsigned int limit;
5583 } *cdiscrim_t;
5584
5585 static cdiscrim_t opserv_cdiscrim_create(struct userNode *user, struct userNode *bot, unsigned int argc, char *argv[]);
5586 static unsigned int opserv_cdiscrim_search(cdiscrim_t discrim, cdiscrim_search_func dsf, void *data, struct userNode *bot);
5587
5588 static time_t
5589 smart_parse_time(const char *str) {
5590 /* If an interval-style string is given, treat as time before now.
5591 * If it's all digits, treat directly as a Unix timestamp. */
5592 return str[strspn(str, "0123456789")] ? (time_t)(now - ParseInterval(str)) : (time_t)atoi(str);
5593 }
5594
5595 static cdiscrim_t
5596 opserv_cdiscrim_create(struct userNode *user, struct userNode *bot, unsigned int argc, char *argv[])
5597 {
5598 cdiscrim_t discrim;
5599 unsigned int i;
5600
5601 discrim = calloc(1, sizeof(*discrim));
5602 discrim->limit = 25;
5603
5604 for (i = 0; i < argc; i++) {
5605 /* Assume all criteria require arguments. */
5606 if (i == (argc - 1)) {
5607 send_message(user, bot, "MSG_MISSING_PARAMS", argv[i]);
5608 return NULL;
5609 }
5610
5611 if (!irccasecmp(argv[i], "name"))
5612 discrim->name = argv[++i];
5613 else if (!irccasecmp(argv[i], "topic"))
5614 discrim->topic = argv[++i];
5615 else if (!irccasecmp(argv[i], "users")) {
5616 const char *cmp = argv[++i];
5617 if (cmp[0] == '<') {
5618 if (cmp[1] == '=')
5619 discrim->max_users = strtoul(cmp+2, NULL, 0);
5620 else
5621 discrim->max_users = strtoul(cmp+1, NULL, 0) - 1;
5622 } else if (cmp[0] == '=') {
5623 discrim->min_users = discrim->max_users = strtoul(cmp+1, NULL, 0);
5624 } else if (cmp[0] == '>') {
5625 if (cmp[1] == '=')
5626 discrim->min_users = strtoul(cmp+2, NULL, 0);
5627 else
5628 discrim->min_users = strtoul(cmp+1, NULL, 0) + 1;
5629 } else {
5630 discrim->min_users = strtoul(cmp+2, NULL, 0);
5631 }
5632 } else if (!irccasecmp(argv[i], "timestamp")) {
5633 const char *cmp = argv[++i];
5634 if (cmp[0] == '<') {
5635 if (cmp[1] == '=')
5636 discrim->max_ts = smart_parse_time(cmp+2);
5637 else
5638 discrim->max_ts = smart_parse_time(cmp+1)-1;
5639 } else if (cmp[0] == '=') {
5640 discrim->min_ts = discrim->max_ts = smart_parse_time(cmp+1);
5641 } else if (cmp[0] == '>') {
5642 if (cmp[1] == '=')
5643 discrim->min_ts = smart_parse_time(cmp+2);
5644 else
5645 discrim->min_ts = smart_parse_time(cmp+1)+1;
5646 } else {
5647 discrim->min_ts = smart_parse_time(cmp);
5648 }
5649 } else if (!irccasecmp(argv[i], "limit")) {
5650 discrim->limit = strtoul(argv[++i], NULL, 10);
5651 } else {
5652 send_message(user, bot, "MSG_INVALID_CRITERIA", argv[i]);
5653 goto fail;
5654 }
5655 }
5656
5657 if (discrim->name && !strcmp(discrim->name, "*"))
5658 discrim->name = 0;
5659 if (discrim->topic && !strcmp(discrim->topic, "*"))
5660 discrim->topic = 0;
5661
5662 return discrim;
5663 fail:
5664 free(discrim);
5665 return NULL;
5666 }
5667
5668 static int
5669 cdiscrim_match(cdiscrim_t discrim, struct chanNode *chan)
5670 {
5671 if ((discrim->name && !match_ircglob(chan->name, discrim->name)) ||
5672 (discrim->topic && !match_ircglob(chan->topic, discrim->topic)) ||
5673 (discrim->min_users && chan->members.used < discrim->min_users) ||
5674 (discrim->max_users && chan->members.used > discrim->max_users) ||
5675 (discrim->min_ts && chan->timestamp < discrim->min_ts) ||
5676 (discrim->max_ts && chan->timestamp > discrim->max_ts)) {
5677 return 0;
5678 }
5679 return 1;
5680 }
5681
5682 static unsigned int opserv_cdiscrim_search(cdiscrim_t discrim, cdiscrim_search_func dsf, void *data, struct userNode *bot)
5683 {
5684 unsigned int count = 0;
5685 dict_iterator_t it, next;
5686
5687 for (it = dict_first(channels); it && count < discrim->limit ; it = next) {
5688 struct chanNode *chan = iter_data(it);
5689
5690 /* Hold on to the next channel in case we decide to
5691 add actions that destructively modify the channel. */
5692 next = iter_next(it);
5693 if ((chan->members.used > 0) && cdiscrim_match(discrim, chan)) {
5694 dsf(chan, data, bot);
5695 count++;
5696 }
5697 }
5698
5699 return count;
5700 }
5701
5702 void channel_count(UNUSED_ARG(struct chanNode *channel), UNUSED_ARG(void *data), UNUSED_ARG(struct userNode *bot))
5703 {
5704 }
5705
5706 void channel_print(struct chanNode *channel, void *data, struct userNode *bot)
5707 {
5708 char modes[MAXLEN];
5709 irc_make_chanmode(channel, modes);
5710 send_message(data, bot, "OSMSG_CSEARCH_CHANNEL_INFO", channel->name, channel->members.used, modes, channel->topic);
5711 }
5712
5713 static MODCMD_FUNC(cmd_csearch)
5714 {
5715 cdiscrim_t discrim;
5716 unsigned int matches;
5717 cdiscrim_search_func action;
5718 struct svccmd *subcmd;
5719 char buf[MAXLEN];
5720
5721 if (!irccasecmp(argv[1], "count"))
5722 action = channel_count;
5723 else if (!irccasecmp(argv[1], "print"))
5724 action = channel_print;
5725 else {
5726 reply("OSMSG_BAD_ACTION", argv[1]);
5727 return 0;
5728 }
5729
5730 sprintf(buf, "%s %s", argv[0], argv[0]);
5731 if ((subcmd = dict_find(opserv_service->commands, buf, NULL))
5732 && !svccmd_can_invoke(user, opserv_service->bot, subcmd, channel, SVCCMD_NOISY)) {
5733 return 0;
5734 }
5735
5736 discrim = opserv_cdiscrim_create(user, cmd->parent->bot, argc - 2, argv + 2);
5737 if (!discrim)
5738 return 0;
5739
5740 if (action == channel_print)
5741 reply("OSMSG_CHANNEL_SEARCH_RESULTS");
5742 else if (action == channel_count)
5743 discrim->limit = INT_MAX;
5744
5745 matches = opserv_cdiscrim_search(discrim, action, user, cmd->parent->bot);
5746
5747 if (matches)
5748 reply("MSG_MATCH_COUNT", matches);
5749 else
5750 reply("MSG_NO_MATCHES");
5751
5752 free(discrim);
5753 return 1;
5754 }
5755
5756 static MODCMD_FUNC(cmd_gsync)
5757 {
5758 struct server *src;
5759 if (argc > 1) {
5760 src = GetServerH(argv[1]);
5761 if (!src) {
5762 reply("MSG_SERVER_UNKNOWN", argv[1]);
5763 return 0;
5764 }
5765 } else {
5766 src = self->uplink;
5767 }
5768 irc_stats(cmd->parent->bot, src, 'G');
5769 reply("OSMSG_GSYNC_RUNNING", src->name);
5770 return 1;
5771 }
5772
5773 static MODCMD_FUNC(cmd_ssync)
5774 {
5775 struct server *src;
5776 if (argc > 1) {
5777 src = GetServerH(argv[1]);
5778 if (!src) {
5779 reply("MSG_SERVER_UNKNOWN", argv[1]);
5780 return 0;
5781 }
5782 } else {
5783 src = self->uplink;
5784 }
5785 irc_stats(cmd->parent->bot, src, 'S');
5786 reply("OSMSG_SSYNC_RUNNING", src->name);
5787 return 1;
5788 }
5789
5790 struct gline_extra {
5791 struct userNode *user;
5792 struct string_list *glines;
5793 struct userNode *bot;
5794 };
5795
5796 static void
5797 gtrace_print_func(struct gline *gline, void *extra)
5798 {
5799 struct gline_extra *xtra = extra;
5800 char *when_text, set_text[20];
5801 strftime(set_text, sizeof(set_text), "%Y-%m-%d", localtime(&gline->issued));
5802 when_text = asctime(localtime(&gline->expires));
5803 when_text[strlen(when_text)-1] = 0; /* strip lame \n */
5804 send_message(xtra->user, xtra->bot, "OSMSG_GTRACE_FORMAT", gline->target, set_text, gline->issuer, when_text, gline->reason);
5805 }
5806
5807 static void
5808 gtrace_count_func(UNUSED_ARG(struct gline *gline), UNUSED_ARG(void *extra))
5809 {
5810 }
5811
5812 static void
5813 gtrace_ungline_func(struct gline *gline, void *extra)
5814 {
5815 struct gline_extra *xtra = extra;
5816 string_list_append(xtra->glines, strdup(gline->target));
5817 }
5818
5819 static MODCMD_FUNC(cmd_gtrace)
5820 {
5821 struct gline_discrim *discrim;
5822 gline_search_func action;
5823 unsigned int matches, nn;
5824 struct gline_extra extra;
5825 struct svccmd *subcmd;
5826 char buf[MAXLEN];
5827
5828 if (!irccasecmp(argv[1], "print"))
5829 action = gtrace_print_func;
5830 else if (!irccasecmp(argv[1], "count"))
5831 action = gtrace_count_func;
5832 else if (!irccasecmp(argv[1], "ungline"))
5833 action = gtrace_ungline_func;
5834 else {
5835 reply("OSMSG_BAD_ACTION", argv[1]);
5836 return 0;
5837 }
5838 sprintf(buf, "%s %s", argv[0], argv[0]);
5839 if ((subcmd = dict_find(opserv_service->commands, buf, NULL))
5840 && !svccmd_can_invoke(user, opserv_service->bot, subcmd, channel, SVCCMD_NOISY)) {
5841 return 0;
5842 }
5843
5844 discrim = gline_discrim_create(user, cmd->parent->bot, argc-2, argv+2);
5845 if (!discrim)
5846 return 0;
5847
5848 if (action == gtrace_print_func)
5849 reply("OSMSG_GLINE_SEARCH_RESULTS");
5850 else if (action == gtrace_count_func)
5851 discrim->limit = INT_MAX;
5852
5853 extra.user = user;
5854 extra.glines = alloc_string_list(4);
5855 extra.bot = cmd->parent->bot;
5856 matches = gline_discrim_search(discrim, action, &extra);
5857
5858 if (action == gtrace_ungline_func)
5859 for (nn=0; nn<extra.glines->used; nn++)
5860 gline_remove(extra.glines->list[nn], 1);
5861 free_string_list(extra.glines);
5862
5863 if (matches)
5864 reply("MSG_MATCH_COUNT", matches);
5865 else
5866 reply("MSG_NO_MATCHES");
5867 free(discrim->alt_target_mask);
5868 free(discrim);
5869 return 1;
5870 }
5871
5872 struct shun_extra {
5873 struct userNode *user;
5874 struct string_list *shuns;
5875 struct userNode *bot;
5876 };
5877
5878 static void
5879 strace_print_func(struct shun *shun, void *extra)
5880 {
5881 struct shun_extra *xtra = extra;
5882 char *when_text, set_text[20];
5883 strftime(set_text, sizeof(set_text), "%Y-%m-%d", localtime(&shun->issued));
5884 when_text = asctime(localtime(&shun->expires));
5885 when_text[strlen(when_text)-1] = 0; /* strip lame \n */
5886 send_message(xtra->user, xtra->bot, "OSMSG_STRACE_FORMAT", shun->target, set_text, shun->issuer, when_text, shun->reason);
5887 }
5888
5889 static void
5890 strace_count_func(UNUSED_ARG(struct shun *shun), UNUSED_ARG(void *extra))
5891 {
5892 }
5893
5894 static void
5895 strace_unshun_func(struct shun *shun, void *extra)
5896 {
5897 struct shun_extra *xtra = extra;
5898 string_list_append(xtra->shuns, strdup(shun->target));
5899 }
5900
5901 static MODCMD_FUNC(cmd_strace)
5902 {
5903 struct shun_discrim *discrim;
5904 shun_search_func action;
5905 unsigned int matches, nn;
5906 struct shun_extra extra;
5907 struct svccmd *subcmd;
5908 char buf[MAXLEN];
5909
5910 if (!irccasecmp(argv[1], "print"))
5911 action = strace_print_func;
5912 else if (!irccasecmp(argv[1], "count"))
5913 action = strace_count_func;
5914 else if (!irccasecmp(argv[1], "unshun"))
5915 action = strace_unshun_func;
5916 else {
5917 reply("OSMSG_BAD_ACTION", argv[1]);
5918 return 0;
5919 }
5920 sprintf(buf, "%s %s", argv[0], argv[0]);
5921 if ((subcmd = dict_find(opserv_service->commands, buf, NULL))
5922 && !svccmd_can_invoke(user, opserv_service->bot, subcmd, channel, SVCCMD_NOISY)) {
5923 return 0;
5924 }
5925
5926 discrim = shun_discrim_create(user, cmd->parent->bot, argc-2, argv+2);
5927 if (!discrim)
5928 return 0;
5929
5930 if (action == strace_print_func)
5931 reply("OSMSG_SHUN_SEARCH_RESULTS");
5932 else if (action == strace_count_func)
5933 discrim->limit = INT_MAX;
5934
5935 extra.user = user;
5936 extra.shuns = alloc_string_list(4);
5937 extra.bot = cmd->parent->bot;
5938 matches = shun_discrim_search(discrim, action, &extra);
5939
5940 if (action == strace_unshun_func)
5941 for (nn=0; nn<extra.shuns->used; nn++)
5942 shun_remove(extra.shuns->list[nn], 1);
5943 free_string_list(extra.shuns);
5944
5945 if (matches)
5946 reply("MSG_MATCH_COUNT", matches);
5947 else
5948 reply("MSG_NO_MATCHES");
5949 free(discrim->alt_target_mask);
5950 free(discrim);
5951 return 1;
5952 }
5953
5954 static int
5955 alert_check_user(const char *key, void *data, void *extra)
5956 {
5957 struct opserv_user_alert *alert = data;
5958 struct userNode *user = extra;
5959
5960 if (!discrim_match(alert->discrim, user))
5961 return 0;
5962
5963 if ((alert->reaction != REACT_NOTICE)
5964 && IsOper(user)
5965 && !alert->discrim->match_opers) {
5966 return 0;
5967 }
5968
5969 /* The user matches the alert criteria, so trigger the reaction. */
5970 if (alert->discrim->option_log)
5971 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);
5972
5973 /* Return 1 to halt alert matching, such as when killing the user
5974 that triggered the alert. */
5975 switch (alert->reaction) {
5976 case REACT_KILL:
5977 DelUser(user, opserv, 1, alert->discrim->reason);
5978 return 1;
5979 /*
5980 case REACT_SILENT:
5981 opserv_block(user, alert->owner, alert->discrim->reason, alert->discrim->duration, 1);
5982 return 1;
5983 */
5984 case REACT_GLINE:
5985 opserv_block(user, alert->owner, alert->discrim->reason, alert->discrim->duration, alert->discrim->silent);
5986 return 1;
5987 case REACT_SHUN:
5988 opserv_shun(user, alert->owner, alert->discrim->reason, alert->discrim->duration);
5989 return 1;
5990 default:
5991 log_module(OS_LOG, LOG_ERROR, "Invalid reaction type %d for alert %s.", alert->reaction, key);
5992 /* fall through to REACT_NOTICE case */
5993 case REACT_NOTICE:
5994 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);
5995 break;
5996 case REACT_TRACK:
5997 #ifdef HAVE_TRACK
5998 opserv_alert("Alert $b%s$b triggered by user $b%s$b!%s@%s (%s) (Tracking).", key, user->nick, user->ident, user->hostname, alert->discrim->reason);
5999 add_track_user(user);
6000 #endif
6001 break;
6002 }
6003 return 0;
6004 }
6005
6006 static void
6007 opserv_alert_check_nick(struct userNode *user, UNUSED_ARG(const char *old_nick))
6008 {
6009 struct gag_entry *gag;
6010 dict_foreach(opserv_nick_based_alerts, alert_check_user, user);
6011 /* Gag them if appropriate (and only if). */
6012 user->modes &= ~FLAGS_GAGGED;
6013 for (gag = gagList; gag; gag = gag->next) {
6014 if (user_matches_glob(user, gag->mask, MATCH_USENICK)) {
6015 gag_helper_func(user, NULL);
6016 break;
6017 }
6018 }
6019 }
6020
6021 static void
6022 opserv_staff_alert(struct userNode *user, UNUSED_ARG(struct handle_info *old_handle))
6023 {
6024 const char *type;
6025
6026 if (!opserv_conf.staff_auth_channel
6027 || user->uplink->burst
6028 || !user->handle_info)
6029 return;
6030 else if (user->handle_info->opserv_level)
6031 type = "OPER";
6032 else if (IsNetworkHelper(user))
6033 type = "NETWORK HELPER";
6034 else if (IsSupportHelper(user))
6035 type = "SUPPORT HELPER";
6036 else
6037 return;
6038
6039 if (irc_in_addr_is_valid(user->ip))
6040 send_channel_notice(opserv_conf.staff_auth_channel, opserv, IDENT_FORMAT" authed to %s account %s", IDENT_DATA(user), type, user->handle_info->handle);
6041 else
6042 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);
6043 }
6044
6045 static MODCMD_FUNC(cmd_log)
6046 {
6047 struct logSearch *discrim;
6048 unsigned int matches;
6049 struct logReport report;
6050
6051 discrim = log_discrim_create(cmd->parent->bot, user, argc, argv);
6052 if (!discrim)
6053 return 0;
6054
6055 reply("OSMSG_LOG_SEARCH_RESULTS");
6056 report.reporter = opserv;
6057 report.user = user;
6058 matches = log_entry_search(discrim, log_report_entry, &report);
6059
6060 if (matches)
6061 reply("MSG_MATCH_COUNT", matches);
6062 else
6063 reply("MSG_NO_MATCHES");
6064
6065 free(discrim);
6066 return 1;
6067 }
6068
6069 static int
6070 gag_helper_func(struct userNode *match, UNUSED_ARG(void *extra))
6071 {
6072 if (IsOper(match) || IsLocal(match))
6073 return 0;
6074 match->modes |= FLAGS_GAGGED;
6075 return 0;
6076 }
6077
6078 static MODCMD_FUNC(cmd_gag)
6079 {
6080 struct gag_entry *gag;
6081 unsigned int gagged;
6082 unsigned long duration;
6083 char *reason;
6084
6085 reason = unsplit_string(argv + 3, argc - 3, NULL);
6086
6087 if (!is_ircmask(argv[1])) {
6088 reply("OSMSG_INVALID_IRCMASK", argv[1]);
6089 return 0;
6090 }
6091
6092 for (gag = gagList; gag; gag = gag->next)
6093 if (match_ircglobs(gag->mask, argv[1]))
6094 break;
6095
6096 if (gag) {
6097 reply("OSMSG_REDUNDANT_GAG", argv[1]);
6098 return 0;
6099 }
6100
6101 duration = ParseInterval(argv[2]);
6102 gagged = gag_create(argv[1], user->handle_info->handle, reason, (duration?now+duration:0));
6103
6104 if (gagged)
6105 reply("OSMSG_GAG_APPLIED", argv[1], gagged);
6106 else
6107 reply("OSMSG_GAG_ADDED", argv[1]);
6108 return 1;
6109 }
6110
6111 static int
6112 ungag_helper_func(struct userNode *match, UNUSED_ARG(void *extra))
6113 {
6114 match->modes &= ~FLAGS_GAGGED;
6115 return 0;
6116 }
6117
6118 static MODCMD_FUNC(cmd_ungag)
6119 {
6120 struct gag_entry *gag;
6121 unsigned int ungagged;
6122
6123 for (gag = gagList; gag; gag = gag->next)
6124 if (!strcmp(gag->mask, argv[1]))
6125 break;
6126
6127 if (!gag) {
6128 reply("OSMSG_GAG_NOT_FOUND", argv[1]);
6129 return 0;
6130 }
6131
6132 timeq_del(gag->expires, gag_expire, gag, 0);
6133 ungagged = gag_free(gag);
6134
6135 if (ungagged)
6136 reply("OSMSG_UNGAG_APPLIED", argv[1], ungagged);
6137 else
6138 reply("OSMSG_UNGAG_ADDED", argv[1]);
6139 return 1;
6140 }
6141
6142 static MODCMD_FUNC(cmd_addalert)
6143 {
6144 opserv_alert_reaction reaction;
6145 struct svccmd *subcmd;
6146 const char *name;
6147 char buf[MAXLEN];
6148
6149 name = argv[1];
6150 sprintf(buf, "addalert %s", argv[2]);
6151 if (!(subcmd = dict_find(opserv_service->commands, buf, NULL))) {
6152 reply("OSMSG_UNKNOWN_REACTION", argv[2]);
6153 return 0;
6154 }
6155 if (!irccasecmp(argv[2], "notice"))
6156 reaction = REACT_NOTICE;
6157 else if (!irccasecmp(argv[2], "kill"))
6158 reaction = REACT_KILL;
6159 /*
6160 else if (!irccasecmp(argv[2], "silent"))
6161 reaction = REACT_SILENT;
6162 */
6163 else if (!irccasecmp(argv[2], "gline"))
6164 reaction = REACT_GLINE;
6165 else if (!irccasecmp(argv[2], "track")) {
6166 #ifndef HAVE_TRACK
6167 reply("OSMSG_TRACK_DISABLED");
6168 return 0;
6169 #else
6170 reaction = REACT_TRACK;
6171 #endif
6172 } else if (!irccasecmp(argv[2], "shun"))
6173 reaction = REACT_SHUN;
6174 else {
6175 reply("OSMSG_UNKNOWN_REACTION", argv[2]);
6176 return 0;
6177 }
6178 if (!svccmd_can_invoke(user, opserv_service->bot, subcmd, channel, SVCCMD_NOISY)
6179 || !opserv_add_user_alert(user, name, reaction, unsplit_string(argv + 3, argc - 3, NULL)))
6180 return 0;
6181 reply("OSMSG_ADDED_ALERT", name);
6182 return 1;
6183 }
6184
6185 static MODCMD_FUNC(cmd_delalert)
6186 {
6187 unsigned int i;
6188 for (i=1; i<argc; i++) {
6189 dict_remove(opserv_nick_based_alerts, argv[i]);
6190 dict_remove(opserv_channel_alerts, argv[i]);
6191 if (dict_remove(opserv_user_alerts, argv[i]))
6192 reply("OSMSG_REMOVED_ALERT", argv[i]);
6193 else
6194 reply("OSMSG_NO_SUCH_ALERT", argv[i]);
6195 }
6196 return 1;
6197 }
6198
6199 static void
6200 opserv_conf_read(void)
6201 {
6202 struct chanNode *chan;
6203 unsigned int i;
6204 struct record_data *rd;
6205 dict_t conf_node, child;
6206 const char *str, *str2;
6207 struct policer_params *pp;
6208 dict_iterator_t it;
6209
6210 rd = conf_get_node(OPSERV_CONF_NAME);
6211 if (!rd || rd->type != RECDB_OBJECT) {
6212 log_module(OS_LOG, LOG_ERROR, "config node `%s' is missing or has wrong type.", OPSERV_CONF_NAME);
6213 return;
6214 }
6215 conf_node = rd->d.object;
6216 str = database_get_data(conf_node, KEY_DEBUG_CHANNEL, RECDB_QSTRING);
6217 if (opserv && str) {
6218 str2 = database_get_data(conf_node, KEY_DEBUG_CHANNEL_MODES, RECDB_QSTRING);
6219 if (!str2)
6220 str2 = "+tinms";
6221 opserv_conf.debug_channel = AddChannel(str, now, str2, NULL, NULL);
6222 AddChannelUser(opserv, opserv_conf.debug_channel)->modes |= MODE_CHANOP;
6223 } else {
6224 opserv_conf.debug_channel = NULL;
6225 }
6226 str = database_get_data(conf_node, KEY_ALERT_CHANNEL, RECDB_QSTRING);
6227 if (opserv && str) {
6228 str2 = database_get_data(conf_node, KEY_ALERT_CHANNEL_MODES, RECDB_QSTRING);
6229 if (!str2)
6230 str2 = "+tns";
6231 opserv_conf.alert_channel = AddChannel(str, now, str2, NULL, NULL);
6232 AddChannelUser(opserv, opserv_conf.alert_channel)->modes |= MODE_CHANOP;
6233 } else {
6234 opserv_conf.alert_channel = NULL;
6235 }
6236 str = database_get_data(conf_node, KEY_STAFF_AUTH_CHANNEL, RECDB_QSTRING);
6237 if (opserv && str) {
6238 str2 = database_get_data(conf_node, KEY_STAFF_AUTH_CHANNEL_MODES, RECDB_QSTRING);
6239 if (!str2)
6240 str2 = "+timns";
6241 opserv_conf.staff_auth_channel = AddChannel(str, now, str2, NULL, NULL);
6242 AddChannelUser(opserv, opserv_conf.staff_auth_channel)->modes |= MODE_CHANOP;
6243 } else {
6244 opserv_conf.staff_auth_channel = NULL;
6245 }
6246
6247 str = database_get_data(conf_node, KEY_ADMIN_LEVEL, RECDB_QSTRING);
6248 opserv_conf.admin_level = str ? strtoul(str, NULL, 0): 800;
6249
6250 str = database_get_data(conf_node, KEY_SILENT_LEVEL, RECDB_QSTRING);
6251 opserv_conf.silent_level = str ? strtoul(str, NULL, 0): 700;
6252
6253 str = database_get_data(conf_node, KEY_UNTRUSTED_MAX, RECDB_QSTRING);
6254 opserv_conf.untrusted_max = str ? strtoul(str, NULL, 0) : 5;
6255 str = database_get_data(conf_node, KEY_PURGE_LOCK_DELAY, RECDB_QSTRING);
6256 opserv_conf.purge_lock_delay = str ? strtoul(str, NULL, 0) : 60;
6257 str = database_get_data(conf_node, KEY_JOIN_FLOOD_MODERATE, RECDB_QSTRING);
6258 opserv_conf.join_flood_moderate = str ? strtoul(str, NULL, 0) : 1;
6259 str = database_get_data(conf_node, KEY_JOIN_FLOOD_MODERATE_THRESH, RECDB_QSTRING);
6260 opserv_conf.join_flood_moderate_threshold = str ? strtoul(str, NULL, 0) : 50;
6261 str = database_get_data(conf_node, KEY_NICK, RECDB_QSTRING);
6262 if (opserv && str)
6263 NickChange(opserv, str, 0);
6264
6265 str = database_get_data(conf_node, KEY_CLONE_GLINE_DURATION, RECDB_QSTRING);
6266 opserv_conf.clone_gline_duration = str ? ParseInterval(str) : 3600;
6267 str = database_get_data(conf_node, KEY_BLOCK_GLINE_DURATION, RECDB_QSTRING);
6268 opserv_conf.block_gline_duration = str ? ParseInterval(str) : 3600;
6269
6270 free_string_list(autojoin_channels);
6271 autojoin_channels = database_get_data(conf_node, KEY_AUTOJOIN_CHANNELS, RECDB_STRING_LIST);
6272
6273 if(autojoin_channels)
6274 autojoin_channels = string_list_copy(autojoin_channels);
6275
6276 if (autojoin_channels && opserv) {
6277 for (i = 0; i < autojoin_channels->used; i++) {
6278 chan = AddChannel(autojoin_channels->list[i], now, "+nt", NULL, NULL);
6279 AddChannelUser(opserv, chan)->modes |= MODE_CHANOP;
6280 }
6281 }
6282
6283 str = database_get_data(conf_node, KEY_BLOCK_SHUN_DURATION, RECDB_QSTRING);
6284 opserv_conf.block_shun_duration = str ? ParseInterval(str) : 3600;
6285
6286 if (!opserv_conf.join_policer_params)
6287 opserv_conf.join_policer_params = policer_params_new();
6288 policer_params_set(opserv_conf.join_policer_params, "size", "20");
6289 policer_params_set(opserv_conf.join_policer_params, "drain-rate", "1");
6290 if ((child = database_get_data(conf_node, KEY_JOIN_POLICER, RECDB_OBJECT)))
6291 dict_foreach(child, set_policer_param, opserv_conf.join_policer_params);
6292
6293 for (it = dict_first(channels); it; it = iter_next(it)) {
6294 struct chanNode *cNode = iter_data(it);
6295 cNode->join_policer.params = opserv_conf.join_policer_params;
6296 }
6297
6298 if (opserv_conf.new_user_policer.params)
6299 pp = opserv_conf.new_user_policer.params;
6300 else
6301 pp = opserv_conf.new_user_policer.params = policer_params_new();
6302 policer_params_set(pp, "size", "200");
6303 policer_params_set(pp, "drain-rate", "3");
6304 if ((child = database_get_data(conf_node, KEY_NEW_USER_POLICER, RECDB_OBJECT)))
6305 dict_foreach(child, set_policer_param, pp);
6306
6307 /* Defcon configuration */
6308 DefCon[0] = 0;
6309 str = database_get_data(conf_node, KEY_DEFCON1, RECDB_QSTRING);
6310 DefCon[1] = str ? atoi(str) : 415;
6311 str = database_get_data(conf_node, KEY_DEFCON2, RECDB_QSTRING);
6312 DefCon[2] = str ? atoi(str) : 159;
6313 str = database_get_data(conf_node, KEY_DEFCON3, RECDB_QSTRING);
6314 DefCon[3] = str ? atoi(str) : 31;
6315 str = database_get_data(conf_node, KEY_DEFCON4, RECDB_QSTRING);
6316 DefCon[4] = str? atoi(str) : 23;
6317 DefCon[5] = 0;
6318
6319 str = database_get_data(conf_node, KEY_DEFCON_LEVEL, RECDB_QSTRING);
6320 DefConLevel = str ? atoi(str) : 5;
6321
6322 str = database_get_data(conf_node, KEY_DEFCON_CHANMODES, RECDB_QSTRING);
6323 DefConChanModes = str ? strdup(str) : "+r";
6324
6325 str = database_get_data(conf_node, KEY_DEFCON_SESSION_LIMIT, RECDB_QSTRING);
6326 DefConSessionLimit = str ? atoi(str) : 2;
6327
6328 str = database_get_data(conf_node, KEY_DEFCON_TIMEOUT, RECDB_QSTRING);
6329 DefConTimeOut = str ? ParseInterval(str) : 900;
6330
6331 str = database_get_data(conf_node, KEY_DEFCON_GLINE_DURATION, RECDB_QSTRING);
6332 DefConGlineExpire = str ? ParseInterval(str) : 300;
6333
6334 str = database_get_data(conf_node, KEY_DEFCON_GLOBAL, RECDB_QSTRING);
6335 GlobalOnDefcon = str ? atoi(str) : 0;
6336
6337 str = database_get_data(conf_node, KEY_DEFCON_GLOBAL_MORE, RECDB_QSTRING);
6338 GlobalOnDefconMore = str ? atoi(str) : 0;
6339
6340 str = database_get_data(conf_node, KEY_DEFCON_MESSAGE, RECDB_QSTRING);
6341 DefConMessage = str ? strdup(str) : "Put your message to send your users here. Dont forget to uncomment GlobalOnDefconMore";
6342
6343 str = database_get_data(conf_node, KEY_DEFCON_OFF_MESSAGE, RECDB_QSTRING);
6344 DefConOffMessage = str? strdup(str) : "Services are now back to normal, sorry for any inconvenience";
6345
6346 str = database_get_data(conf_node, KEY_DEFCON_GLINE_REASON, RECDB_QSTRING);
6347 DefConGlineReason = str ? strdup(str) : "This network is currently not accepting connections, please try again later";
6348 }
6349
6350 /* lame way to export opserv_conf value to nickserv.c ... */
6351 unsigned int
6352 opserv_conf_admin_level()
6353 {
6354 return(opserv_conf.admin_level);
6355 }
6356
6357 static void
6358 opserv_db_init(void) {
6359 /* set up opserv_trusted_hosts dict */
6360 dict_delete(opserv_trusted_hosts);
6361 opserv_trusted_hosts = dict_new();
6362 dict_set_free_data(opserv_trusted_hosts, free_trusted_host);
6363
6364 opserv_routing_plan_options = dict_new();
6365
6366 opserv_routing_plans = dict_new();
6367 dict_set_free_data(opserv_routing_plans, free_routing_plan);
6368 /* set up opserv_chan_warn dict */
6369
6370 /* alert trace notice channel #x replaces warnings
6371 dict_delete(opserv_chan_warn);
6372 opserv_chan_warn = dict_new();
6373 dict_set_free_keys(opserv_chan_warn, free);
6374 dict_set_free_data(opserv_chan_warn, free);
6375 */
6376 /* set up opserv_user_alerts */
6377 dict_delete(opserv_channel_alerts);
6378 opserv_channel_alerts = dict_new();
6379 dict_delete(opserv_nick_based_alerts);
6380 opserv_nick_based_alerts = dict_new();
6381 dict_delete(opserv_user_alerts);
6382 opserv_user_alerts = dict_new();
6383 dict_set_free_keys(opserv_user_alerts, free);
6384 dict_set_free_data(opserv_user_alerts, opserv_free_user_alert);
6385 /* set up opserv_bad_words */
6386 free_string_list(opserv_bad_words);
6387 opserv_bad_words = alloc_string_list(4);
6388 /* and opserv_exempt_channels */
6389 dict_delete(opserv_exempt_channels);
6390 opserv_exempt_channels = dict_new();
6391 dict_set_free_keys(opserv_exempt_channels, free);
6392 }
6393
6394 static void
6395 opserv_db_cleanup(void)
6396 {
6397 unsigned int nn;
6398
6399 /* dict_delete(opserv_chan_warn); */
6400 dict_delete(opserv_reserved_nick_dict);
6401 free_string_list(opserv_bad_words);
6402 dict_delete(opserv_exempt_channels);
6403 dict_delete(opserv_trusted_hosts);
6404 unreg_del_user_func(opserv_user_cleanup);
6405 dict_delete(opserv_hostinfo_dict);
6406 dict_delete(opserv_nick_based_alerts);
6407 dict_delete(opserv_channel_alerts);
6408 dict_delete(opserv_user_alerts);
6409 for (nn=0; nn<ArrayLength(level_strings); ++nn)
6410 free(level_strings[nn]);
6411 while (gagList)
6412 gag_free(gagList);
6413 policer_params_delete(opserv_conf.join_policer_params);
6414 policer_params_delete(opserv_conf.new_user_policer.params);
6415 }
6416
6417 void
6418 init_opserv(const char *nick)
6419 {
6420 OS_LOG = log_register_type("OpServ", "file:opserv.log");
6421 if (nick) {
6422 const char *modes = conf_get_data("services/opserv/modes", RECDB_QSTRING);
6423 opserv = AddService(nick, modes ? modes : NULL, "Oper Services", NULL);
6424 }
6425 conf_register_reload(opserv_conf_read);
6426
6427 memset(level_strings, 0, sizeof(level_strings));
6428 opserv_module = module_register("OpServ", OS_LOG, "opserv.help", opserv_help_expand);
6429 opserv_define_func("ACCESS", cmd_access, 0, 0, 0);
6430 opserv_define_func("ADDALERT", cmd_addalert, 800, 0, 4);
6431 opserv_define_func("ADDALERT NOTICE", NULL, 0, 0, 0);
6432 opserv_define_func("ADDALERT SILENT", NULL, 900, 0, 0);
6433 opserv_define_func("ADDALERT GLINE", NULL, 900, 0, 0);
6434 opserv_define_func("ADDALERT SHUN", NULL, 900, 0, 0);
6435 opserv_define_func("ADDALERT TRACK", NULL, 900, 0, 0);
6436 opserv_define_func("ADDALERT KILL", NULL, 900, 0, 0);
6437 opserv_define_func("ADDBAD", cmd_addbad, 800, 0, 2);
6438 opserv_define_func("ADDEXEMPT", cmd_addexempt, 800, 0, 2);
6439 opserv_define_func("ADDTRUST", cmd_addtrust, 800, 0, 5);
6440 opserv_define_func("BAN", cmd_ban, 100, 2, 2);
6441 opserv_define_func("BLOCK", cmd_block, 100, 0, 2);
6442 opserv_define_func("CHANINFO", cmd_chaninfo, 0, 3, 0);
6443 opserv_define_func("CLEARBANS", cmd_clearbans, 300, 2, 0);
6444 opserv_define_func("CLEARMODES", cmd_clearmodes, 400, 2, 0);
6445 opserv_define_func("CLONE", cmd_clone, 999, 0, 3);
6446 opserv_define_func("COLLIDE", cmd_collide, 800, 0, 5);
6447 opserv_define_func("CSEARCH", cmd_csearch, 100, 0, 3);
6448 opserv_define_func("CSEARCH COUNT", cmd_csearch, 0, 0, 0);
6449 opserv_define_func("CSEARCH PRINT", cmd_csearch, 0, 0, 0);
6450 opserv_define_func("DELALERT", cmd_delalert, 800, 0, 2);
6451 opserv_define_func("DELBAD", cmd_delbad, 800, 0, 2);
6452 opserv_define_func("DELEXEMPT", cmd_delexempt, 800, 0, 2);
6453 opserv_define_func("DELTRUST", cmd_deltrust, 800, 0, 2);
6454 opserv_define_func("DEOP", cmd_deop, 100, 2, 2);
6455 opserv_define_func("DEOPALL", cmd_deopall, 400, 2, 0);
6456 opserv_define_func("DEFCON", cmd_defcon, 900, 0, 0);
6457 opserv_define_func("DEHOP", cmd_dehop, 100, 2, 2);
6458 opserv_define_func("DEHOPALL", cmd_dehopall, 400, 2, 0);
6459 opserv_define_func("DEVOICEALL", cmd_devoiceall, 300, 2, 0);
6460 opserv_define_func("DIE", cmd_die, 900, 0, 2);
6461 opserv_define_func("DUMP", cmd_dump, 999, 0, 2);
6462 opserv_define_func("EDITTRUST", cmd_edittrust, 800, 0, 5);
6463 opserv_define_func("GAG", cmd_gag, 600, 0, 4);
6464 opserv_define_func("GLINE", cmd_gline, 600, 0, 4);
6465 opserv_define_func("GSYNC", cmd_gsync, 600, 0, 0);
6466 opserv_define_func("GTRACE", cmd_gtrace, 100, 0, 3);
6467 opserv_define_func("GTRACE COUNT", NULL, 0, 0, 0);
6468 opserv_define_func("GTRACE PRINT", NULL, 0, 0, 0);
6469 opserv_define_func("SBLOCK", cmd_sblock, 100, 0, 2);
6470 opserv_define_func("SHUN", cmd_shun, 600, 0, 4);
6471 opserv_define_func("SSYNC", cmd_ssync, 600, 0, 0);
6472 opserv_define_func("STRACE", cmd_strace, 100, 0, 3);
6473 opserv_define_func("STRACE COUNT", NULL, 0, 0, 0);
6474 opserv_define_func("STRACE PRINT", NULL, 0, 0, 0);
6475 opserv_define_func("INVITE", cmd_invite, 100, 2, 0);
6476 opserv_define_func("INVITEME", cmd_inviteme, 100, 0, 0);
6477 opserv_define_func("JOIN", cmd_join, 601, 0, 2);
6478 opserv_define_func("JUMP", cmd_jump, 900, 0, 2);
6479 opserv_define_func("JUPE", cmd_jupe, 900, 0, 4);
6480 opserv_define_func("KICK", cmd_kick, 100, 2, 2);
6481 opserv_define_func("KICKALL", cmd_kickall, 400, 2, 0);
6482 opserv_define_func("KICKBAN", cmd_kickban, 100, 2, 2);
6483 opserv_define_func("KICKBANALL", cmd_kickbanall, 450, 2, 0);
6484 opserv_define_func("LOG", cmd_log, 900, 0, 2);
6485 opserv_define_func("MODE", cmd_mode, 100, 2, 2);
6486 opserv_define_func("OP", cmd_op, 100, 2, 2);
6487 opserv_define_func("OPALL", cmd_opall, 400, 2, 0);
6488 opserv_define_func("HOP", cmd_hop, 100, 2, 2);
6489 opserv_define_func("HOPALL", cmd_hopall, 400, 2, 0);
6490 opserv_define_func("MAP", cmd_stats_links, 0, 0, 0);
6491 opserv_define_func("PRIVSET", cmd_privset, 900, 0, 3);
6492 opserv_define_func("PART", cmd_part, 601, 0, 2);
6493 opserv_define_func("QUERY", cmd_query, 0, 0, 0);
6494 opserv_define_func("RAW", cmd_raw, 999, 0, 2);
6495 opserv_define_func("RECONNECT", cmd_reconnect, 900, 0, 0);
6496 opserv_define_func("REFRESHG", cmd_refreshg, 600, 0, 0);
6497 opserv_define_func("REFRESHS", cmd_refreshs, 600, 0, 0);
6498 opserv_define_func("REHASH", cmd_rehash, 900, 0, 0);
6499 opserv_define_func("REOPEN", cmd_reopen, 900, 0, 0);
6500 opserv_define_func("RESETMAX", cmd_resetmax, 900, 0, 0);
6501 opserv_define_func("RESERVE", cmd_reserve, 800, 0, 5);
6502 opserv_define_func("RESTART", cmd_restart, 900, 0, 2);
6503 opserv_define_func("ROUTING ADDPLAN", cmd_routing_addplan, 800, 0, 2);
6504 opserv_define_func("ROUTING DELPLAN", cmd_routing_delplan, 800, 0, 2);
6505 opserv_define_func("ROUTING ADDSERVER", cmd_routing_addserver, 800, 0, 4);
6506 opserv_define_func("ROUTING DELSERVER", cmd_routing_delserver, 800, 0, 3);
6507 opserv_define_func("ROUTING MAP", cmd_routing_map, 800, 0, 0);
6508 opserv_define_func("ROUTING SET", cmd_routing_set, 800, 0, 0);
6509 opserv_define_func("REROUTE", cmd_reroute, 800, 0, 2);
6510 opserv_define_func("SET", cmd_set, 900, 0, 3);
6511 opserv_define_func("SETTIME", cmd_settime, 901, 0, 0);
6512 opserv_define_func("STATS ALERTS", cmd_stats_alerts, 0, 0, 0);
6513 opserv_define_func("STATS BAD", cmd_stats_bad, 0, 0, 0);
6514 opserv_define_func("STATS GAGS", cmd_stats_gags, 0, 0, 0);
6515 opserv_define_func("STATS GLINES", cmd_stats_glines, 0, 0, 0);
6516 opserv_define_func("STATS SHUNS", cmd_stats_shuns, 0, 0, 0);
6517 opserv_define_func("STATS LINKS", cmd_stats_links, 0, 0, 0);
6518 opserv_define_func("STATS MAX", cmd_stats_max, 0, 0, 0);
6519 opserv_define_func("STATS NETWORK", cmd_stats_network, 0, 0, 0);
6520 opserv_define_func("STATS NETWORK2", cmd_stats_network2, 0, 0, 0);
6521 opserv_define_func("STATS RESERVED", cmd_stats_reserved, 0, 0, 0);
6522 opserv_define_func("STATS ROUTING", cmd_stats_routing_plans, 0, 0, 0);
6523 opserv_define_func("STATS TIMEQ", cmd_stats_timeq, 0, 0, 0);
6524 opserv_define_func("STATS TRUSTED", cmd_stats_trusted, 0, 0, 0);
6525 opserv_define_func("STATS UPLINK", cmd_stats_uplink, 0, 0, 0);
6526 opserv_define_func("STATS UPTIME", cmd_stats_uptime, 0, 0, 0);
6527 /* opserv_define_func("STATS WARN", cmd_stats_warn, 0, 0, 0); */
6528 #if defined(WITH_MALLOC_X3) || defined(WITH_MALLOC_SLAB)
6529 opserv_define_func("STATS MEMORY", cmd_stats_memory, 0, 0, 0);
6530 #endif
6531 opserv_define_func("TRACE", cmd_trace, 100, 0, 3);
6532 opserv_define_func("TRACE PRINT", NULL, 0, 0, 0);
6533 opserv_define_func("TRACE COUNT", NULL, 0, 0, 0);
6534 opserv_define_func("TRACE DOMAINS", NULL, 0, 0, 0);
6535 opserv_define_func("TRACE GLINE", NULL, 600, 0, 0);
6536 opserv_define_func("TRACE SHUN", NULL, 600, 0, 0);
6537 opserv_define_func("TRACE GAG", NULL, 600, 0, 0);
6538 opserv_define_func("TRACE KILL", NULL, 600, 0, 0);
6539 opserv_define_func("UNBAN", cmd_unban, 100, 2, 2);
6540 opserv_define_func("UNGAG", cmd_ungag, 600, 0, 2);
6541 opserv_define_func("UNGLINE", cmd_ungline, 600, 0, 2);
6542 modcmd_register(opserv_module, "GTRACE UNGLINE", NULL, 0, 0, "template", "ungline", NULL);
6543 opserv_define_func("UNSHUN", cmd_unshun, 600, 0, 2);
6544 modcmd_register(opserv_module, "GTRACE UNSHUN", NULL, 0, 0, "template", "unshun", NULL);
6545 opserv_define_func("UNJUPE", cmd_unjupe, 900, 0, 2);
6546 opserv_define_func("UNRESERVE", cmd_unreserve, 800, 0, 2);
6547 /* opserv_define_func("UNWARN", cmd_unwarn, 800, 0, 0); */
6548 opserv_define_func("VOICEALL", cmd_voiceall, 300, 2, 0);
6549 /* opserv_define_func("WARN", cmd_warn, 800, 0, 2); */
6550 opserv_define_func("WHOIS", cmd_whois, 0, 0, 2);
6551
6552 opserv_reserved_nick_dict = dict_new();
6553 opserv_hostinfo_dict = dict_new();
6554
6555 dict_set_free_keys(opserv_hostinfo_dict, free);
6556 dict_set_free_data(opserv_hostinfo_dict, opserv_free_hostinfo);
6557
6558 opserv_waiting_connections = dict_new();
6559 dict_set_free_data(opserv_waiting_connections, opserv_free_waiting_connection);
6560
6561 reg_new_user_func(opserv_new_user_check);
6562 reg_nick_change_func(opserv_alert_check_nick);
6563 reg_del_user_func(opserv_user_cleanup);
6564 reg_new_channel_func(opserv_channel_check);
6565 reg_del_channel_func(opserv_channel_delete);
6566 reg_join_func(opserv_join_check);
6567 reg_auth_func(opserv_staff_alert);
6568
6569 opserv_db_init();
6570 saxdb_register("OpServ", opserv_saxdb_read, opserv_saxdb_write);
6571 if (nick)
6572 {
6573 opserv_service = service_register(opserv);
6574 opserv_service->trigger = '?';
6575 }
6576
6577 /* start auto-routing system */
6578 reroute_timer(NULL);
6579 /* start the karma timer, using the saved one if available */
6580 routing_karma_timer(dict_find(opserv_routing_plan_options, "KARMA_TIMER", NULL));
6581
6582 reg_exit_func(opserv_db_cleanup);
6583 message_register_table(msgtab);
6584 }