]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_channel/core_channel.cpp
Merge branch 'insp20' into master.
[user/henk/code/inspircd.git] / src / coremods / core_channel / core_channel.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2014-2015 Attila Molnar <attilamolnar@hush.com>
5  *
6  * This file is part of InspIRCd.  InspIRCd is free software: you can
7  * redistribute it and/or modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation, version 2.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
13  * details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19
20 #include "inspircd.h"
21 #include "core_channel.h"
22 #include "invite.h"
23 #include "listmode.h"
24
25 namespace
26 {
27 /** Hook that sends a MODE after a JOIN if the user in the JOIN has some modes prefix set.
28  * This happens e.g. when modules such as operprefix explicitly set prefix modes on the joining
29  * user, or when a member with prefix modes does a host cycle.
30  */
31 class JoinHook : public ClientProtocol::EventHook
32 {
33         ClientProtocol::Messages::Mode modemsg;
34         Modes::ChangeList modechangelist;
35         const User* joininguser;
36
37  public:
38         /** If true, MODE changes after JOIN will be sourced from the user, rather than the server
39          */
40         bool modefromuser;
41
42         JoinHook(Module* mod)
43                 : ClientProtocol::EventHook(mod, "JOIN")
44         {
45         }
46
47         void OnEventInit(const ClientProtocol::Event& ev) CXX11_OVERRIDE
48         {
49                 const ClientProtocol::Events::Join& join = static_cast<const ClientProtocol::Events::Join&>(ev);
50                 const Membership& memb = *join.GetMember();
51
52                 modechangelist.clear();
53                 for (std::string::const_iterator i = memb.modes.begin(); i != memb.modes.end(); ++i)
54                 {
55                         PrefixMode* const pm = ServerInstance->Modes.FindPrefixMode(*i);
56                         if (!pm)
57                                 continue; // Shouldn't happen
58                         modechangelist.push_add(pm, memb.user->nick);
59                 }
60
61                 if (modechangelist.empty())
62                 {
63                         // Member got no modes on join
64                         joininguser = NULL;
65                         return;
66                 }
67
68                 joininguser = memb.user;
69
70                 // Prepare a mode protocol event that we can append to the message list in OnPreEventSend()
71                 modemsg.SetParams(memb.chan, NULL, modechangelist);
72                 if (modefromuser)
73                         modemsg.SetSource(join);
74                 else
75                         modemsg.SetSourceUser(ServerInstance->FakeClient);
76         }
77
78         ModResult OnPreEventSend(LocalUser* user, const ClientProtocol::Event& ev, ClientProtocol::MessageList& messagelist) CXX11_OVERRIDE
79         {
80                 // If joininguser is NULL then they didn't get any modes on join, skip.
81                 // Also don't show their own modes to them, they get that in the NAMES list not via MODE.
82                 if ((joininguser) && (user != joininguser))
83                         messagelist.push_back(&modemsg);
84                 return MOD_RES_PASSTHRU;
85         }
86 };
87
88 }
89
90 class CoreModChannel : public Module, public CheckExemption::EventListener
91 {
92         Invite::APIImpl invapi;
93         CommandInvite cmdinvite;
94         CommandJoin cmdjoin;
95         CommandKick cmdkick;
96         CommandNames cmdnames;
97         CommandTopic cmdtopic;
98         Events::ModuleEventProvider evprov;
99         JoinHook joinhook;
100
101         ModeChannelBan banmode;
102         SimpleChannelModeHandler inviteonlymode;
103         ModeChannelKey keymode;
104         ModeChannelLimit limitmode;
105         SimpleChannelModeHandler moderatedmode;
106         SimpleChannelModeHandler noextmsgmode;
107         ModeChannelOp opmode;
108         SimpleChannelModeHandler privatemode;
109         SimpleChannelModeHandler secretmode;
110         SimpleChannelModeHandler topiclockmode;
111         ModeChannelVoice voicemode;
112
113         insp::flat_map<std::string, char> exemptions;
114
115         ModResult IsInvited(User* user, Channel* chan)
116         {
117                 LocalUser* localuser = IS_LOCAL(user);
118                 if ((localuser) && (invapi.IsInvited(localuser, chan)))
119                         return MOD_RES_ALLOW;
120                 return MOD_RES_PASSTHRU;
121         }
122
123  public:
124         CoreModChannel()
125                 : CheckExemption::EventListener(this)
126                 , invapi(this)
127                 , cmdinvite(this, invapi)
128                 , cmdjoin(this)
129                 , cmdkick(this)
130                 , cmdnames(this)
131                 , cmdtopic(this)
132                 , evprov(this, "event/channel")
133                 , joinhook(this)
134                 , banmode(this)
135                 , inviteonlymode(this, "inviteonly", 'i')
136                 , keymode(this)
137                 , limitmode(this)
138                 , moderatedmode(this, "moderated", 'm')
139                 , noextmsgmode(this, "noextmsg", 'n')
140                 , opmode(this)
141                 , privatemode(this, "private", 'p')
142                 , secretmode(this, "secret", 's')
143                 , topiclockmode(this, "topiclock", 't')
144                 , voicemode(this)
145         {
146         }
147
148         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
149         {
150                 ConfigTag* optionstag = ServerInstance->Config->ConfValue("options");
151                 Implementation events[] = { I_OnCheckKey, I_OnCheckLimit, I_OnCheckChannelBan };
152                 if (optionstag->getBool("invitebypassmodes", true))
153                         ServerInstance->Modules.Attach(events, this, sizeof(events)/sizeof(Implementation));
154                 else
155                 {
156                         for (unsigned int i = 0; i < sizeof(events)/sizeof(Implementation); i++)
157                                 ServerInstance->Modules.Detach(events[i], this);
158                 }
159
160                 joinhook.modefromuser = optionstag->getBool("cyclehostsfromuser");
161
162                 std::string current;
163                 irc::spacesepstream defaultstream(optionstag->getString("exemptchanops"));
164                 insp::flat_map<std::string, char> exempts;
165                 while (defaultstream.GetToken(current))
166                 {
167                         std::string::size_type pos = current.find(':');
168                         if (pos == std::string::npos || (pos + 2) > current.size())
169                                 throw ModuleException("Invalid exemptchanops value '" + current + "' at " + optionstag->getTagLocation());
170
171                         const std::string restriction = current.substr(0, pos);
172                         const char prefix = current[pos + 1];
173
174                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Exempting prefix %c from %s", prefix, restriction.c_str());
175                         exempts[restriction] = prefix;
176                 }
177                 exemptions.swap(exempts);
178
179                 ConfigTag* securitytag = ServerInstance->Config->ConfValue("security");
180                 const std::string announceinvites = securitytag->getString("announceinvites", "dynamic");
181                 if (stdalgo::string::equalsci(announceinvites, "none"))
182                         cmdinvite.announceinvites = Invite::ANNOUNCE_NONE;
183                 else if (stdalgo::string::equalsci(announceinvites, "all"))
184                         cmdinvite.announceinvites = Invite::ANNOUNCE_ALL;
185                 else if (stdalgo::string::equalsci(announceinvites, "ops"))
186                         cmdinvite.announceinvites = Invite::ANNOUNCE_OPS;
187                 else if (stdalgo::string::equalsci(announceinvites, "dynamic"))
188                         cmdinvite.announceinvites = Invite::ANNOUNCE_DYNAMIC;
189                 else
190                         throw ModuleException(announceinvites + " is an invalid <security:announceinvites> value, at " + securitytag->getTagLocation());
191
192                 // In 2.0 we allowed limits of 0 to be set. This is non-standard behaviour
193                 // and will be removed in the next major release.
194                 limitmode.minlimit = optionstag->getBool("allowzerolimit", true) ? 0 : 1;
195
196                 banmode.DoRehash();
197         }
198
199         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
200         {
201                 tokens["KEYLEN"] = ConvToStr(ModeChannelKey::maxkeylen);
202
203                 // Build a map of limits to their mode character.
204                 insp::flat_map<int, std::string> limits;
205                 const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes();
206                 for (ModeParser::ListModeList::const_iterator iter = listmodes.begin(); iter != listmodes.end(); ++iter)
207                 {
208                         const unsigned int limit = (*iter)->GetLowerLimit();
209                         limits[limit].push_back((*iter)->GetModeChar());
210                 }
211
212                 // Generate the MAXLIST token from the limits map.
213                 std::string& buffer = tokens["MAXLIST"];
214                 for (insp::flat_map<int, std::string>::const_iterator iter = limits.begin(); iter != limits.end(); ++iter)
215                 {
216                         if (!buffer.empty())
217                                 buffer.push_back(',');
218
219                         buffer.append(iter->second);
220                         buffer.push_back(':');
221                         buffer.append(ConvToStr(iter->first));
222                 }
223         }
224
225         ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string&, std::string&, const std::string& keygiven) CXX11_OVERRIDE
226         {
227                 if (!chan)
228                         return MOD_RES_PASSTHRU;
229
230                 // Check whether the channel key is correct.
231                 const std::string ckey = chan->GetModeParameter(&keymode);
232                 if (!ckey.empty())
233                 {
234                         ModResult MOD_RESULT;
235                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, keygiven));
236                         if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, keygiven)))
237                         {
238                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
239                                 user->WriteNumeric(ERR_BADCHANNELKEY, chan->name, "Cannot join channel (Incorrect channel key)");
240                                 return MOD_RES_DENY;
241                         }
242                 }
243
244                 // Check whether the invite only mode is set.
245                 if (chan->IsModeSet(inviteonlymode))
246                 {
247                         ModResult MOD_RESULT;
248                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
249                         if (MOD_RESULT != MOD_RES_ALLOW)
250                         {
251                                 user->WriteNumeric(ERR_INVITEONLYCHAN, chan->name, "Cannot join channel (Invite only)");
252                                 return MOD_RES_DENY;
253                         }
254                 }
255
256                 // Check whether the limit would be exceeded by this user joining.
257                 if (chan->IsModeSet(limitmode))
258                 {
259                         ModResult MOD_RESULT;
260                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
261                         if (!MOD_RESULT.check(chan->GetUserCounter() < static_cast<size_t>(limitmode.ext.get(chan))))
262                         {
263                                 user->WriteNumeric(ERR_CHANNELISFULL, chan->name, "Cannot join channel (Channel is full)");
264                                 return MOD_RES_DENY;
265                         }
266                 }
267
268                 // Everything looks okay.
269                 return MOD_RES_PASSTHRU;
270         }
271
272         void OnPostJoin(Membership* memb) CXX11_OVERRIDE
273         {
274                 Channel* const chan = memb->chan;
275                 LocalUser* const localuser = IS_LOCAL(memb->user);
276                 if (localuser)
277                 {
278                         // Remove existing invite, if any
279                         invapi.Remove(localuser, chan);
280
281                         if (chan->topic.length())
282                                 Topic::ShowTopic(localuser, chan);
283
284                         // Show all members of the channel, including invisible (+i) users
285                         cmdnames.SendNames(localuser, chan, true);
286                 }
287         }
288
289         ModResult OnCheckKey(User* user, Channel* chan, const std::string& keygiven) CXX11_OVERRIDE
290         {
291                 // Hook only runs when being invited bypasses +bkl
292                 return IsInvited(user, chan);
293         }
294
295         ModResult OnCheckChannelBan(User* user, Channel* chan) CXX11_OVERRIDE
296         {
297                 // Hook only runs when being invited bypasses +bkl
298                 return IsInvited(user, chan);
299         }
300
301         ModResult OnCheckLimit(User* user, Channel* chan) CXX11_OVERRIDE
302         {
303                 // Hook only runs when being invited bypasses +bkl
304                 return IsInvited(user, chan);
305         }
306
307         ModResult OnCheckInvite(User* user, Channel* chan) CXX11_OVERRIDE
308         {
309                 // Hook always runs
310                 return IsInvited(user, chan);
311         }
312
313         void OnUserDisconnect(LocalUser* user) CXX11_OVERRIDE
314         {
315                 invapi.RemoveAll(user);
316         }
317
318         void OnChannelDelete(Channel* chan) CXX11_OVERRIDE
319         {
320                 // Make sure the channel won't appear in invite lists from now on, don't wait for cull to unset the ext
321                 invapi.RemoveAll(chan);
322         }
323
324         ModResult OnCheckExemption(User* user, Channel* chan, const std::string& restriction) CXX11_OVERRIDE
325         {
326                 if (!exemptions.count(restriction))
327                         return MOD_RES_PASSTHRU;
328
329                 unsigned int mypfx = chan->GetPrefixValue(user);
330                 char minmode = exemptions[restriction];
331
332                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(minmode);
333                 if (mh && mypfx >= mh->GetPrefixRank())
334                         return MOD_RES_ALLOW;
335                 if (mh || minmode == '*')
336                         return MOD_RES_DENY;
337                 return MOD_RES_PASSTHRU;
338         }
339
340         void Prioritize() CXX11_OVERRIDE
341         {
342                 ServerInstance->Modules.SetPriority(this, I_OnPostJoin, PRIORITY_FIRST);
343                 ServerInstance->Modules.SetPriority(this, I_OnUserPreJoin, PRIORITY_LAST);
344         }
345
346         Version GetVersion() CXX11_OVERRIDE
347         {
348                 return Version("Provides the INVITE, JOIN, KICK, NAMES, and TOPIC commands", VF_VENDOR|VF_CORE);
349         }
350 };
351
352 MODULE_INIT(CoreModChannel)