]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_alias.cpp
4d1dd65c95576c1b34484e73b5f8c210da8d8566
[user/henk/code/inspircd.git] / src / modules / m_alias.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2005, 2009 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2004-2007, 2009 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #include "inspircd.h"
24
25 /** An alias definition
26  */
27 class Alias
28 {
29  public:
30         /** The text of the alias command */
31         std::string AliasedCommand;
32
33         /** Text to replace with */
34         std::string ReplaceFormat;
35
36         /** Nickname required to perform alias */
37         std::string RequiredNick;
38
39         /** Alias requires ulined server */
40         bool ULineOnly;
41
42         /** Requires oper? */
43         bool OperOnly;
44
45         /* whether or not it may be executed via fantasy (default OFF) */
46         bool ChannelCommand;
47
48         /* whether or not it may be executed via /command (default ON) */
49         bool UserCommand;
50
51         /** Format that must be matched for use */
52         std::string format;
53 };
54
55 class ModuleAlias : public Module
56 {
57         std::string fprefix;
58
59         /* We cant use a map, there may be multiple aliases with the same name.
60          * We can, however, use a fancy invention: the multimap. Maps a key to one or more values.
61          *              -- w00t
62          */
63         typedef insp::flat_multimap<std::string, Alias, irc::insensitive_swo> AliasMap;
64
65         AliasMap Aliases;
66
67         /* whether or not +B users are allowed to use fantasy commands */
68         bool AllowBots;
69         UserModeReference botmode;
70
71         // Whether we are actively executing an alias.
72         bool active;
73
74  public:
75         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
76         {
77                 AliasMap newAliases;
78                 ConfigTagList tags = ServerInstance->Config->ConfTags("alias");
79                 for(ConfigIter i = tags.first; i != tags.second; ++i)
80                 {
81                         ConfigTag* tag = i->second;
82                         Alias a;
83                         a.AliasedCommand = tag->getString("text");
84                         if (a.AliasedCommand.empty())
85                                 throw ModuleException("<alias:text> is empty! at " + tag->getTagLocation());
86
87                         tag->readString("replace", a.ReplaceFormat, true);
88                         if (a.ReplaceFormat.empty())
89                                 throw ModuleException("<alias:replace> is empty! at " + tag->getTagLocation());
90
91                         a.RequiredNick = tag->getString("requires");
92                         a.ULineOnly = tag->getBool("uline");
93                         a.ChannelCommand = tag->getBool("channelcommand", false);
94                         a.UserCommand = tag->getBool("usercommand", true);
95                         a.OperOnly = tag->getBool("operonly");
96                         a.format = tag->getString("format");
97
98                         std::transform(a.AliasedCommand.begin(), a.AliasedCommand.end(), a.AliasedCommand.begin(), ::toupper);
99                         newAliases.insert(std::make_pair(a.AliasedCommand, a));
100                 }
101
102                 ConfigTag* fantasy = ServerInstance->Config->ConfValue("fantasy");
103                 AllowBots = fantasy->getBool("allowbots", false);
104                 fprefix = fantasy->getString("prefix", "!", 1, ServerInstance->Config->Limits.MaxLine);
105                 Aliases.swap(newAliases);
106         }
107
108         ModuleAlias()
109                 : botmode(this, "bot")
110         {
111         }
112
113         Version GetVersion() CXX11_OVERRIDE
114         {
115                 return Version("Provides aliases of commands.", VF_VENDOR);
116         }
117
118         std::string GetVar(std::string varname, const std::string &original_line)
119         {
120                 irc::spacesepstream ss(original_line);
121                 varname.erase(varname.begin());
122                 int index = *(varname.begin()) - 48;
123                 varname.erase(varname.begin());
124                 bool everything_after = (varname == "-");
125                 std::string word;
126
127                 for (int j = 0; j < index; j++)
128                         ss.GetToken(word);
129
130                 if (everything_after)
131                 {
132                         std::string more;
133                         while (ss.GetToken(more))
134                         {
135                                 word.append(" ");
136                                 word.append(more);
137                         }
138                 }
139
140                 return word;
141         }
142
143         std::string CreateRFCMessage(const std::string& command, CommandBase::Params& parameters)
144         {
145                 std::string message(command);
146                 for (CommandBase::Params::const_iterator iter = parameters.begin(); iter != parameters.end();)
147                 {
148                         const std::string& parameter = *iter++;
149                         message.push_back(' ');
150                         if (iter == parameters.end() && (parameter.empty() || parameter.find(' ') != std::string::npos))
151                                 message.push_back(':');
152                         message.append(parameter);
153                 }
154                 return message;
155         }
156
157         ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE
158         {
159                 /* If theyre not registered yet, we dont want
160                  * to know.
161                  */
162                 if (user->registered != REG_ALL)
163                         return MOD_RES_PASSTHRU;
164
165                 /* We dont have any commands looking like this? Stop processing. */
166                 std::pair<AliasMap::iterator, AliasMap::iterator> iters = Aliases.equal_range(command);
167                 if (iters.first == iters.second)
168                         return MOD_RES_PASSTHRU;
169
170                 /* The parameters for the command in their original form, with the command stripped off */
171                 std::string original_line = CreateRFCMessage(command, parameters);
172                 std::string compare(original_line, command.length());
173                 while (*(compare.c_str()) == ' ')
174                         compare.erase(compare.begin());
175
176                 for (AliasMap::iterator i = iters.first; i != iters.second; ++i)
177                 {
178                         if (i->second.UserCommand)
179                         {
180                                 if (DoAlias(user, NULL, &(i->second), compare, original_line))
181                                 {
182                                         return MOD_RES_DENY;
183                                 }
184                         }
185                 }
186
187                 // If we made it here, no aliases actually matched.
188                 return MOD_RES_PASSTHRU;
189         }
190
191         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
192         {
193                 // Don't echo anything which is caused by an alias.
194                 if (active)
195                         details.echo = false;
196
197                 return MOD_RES_PASSTHRU;
198         }
199
200         void OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details) CXX11_OVERRIDE
201         {
202                 if ((target.type != MessageTarget::TYPE_CHANNEL) || (details.type != MSG_PRIVMSG))
203                 {
204                         return;
205                 }
206
207                 // fcommands are only for local users. Spanningtree will send them back out as their original cmd.
208                 if (!IS_LOCAL(user))
209                 {
210                         return;
211                 }
212
213                 /* Stop here if the user is +B and allowbot is set to no. */
214                 if (!AllowBots && user->IsModeSet(botmode))
215                 {
216                         return;
217                 }
218
219                 Channel *c = target.Get<Channel>();
220                 std::string scommand;
221
222                 // text is like "!moo cows bite me", we want "!moo" first
223                 irc::spacesepstream ss(details.text);
224                 ss.GetToken(scommand);
225
226                 if (scommand.size() <= fprefix.size())
227                 {
228                         return; // wtfbbq
229                 }
230
231                 // we don't want to touch non-fantasy stuff
232                 if (scommand.compare(0, fprefix.size(), fprefix) != 0)
233                 {
234                         return;
235                 }
236
237                 // nor do we give a shit about the prefix
238                 scommand.erase(0, fprefix.size());
239
240                 std::pair<AliasMap::iterator, AliasMap::iterator> iters = Aliases.equal_range(scommand);
241                 if (iters.first == iters.second)
242                         return;
243
244                 /* The parameters for the command in their original form, with the command stripped off */
245                 std::string compare(details.text, scommand.length() + fprefix.size());
246                 while (*(compare.c_str()) == ' ')
247                         compare.erase(compare.begin());
248
249                 for (AliasMap::iterator i = iters.first; i != iters.second; ++i)
250                 {
251                         if (i->second.ChannelCommand)
252                         {
253                                 // We use substr here to remove the fantasy prefix
254                                 if (DoAlias(user, c, &(i->second), compare, details.text.substr(fprefix.size())))
255                                         return;
256                         }
257                 }
258         }
259
260
261         int DoAlias(User *user, Channel *c, Alias *a, const std::string& compare, const std::string& safe)
262         {
263                 /* Does it match the pattern? */
264                 if (!a->format.empty())
265                 {
266                         if (!InspIRCd::Match(compare, a->format))
267                                 return 0;
268                 }
269
270                 if ((a->OperOnly) && (!user->IsOper()))
271                         return 0;
272
273                 if (!a->RequiredNick.empty())
274                 {
275                         User* u = ServerInstance->FindNick(a->RequiredNick);
276                         if (!u)
277                         {
278                                 user->WriteNumeric(ERR_NOSUCHNICK, a->RequiredNick, "is currently unavailable. Please try again later.");
279                                 return 1;
280                         }
281
282                         if ((a->ULineOnly) && (!u->server->IsULine()))
283                         {
284                                 ServerInstance->SNO->WriteToSnoMask('a', "NOTICE -- Service "+a->RequiredNick+" required by alias "+a->AliasedCommand+" is not on a u-lined server, possibly underhanded antics detected!");
285                                 user->WriteNumeric(ERR_NOSUCHNICK, a->RequiredNick, "is an imposter! Please inform an IRC operator as soon as possible.");
286                                 return 1;
287                         }
288                 }
289
290                 /* Now, search and replace in a copy of the original_line, replacing $1 through $9 and $1- etc */
291
292                 std::string::size_type crlf = a->ReplaceFormat.find('\n');
293
294                 if (crlf == std::string::npos)
295                 {
296                         DoCommand(a->ReplaceFormat, user, c, safe, a);
297                         return 1;
298                 }
299                 else
300                 {
301                         irc::sepstream commands(a->ReplaceFormat, '\n');
302                         std::string scommand;
303                         while (commands.GetToken(scommand))
304                         {
305                                 DoCommand(scommand, user, c, safe, a);
306                         }
307                         return 1;
308                 }
309         }
310
311         void DoCommand(const std::string& newline, User* user, Channel *chan, const std::string &original_line, Alias* a)
312         {
313                 std::string result;
314                 result.reserve(newline.length());
315                 for (unsigned int i = 0; i < newline.length(); i++)
316                 {
317                         char c = newline[i];
318                         if ((c == '$') && (i + 1 < newline.length()))
319                         {
320                                 if (isdigit(newline[i+1]))
321                                 {
322                                         size_t len = ((i + 2 < newline.length()) && (newline[i+2] == '-')) ? 3 : 2;
323                                         std::string var = newline.substr(i, len);
324                                         result.append(GetVar(var, original_line));
325                                         i += len - 1;
326                                 }
327                                 else if (!newline.compare(i, 5, "$nick", 5))
328                                 {
329                                         result.append(user->nick);
330                                         i += 4;
331                                 }
332                                 else if (!newline.compare(i, 5, "$host", 5))
333                                 {
334                                         result.append(user->GetRealHost());
335                                         i += 4;
336                                 }
337                                 else if (!newline.compare(i, 5, "$chan", 5))
338                                 {
339                                         if (chan)
340                                                 result.append(chan->name);
341                                         i += 4;
342                                 }
343                                 else if (!newline.compare(i, 6, "$ident", 6))
344                                 {
345                                         result.append(user->ident);
346                                         i += 5;
347                                 }
348                                 else if (!newline.compare(i, 6, "$vhost", 6))
349                                 {
350                                         result.append(user->GetDisplayedHost());
351                                         i += 5;
352                                 }
353                                 else if (!newline.compare(i, 12, "$requirement", 12))
354                                 {
355                                         result.append(a->RequiredNick);
356                                         i += 11;
357                                 }
358                                 else
359                                         result.push_back(c);
360                         }
361                         else
362                                 result.push_back(c);
363                 }
364
365                 irc::tokenstream ss(result);
366                 CommandBase::Params pars;
367                 std::string command, token;
368
369                 ss.GetMiddle(command);
370                 while (ss.GetTrailing(token))
371                 {
372                         pars.push_back(token);
373                 }
374
375                 active = true;
376                 ServerInstance->Parser.CallHandler(command, pars, user);
377                 active = false;
378         }
379
380         void Prioritize() CXX11_OVERRIDE
381         {
382                 // Prioritise after spanningtree so that channel aliases show the alias before the effects.
383                 Module* linkmod = ServerInstance->Modules->Find("m_spanningtree.so");
384                 ServerInstance->Modules->SetPriority(this, I_OnUserPostMessage, PRIORITY_AFTER, linkmod);
385         }
386 };
387
388 MODULE_INIT(ModuleAlias)