]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_channel/core_channel.cpp
Alphabetically sort the modes in MAXLIST tokens.
[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                         std::string modes(iter->second);
220                         std::sort(modes.begin(), modes.end());
221
222                         buffer.append(modes);
223                         buffer.push_back(':');
224                         buffer.append(ConvToStr(iter->first));
225                 }
226         }
227
228         ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string&, std::string&, const std::string& keygiven) CXX11_OVERRIDE
229         {
230                 if (!chan)
231                         return MOD_RES_PASSTHRU;
232
233                 // Check whether the channel key is correct.
234                 const std::string ckey = chan->GetModeParameter(&keymode);
235                 if (!ckey.empty())
236                 {
237                         ModResult MOD_RESULT;
238                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, keygiven));
239                         if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, keygiven)))
240                         {
241                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
242                                 user->WriteNumeric(ERR_BADCHANNELKEY, chan->name, "Cannot join channel (Incorrect channel key)");
243                                 return MOD_RES_DENY;
244                         }
245                 }
246
247                 // Check whether the invite only mode is set.
248                 if (chan->IsModeSet(inviteonlymode))
249                 {
250                         ModResult MOD_RESULT;
251                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
252                         if (MOD_RESULT != MOD_RES_ALLOW)
253                         {
254                                 user->WriteNumeric(ERR_INVITEONLYCHAN, chan->name, "Cannot join channel (Invite only)");
255                                 return MOD_RES_DENY;
256                         }
257                 }
258
259                 // Check whether the limit would be exceeded by this user joining.
260                 if (chan->IsModeSet(limitmode))
261                 {
262                         ModResult MOD_RESULT;
263                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
264                         if (!MOD_RESULT.check(chan->GetUserCounter() < static_cast<size_t>(limitmode.ext.get(chan))))
265                         {
266                                 user->WriteNumeric(ERR_CHANNELISFULL, chan->name, "Cannot join channel (Channel is full)");
267                                 return MOD_RES_DENY;
268                         }
269                 }
270
271                 // Everything looks okay.
272                 return MOD_RES_PASSTHRU;
273         }
274
275         void OnPostJoin(Membership* memb) CXX11_OVERRIDE
276         {
277                 Channel* const chan = memb->chan;
278                 LocalUser* const localuser = IS_LOCAL(memb->user);
279                 if (localuser)
280                 {
281                         // Remove existing invite, if any
282                         invapi.Remove(localuser, chan);
283
284                         if (chan->topic.length())
285                                 Topic::ShowTopic(localuser, chan);
286
287                         // Show all members of the channel, including invisible (+i) users
288                         cmdnames.SendNames(localuser, chan, true);
289                 }
290         }
291
292         ModResult OnCheckKey(User* user, Channel* chan, const std::string& keygiven) CXX11_OVERRIDE
293         {
294                 // Hook only runs when being invited bypasses +bkl
295                 return IsInvited(user, chan);
296         }
297
298         ModResult OnCheckChannelBan(User* user, Channel* chan) CXX11_OVERRIDE
299         {
300                 // Hook only runs when being invited bypasses +bkl
301                 return IsInvited(user, chan);
302         }
303
304         ModResult OnCheckLimit(User* user, Channel* chan) CXX11_OVERRIDE
305         {
306                 // Hook only runs when being invited bypasses +bkl
307                 return IsInvited(user, chan);
308         }
309
310         ModResult OnCheckInvite(User* user, Channel* chan) CXX11_OVERRIDE
311         {
312                 // Hook always runs
313                 return IsInvited(user, chan);
314         }
315
316         void OnUserDisconnect(LocalUser* user) CXX11_OVERRIDE
317         {
318                 invapi.RemoveAll(user);
319         }
320
321         void OnChannelDelete(Channel* chan) CXX11_OVERRIDE
322         {
323                 // Make sure the channel won't appear in invite lists from now on, don't wait for cull to unset the ext
324                 invapi.RemoveAll(chan);
325         }
326
327         ModResult OnCheckExemption(User* user, Channel* chan, const std::string& restriction) CXX11_OVERRIDE
328         {
329                 if (!exemptions.count(restriction))
330                         return MOD_RES_PASSTHRU;
331
332                 unsigned int mypfx = chan->GetPrefixValue(user);
333                 char minmode = exemptions[restriction];
334
335                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(minmode);
336                 if (mh && mypfx >= mh->GetPrefixRank())
337                         return MOD_RES_ALLOW;
338                 if (mh || minmode == '*')
339                         return MOD_RES_DENY;
340                 return MOD_RES_PASSTHRU;
341         }
342
343         void Prioritize() CXX11_OVERRIDE
344         {
345                 ServerInstance->Modules.SetPriority(this, I_OnPostJoin, PRIORITY_FIRST);
346                 ServerInstance->Modules.SetPriority(this, I_OnUserPreJoin, PRIORITY_LAST);
347         }
348
349         Version GetVersion() CXX11_OVERRIDE
350         {
351                 return Version("Provides the INVITE, JOIN, KICK, NAMES, and TOPIC commands", VF_VENDOR|VF_CORE);
352         }
353 };
354
355 MODULE_INIT(CoreModChannel)