]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_message.cpp
Move message access checks to OnUserPre{Tag,}Message.
[user/henk/code/inspircd.git] / src / coremods / core_message.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
7  *
8  * This file is part of InspIRCd.  InspIRCd is free software: you can
9  * redistribute it and/or modify it under the terms of the GNU General Public
10  * License as published by the Free Software Foundation, version 2.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21
22 #include "inspircd.h"
23
24 enum
25 {
26         // From RFC 2812.
27         ERR_NOSUCHSERVICE = 408
28 };
29
30 class MessageDetailsImpl : public MessageDetails
31 {
32 public:
33         MessageDetailsImpl(MessageType mt, const std::string& msg, const ClientProtocol::TagMap& tags)
34                 : MessageDetails(mt, msg, tags)
35         {
36         }
37
38         bool IsCTCP(std::string& name, std::string& body) const CXX11_OVERRIDE
39         {
40                 if (!this->IsCTCP())
41                         return false;
42
43                 size_t end_of_name = text.find(' ', 2);
44                 size_t end_of_ctcp = *text.rbegin() == '\x1' ? 1 : 0;
45                 if (end_of_name == std::string::npos)
46                 {
47                         // The CTCP only contains a name.
48                         name.assign(text, 1, text.length() - 1 - end_of_ctcp);
49                         body.clear();
50                         return true;
51                 }
52
53                 // The CTCP contains a name and a body.
54                 name.assign(text, 1, end_of_name - 1);
55
56                 size_t start_of_body = text.find_first_not_of(' ', end_of_name + 1);
57                 if (start_of_body == std::string::npos)
58                 {
59                         // The CTCP body is provided but empty.
60                         body.clear();
61                         return true;
62                 }
63
64                 // The CTCP body provided was non-empty.
65                 body.assign(text, start_of_body, text.length() - start_of_body - end_of_ctcp);
66                 return true;
67         }
68
69         bool IsCTCP(std::string& name) const CXX11_OVERRIDE
70         {
71                 if (!this->IsCTCP())
72                         return false;
73
74                 size_t end_of_name = text.find(' ', 2);
75                 if (end_of_name == std::string::npos)
76                 {
77                         // The CTCP only contains a name.
78                         size_t end_of_ctcp = *text.rbegin() == '\x1' ? 1 : 0;
79                         name.assign(text, 1, text.length() - 1 - end_of_ctcp);
80                         return true;
81                 }
82
83                 // The CTCP contains a name and a body.
84                 name.assign(text, 1, end_of_name - 1);
85                 return true;
86         }
87
88         bool IsCTCP() const CXX11_OVERRIDE
89         {
90                 // According to draft-oakley-irc-ctcp-02 a valid CTCP must begin with SOH and
91                 // contain at least one octet which is not NUL, SOH, CR, LF, or SPACE. As most
92                 // of these are restricted at the protocol level we only need to check for SOH
93                 // and SPACE.
94                 return (text.length() >= 2) && (text[0] == '\x1') &&  (text[1] != '\x1') && (text[1] != ' ');
95         }
96 };
97
98 namespace
99 {
100         bool FirePreEvents(User* source, MessageTarget& msgtarget, MessageDetails& msgdetails)
101         {
102                 // Inform modules that a message wants to be sent.
103                 ModResult modres;
104                 FIRST_MOD_RESULT(OnUserPreMessage, modres, (source, msgtarget, msgdetails));
105                 if (modres == MOD_RES_DENY)
106                 {
107                         // Inform modules that a module blocked the mssage.
108                         FOREACH_MOD(OnUserMessageBlocked, (source, msgtarget, msgdetails));
109                         return false;
110                 }
111
112                 // Check whether a module zapped the message body.
113                 if (msgdetails.text.empty())
114                 {
115                         source->WriteNumeric(ERR_NOTEXTTOSEND, "No text to send");
116                         return false;
117                 }
118
119                 // Inform modules that a message is about to be sent.
120                 FOREACH_MOD(OnUserMessage, (source, msgtarget, msgdetails));
121                 return true;
122         }
123
124         CmdResult FirePostEvent(User* source, const MessageTarget& msgtarget, const MessageDetails& msgdetails)
125         {
126                 // If the source is local and was not sending a CTCP reply then update their idle time.
127                 LocalUser* lsource = IS_LOCAL(source);
128                 if (lsource && (msgdetails.type != MSG_NOTICE || !msgdetails.IsCTCP()))
129                         lsource->idle_lastmsg = ServerInstance->Time();
130
131                 // Inform modules that a message was sent.
132                 FOREACH_MOD(OnUserPostMessage, (source, msgtarget, msgdetails));
133                 return CMD_SUCCESS;
134         }
135 }
136
137 class CommandMessage : public Command
138 {
139  private:
140         const MessageType msgtype;
141
142         CmdResult HandleChannelTarget(User* source, const Params& parameters, const char* target, PrefixMode* pm)
143         {
144                 Channel* chan = ServerInstance->FindChan(target);
145                 if (!chan)
146                 {
147                         // The target channel does not exist.
148                         source->WriteNumeric(Numerics::NoSuchChannel(parameters[0]));
149                         return CMD_FAILURE;
150                 }
151
152                 // Fire the pre-message events.
153                 MessageTarget msgtarget(chan, pm ? pm->GetPrefix() : 0);
154                 MessageDetailsImpl msgdetails(msgtype, parameters[1], parameters.GetTags());
155                 msgdetails.exemptions.insert(source);
156                 if (!FirePreEvents(source, msgtarget, msgdetails))
157                         return CMD_FAILURE;
158
159                 // Send the message to the members of the channel.
160                 ClientProtocol::Messages::Privmsg privmsg(ClientProtocol::Messages::Privmsg::nocopy, source, chan, msgdetails.text, msgdetails.type, msgtarget.status);
161                 privmsg.AddTags(msgdetails.tags_out);
162                 privmsg.SetSideEffect(true);
163                 chan->Write(ServerInstance->GetRFCEvents().privmsg, privmsg, msgtarget.status, msgdetails.exemptions);
164
165                 // Create the outgoing message and message event.
166                 return FirePostEvent(source, msgtarget, msgdetails);
167         }
168
169         CmdResult HandleServerTarget(User* source, const Params& parameters)
170         {
171                 // If the source isn't allowed to mass message users then reject
172                 // the attempt to mass-message users.
173                 if (!source->HasPrivPermission("users/mass-message"))
174                         return CMD_FAILURE;
175
176                 // Extract the server glob match from the target parameter.
177                 std::string servername(parameters[0], 1);
178
179                 // Fire the pre-message events.
180                 MessageTarget msgtarget(&servername);
181                 MessageDetailsImpl msgdetails(msgtype, parameters[1], parameters.GetTags());
182                 if (!FirePreEvents(source, msgtarget, msgdetails))
183                         return CMD_FAILURE;
184
185                 // If the current server name matches the server name glob then send
186                 // the message out to the local users.
187                 if (InspIRCd::Match(ServerInstance->Config->ServerName, servername))
188                 {
189                         // Create the outgoing message and message event.
190                         ClientProtocol::Messages::Privmsg message(ClientProtocol::Messages::Privmsg::nocopy, source, "$*", msgdetails.text, msgdetails.type);
191                         message.AddTags(msgdetails.tags_out);
192                         message.SetSideEffect(true);
193                         ClientProtocol::Event messageevent(ServerInstance->GetRFCEvents().privmsg, message);
194
195                         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
196                         for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
197                         {
198                                 LocalUser* luser = *i;
199
200                                 // Don't send to unregistered users or the user who is the source.
201                                 if (luser->registered != REG_ALL || luser == source)
202                                         continue;
203
204                                 // Only send to non-exempt users.
205                                 if (!msgdetails.exemptions.count(luser))
206                                         luser->Send(messageevent);
207                         }
208                 }
209
210                 // Fire the post-message event.
211                 return FirePostEvent(source, msgtarget, msgdetails);
212         }
213
214         CmdResult HandleUserTarget(User* source, const Params& parameters)
215         {
216                 User* target;
217                 if (IS_LOCAL(source))
218                 {
219                         // Local sources can specify either a nick or a nick@server mask as the target.
220                         const char* targetserver = strchr(parameters[0].c_str(), '@');
221                         if (targetserver)
222                         {
223                                 // The target is a user on a specific server (e.g. jto@tolsun.oulu.fi).
224                                 target = ServerInstance->FindNickOnly(parameters[0].substr(0, targetserver - parameters[0].c_str()));
225                                 if (target && strcasecmp(target->server->GetName().c_str(), targetserver + 1))
226                                         target = NULL;
227                         }
228                         else
229                         {
230                                 // If the source is a local user then we only look up the target by nick.
231                                 target = ServerInstance->FindNickOnly(parameters[0]);
232                         }
233                 }
234                 else
235                 {
236                         // Remote users can only specify a nick or UUID as the target.
237                         target = ServerInstance->FindNick(parameters[0]);
238                 }
239
240                 if (!target || target->registered != REG_ALL)
241                 {
242                         // The target user does not exist or is not fully registered.
243                         source->WriteNumeric(Numerics::NoSuchNick(parameters[0]));
244                         return CMD_FAILURE;
245                 }
246
247                 // If the target is away then inform the user.
248                 if (target->IsAway() && msgtype == MSG_PRIVMSG)
249                         source->WriteNumeric(RPL_AWAY, target->nick, target->awaymsg);
250
251                 // Fire the pre-message events.
252                 MessageTarget msgtarget(target);
253                 MessageDetailsImpl msgdetails(msgtype, parameters[1], parameters.GetTags());
254                 if (!FirePreEvents(source, msgtarget, msgdetails))
255                         return CMD_FAILURE;
256
257                 LocalUser* const localtarget = IS_LOCAL(target);
258                 if (localtarget)
259                 {
260                         // Send to the target if they are a local user.
261                         ClientProtocol::Messages::Privmsg privmsg(ClientProtocol::Messages::Privmsg::nocopy, source, localtarget->nick, msgdetails.text, msgtype);
262                         privmsg.AddTags(msgdetails.tags_out);
263                         privmsg.SetSideEffect(true);
264                         localtarget->Send(ServerInstance->GetRFCEvents().privmsg, privmsg);
265                 }
266
267                 // Fire the post-message event.
268                 return FirePostEvent(source, msgtarget, msgdetails);
269         }
270
271  public:
272         CommandMessage(Module* parent, MessageType mt)
273                 : Command(parent, ClientProtocol::Messages::Privmsg::CommandStrFromMsgType(mt), 2, 2)
274                 , msgtype(mt)
275         {
276                 syntax = "<target>[,<target>]+ :<message>";
277         }
278
279         /** Handle command.
280          * @param parameters The parameters to the command
281          * @param user The user issuing the command
282          * @return A value from CmdResult to indicate command success or failure.
283          */
284         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
285         {
286                 if (CommandParser::LoopCall(user, this, parameters, 0))
287                         return CMD_SUCCESS;
288
289                 // The specified message was empty.
290                 if (parameters[1].empty())
291                 {
292                         user->WriteNumeric(ERR_NOTEXTTOSEND, "No text to send");
293                         return CMD_FAILURE;
294                 }
295
296                 // The target is a server glob.
297                 if (parameters[0][0] == '$')
298                         return HandleServerTarget(user, parameters);
299
300                 // If the message begins with a status character then look it up.
301                 const char* target = parameters[0].c_str();
302                 PrefixMode* pmh = ServerInstance->Modes->FindPrefix(target[0]);
303                 if (pmh)
304                         target++;
305
306                 // The target is a channel name.
307                 if (*target == '#')
308                         return HandleChannelTarget(user, parameters, target, pmh);
309
310                 // The target is a nickname.
311                 return HandleUserTarget(user, parameters);
312         }
313
314         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
315         {
316                 if (IS_LOCAL(user))
317                         // This is handled by the OnUserPostMessage hook to split the LoopCall pieces
318                         return ROUTE_LOCALONLY;
319                 else
320                         return ROUTE_MESSAGE(parameters[0]);
321         }
322 };
323
324 class CommandSQuery : public SplitCommand
325 {
326  public:
327         CommandSQuery(Module* Creator)
328                 : SplitCommand(Creator, "SQUERY", 2, 2)
329         {
330                 syntax = "<service> :<message>";
331         }
332
333         CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
334         {
335                 // The specified message was empty.
336                 if (parameters[1].empty())
337                 {
338                         user->WriteNumeric(ERR_NOTEXTTOSEND, "No text to send");
339                         return CMD_FAILURE;
340                 }
341
342                 // The target can be either a nick or a nick@server mask.
343                 User* target;
344                 const char* targetserver = strchr(parameters[0].c_str(), '@');
345                 if (targetserver)
346                 {
347                         // The target is a user on a specific server (e.g. jto@tolsun.oulu.fi).
348                         target = ServerInstance->FindNickOnly(parameters[0].substr(0, targetserver - parameters[0].c_str()));
349                         if (target && strcasecmp(target->server->GetName().c_str(), targetserver + 1))
350                                 target = NULL;
351                 }
352                 else
353                 {
354                         // The targer can be on any server.
355                         target = ServerInstance->FindNickOnly(parameters[0]);
356                 }
357
358                 if (!target || target->registered != REG_ALL || !target->server->IsULine())
359                 {
360                         // The target user does not exist, is not fully registered, or is not a service.
361                         user->WriteNumeric(ERR_NOSUCHSERVICE, parameters[0], "No such service");
362                         return CMD_FAILURE;
363                 }
364
365                 // Fire the pre-message events.
366                 MessageTarget msgtarget(target);
367                 MessageDetailsImpl msgdetails(MSG_PRIVMSG, parameters[1], parameters.GetTags());
368                 if (!FirePreEvents(user, msgtarget, msgdetails))
369                         return CMD_FAILURE;
370
371                 // The SQUERY command targets a service on a U-lined server. This can never
372                 // be on the server local to the source so we don't need to do any routing
373                 // logic and can forward it as a PRIVMSG.
374
375                 // Fire the post-message event.
376                 return FirePostEvent(user, msgtarget, msgdetails);
377         }
378 };
379
380 class ModuleCoreMessage : public Module
381 {
382  private:
383         CommandMessage cmdprivmsg;
384         CommandMessage cmdnotice;
385         CommandSQuery cmdsquery;
386         ChanModeReference moderatedmode;
387         ChanModeReference noextmsgmode;
388
389  public:
390         ModuleCoreMessage()
391                 : cmdprivmsg(this, MSG_PRIVMSG)
392                 , cmdnotice(this, MSG_NOTICE)
393                 , cmdsquery(this)
394                 , moderatedmode(this, "moderated")
395                 , noextmsgmode(this, "noextmsg")
396         {
397         }
398
399         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
400         {
401                 if (!IS_LOCAL(user) || target.type != MessageTarget::TYPE_CHANNEL)
402                         return MOD_RES_PASSTHRU;
403
404                 Channel* chan = target.Get<Channel>();
405                 if (chan->IsModeSet(noextmsgmode) && !chan->HasUser(user))
406                 {
407                         // The noextmsg mode is set and the user is not in the channel.
408                         user->WriteNumeric(ERR_CANNOTSENDTOCHAN, chan->name, "Cannot send to channel (no external messages)");
409                         return MOD_RES_DENY;
410                 }
411
412                 bool no_chan_priv = chan->GetPrefixValue(user) < VOICE_VALUE;
413                 if (no_chan_priv && chan->IsModeSet(moderatedmode))
414                 {
415                         // The moderated mode is set and the user has no status rank.
416                         user->WriteNumeric(ERR_CANNOTSENDTOCHAN, chan->name, "Cannot send to channel (+m is set)");
417                         return MOD_RES_DENY;
418                 }
419
420                 if (no_chan_priv && ServerInstance->Config->RestrictBannedUsers != ServerConfig::BUT_NORMAL && chan->IsBanned(user))
421                 {
422                         // The user is banned in the channel and restrictbannedusers is enabled.
423                         if (ServerInstance->Config->RestrictBannedUsers == ServerConfig::BUT_RESTRICT_NOTIFY)
424                                 user->WriteNumeric(ERR_CANNOTSENDTOCHAN, chan->name, "Cannot send to channel (you're banned)");
425                         return MOD_RES_DENY;
426                 }
427
428                 return MOD_RES_PASSTHRU;
429         }
430
431         Version GetVersion() CXX11_OVERRIDE
432         {
433                 return Version("Provides the NOTICE, PRIVMSG, and SQUERY commands", VF_CORE|VF_VENDOR);
434         }
435 };
436
437 MODULE_INIT(ModuleCoreMessage)