]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/mode.cpp
Replace spaces with underscores when checking for class bans.
[user/henk/code/inspircd.git] / src / mode.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2017 B00mX0r <b00mx0r@aureus.pw>
6  *   Copyright (C) 2016-2019 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2012 Shawn Smith <ShawnSmith0828@gmail.com>
10  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
12  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
13  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
14  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
15  *   Copyright (C) 2006-2008, 2010 Craig Edwards <brain@inspircd.org>
16  *
17  * This file is part of InspIRCd.  InspIRCd is free software: you can
18  * redistribute it and/or modify it under the terms of the GNU General Public
19  * License as published by the Free Software Foundation, version 2.
20  *
21  * This program is distributed in the hope that it will be useful, but WITHOUT
22  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
23  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
24  * details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28  */
29
30
31 #include "inspircd.h"
32
33 ModeHandler::ModeHandler(Module* Creator, const std::string& Name, char modeletter, ParamSpec Params, ModeType type, Class mclass)
34         : ServiceProvider(Creator, Name, SERVICE_MODE)
35         , modeid(ModeParser::MODEID_MAX)
36         , parameters_taken(Params)
37         , mode(modeletter)
38         , oper(false)
39         , list(false)
40         , m_type(type)
41         , type_id(mclass)
42         , ranktoset(HALFOP_VALUE)
43         , ranktounset(HALFOP_VALUE)
44 {
45 }
46
47 CullResult ModeHandler::cull()
48 {
49         if (ServerInstance)
50                 ServerInstance->Modes->DelMode(this);
51         return classbase::cull();
52 }
53
54 ModeHandler::~ModeHandler()
55 {
56 }
57
58 bool ModeHandler::NeedsParam(bool adding) const
59 {
60         switch (parameters_taken)
61         {
62                 case PARAM_ALWAYS:
63                         return true;
64                 case PARAM_SETONLY:
65                         return adding;
66                 case PARAM_NONE:
67                         break;
68         }
69         return false;
70 }
71
72 std::string ModeHandler::GetUserParameter(const User* user) const
73 {
74         return "";
75 }
76
77 ModResult ModeHandler::AccessCheck(User*, Channel*, std::string &, bool)
78 {
79         return MOD_RES_PASSTHRU;
80 }
81
82 ModeAction ModeHandler::OnModeChange(User*, User*, Channel*, std::string&, bool)
83 {
84         return MODEACTION_DENY;
85 }
86
87 void ModeHandler::DisplayList(User*, Channel*)
88 {
89 }
90
91 void ModeHandler::DisplayEmptyList(User*, Channel*)
92 {
93 }
94
95 void ModeHandler::OnParameterMissing(User* user, User* dest, Channel* channel)
96 {
97         std::string message = InspIRCd::Format("You must specify a parameter for the %s mode.", name.c_str());
98         if (!syntax.empty())
99                 message.append(InspIRCd::Format(" Syntax: %s.", syntax.c_str()));
100
101         if (channel)
102                 user->WriteNumeric(Numerics::InvalidModeParameter(channel, this, "*", message));
103         else
104                 user->WriteNumeric(Numerics::InvalidModeParameter(dest, this, "*", message));
105 }
106
107 bool ModeHandler::ResolveModeConflict(std::string& theirs, const std::string& ours, Channel*)
108 {
109         return (theirs < ours);
110 }
111
112 void ModeHandler::RegisterService()
113 {
114         ServerInstance->Modes.AddMode(this);
115         ServerInstance->Modules.AddReferent((GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + name, this);
116 }
117
118 ModeAction SimpleUserModeHandler::OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
119 {
120         /* We're either trying to add a mode we already have or
121                 remove a mode we don't have, deny. */
122         if (dest->IsModeSet(this) == adding)
123                 return MODEACTION_DENY;
124
125         /* adding will be either true or false, depending on if we
126                 are adding or removing the mode, since we already checked
127                 to make sure we aren't adding a mode we have or that we
128                 aren't removing a mode we don't have, we don't have to do any
129                 other checks here to see if it's true or false, just add or
130                 remove the mode */
131         dest->SetMode(this, adding);
132
133         return MODEACTION_ALLOW;
134 }
135
136
137 ModeAction SimpleChannelModeHandler::OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
138 {
139         /* We're either trying to add a mode we already have or
140                 remove a mode we don't have, deny. */
141         if (channel->IsModeSet(this) == adding)
142                 return MODEACTION_DENY;
143
144         /* adding will be either true or false, depending on if we
145                 are adding or removing the mode, since we already checked
146                 to make sure we aren't adding a mode we have or that we
147                 aren't removing a mode we don't have, we don't have to do any
148                 other checks here to see if it's true or false, just add or
149                 remove the mode */
150         channel->SetMode(this, adding);
151
152         return MODEACTION_ALLOW;
153 }
154
155 ModeWatcher::ModeWatcher(Module* Creator, const std::string& modename, ModeType type)
156         : mode(modename), m_type(type), creator(Creator)
157 {
158         ServerInstance->Modes->AddModeWatcher(this);
159 }
160
161 ModeWatcher::~ModeWatcher()
162 {
163         ServerInstance->Modes->DelModeWatcher(this);
164 }
165
166 bool ModeWatcher::BeforeMode(User*, User*, Channel*, std::string&, bool)
167 {
168         return true;
169 }
170
171 void ModeWatcher::AfterMode(User*, User*, Channel*, const std::string&, bool)
172 {
173 }
174
175 PrefixMode::PrefixMode(Module* Creator, const std::string& Name, char ModeLetter, unsigned int Rank, char PrefixChar)
176         : ModeHandler(Creator, Name, ModeLetter, PARAM_ALWAYS, MODETYPE_CHANNEL, MC_PREFIX)
177         , prefix(PrefixChar)
178         , prefixrank(Rank)
179         , selfremove(true)
180 {
181         list = true;
182         syntax = "<nick>";
183 }
184
185 ModResult PrefixMode::AccessCheck(User* src, Channel*, std::string& value, bool adding)
186 {
187         if (!adding && src->nick == value && selfremove)
188                 return MOD_RES_ALLOW;
189         return MOD_RES_PASSTHRU;
190 }
191
192 ModeAction PrefixMode::OnModeChange(User* source, User*, Channel* chan, std::string& parameter, bool adding)
193 {
194         User* target;
195         if (IS_LOCAL(source))
196                 target = ServerInstance->FindNickOnly(parameter);
197         else
198                 target = ServerInstance->FindNick(parameter);
199
200         if (!target)
201         {
202                 source->WriteNumeric(Numerics::NoSuchNick(parameter));
203                 return MODEACTION_DENY;
204         }
205
206         Membership* memb = chan->GetUser(target);
207         if (!memb)
208                 return MODEACTION_DENY;
209
210         parameter = target->nick;
211         return (memb->SetPrefix(this, adding) ? MODEACTION_ALLOW : MODEACTION_DENY);
212 }
213
214 void PrefixMode::Update(unsigned int rank, unsigned int setrank, unsigned int unsetrank, bool selfrm)
215 {
216         prefixrank = rank;
217         ranktoset = setrank;
218         ranktounset = unsetrank;
219         selfremove = selfrm;
220 }
221
222 ModeAction ParamModeBase::OnModeChange(User* source, User*, Channel* chan, std::string& parameter, bool adding)
223 {
224         if (adding)
225         {
226                 if (chan->GetModeParameter(this) == parameter)
227                         return MODEACTION_DENY;
228
229                 if (OnSet(source, chan, parameter) != MODEACTION_ALLOW)
230                         return MODEACTION_DENY;
231
232                 chan->SetMode(this, true);
233
234                 // Handler might have changed the parameter internally
235                 parameter.clear();
236                 this->GetParameter(chan, parameter);
237         }
238         else
239         {
240                 if (!chan->IsModeSet(this))
241                         return MODEACTION_DENY;
242                 this->OnUnsetInternal(source, chan);
243                 chan->SetMode(this, false);
244         }
245         return MODEACTION_ALLOW;
246 }
247
248 ModeAction ModeParser::TryMode(User* user, User* targetuser, Channel* chan, Modes::Change& mcitem, bool SkipACL)
249 {
250         ModeType type = chan ? MODETYPE_CHANNEL : MODETYPE_USER;
251
252         ModeHandler* mh = mcitem.mh;
253         bool adding = mcitem.adding;
254         const bool needs_param = mh->NeedsParam(adding);
255
256         std::string& parameter = mcitem.param;
257         // crop mode parameter size to MODE_PARAM_MAX characters
258         if (parameter.length() > MODE_PARAM_MAX && adding)
259                 parameter.erase(MODE_PARAM_MAX);
260
261         ModResult MOD_RESULT;
262         FIRST_MOD_RESULT(OnRawMode, MOD_RESULT, (user, chan, mh, parameter, adding));
263
264         if (IS_LOCAL(user) && (MOD_RESULT == MOD_RES_DENY))
265                 return MODEACTION_DENY;
266
267         const char modechar = mh->GetModeChar();
268
269         if (chan && !SkipACL && (MOD_RESULT != MOD_RES_ALLOW))
270         {
271                 MOD_RESULT = mh->AccessCheck(user, chan, parameter, adding);
272
273                 if (MOD_RESULT == MOD_RES_DENY)
274                         return MODEACTION_DENY;
275                 if (MOD_RESULT == MOD_RES_PASSTHRU)
276                 {
277                         unsigned int neededrank = mh->GetLevelRequired(adding);
278                         /* Compare our rank on the channel against the rank of the required prefix,
279                          * allow if >= ours. Because mIRC and xchat throw a tizz if the modes shown
280                          * in NAMES(X) are not in rank order, we know the most powerful mode is listed
281                          * first, so we don't need to iterate, we just look up the first instead.
282                          */
283                         unsigned int ourrank = chan->GetPrefixValue(user);
284                         if (ourrank < neededrank)
285                         {
286                                 const PrefixMode* neededmh = NULL;
287                                 const PrefixModeList& prefixmodes = GetPrefixModes();
288                                 for (PrefixModeList::const_iterator i = prefixmodes.begin(); i != prefixmodes.end(); ++i)
289                                 {
290                                         const PrefixMode* const privmh = *i;
291                                         if (privmh->GetPrefixRank() >= neededrank)
292                                         {
293                                                 // this mode is sufficient to allow this action
294                                                 if (!neededmh || privmh->GetPrefixRank() < neededmh->GetPrefixRank())
295                                                         neededmh = privmh;
296                                         }
297                                 }
298                                 if (neededmh)
299                                         user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, InspIRCd::Format("You must have channel %s access or above to %sset channel mode %c",
300                                                 neededmh->name.c_str(), adding ? "" : "un", modechar));
301                                 else
302                                         user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, InspIRCd::Format("You cannot %sset channel mode %c", (adding ? "" : "un"), modechar));
303                                 return MODEACTION_DENY;
304                         }
305                 }
306         }
307
308         // Ask mode watchers whether this mode change is OK
309         std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mh->name);
310         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
311         {
312                 ModeWatcher* mw = i->second;
313                 if (mw->GetModeType() == type)
314                 {
315                         if (!mw->BeforeMode(user, targetuser, chan, parameter, adding))
316                                 return MODEACTION_DENY;
317
318                         // A module whacked the parameter completely, and there was one. Abort.
319                         if ((needs_param) && (parameter.empty()))
320                                 return MODEACTION_DENY;
321                 }
322         }
323
324         if ((chan || (!chan && adding)) && IS_LOCAL(user) && mh->NeedsOper() && !user->HasModePermission(mh))
325         {
326                 /* It's an oper only mode, and they don't have access to it. */
327                 if (user->IsOper())
328                 {
329                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to %sset %s mode %c",
330                                         user->oper->name.c_str(), adding ? "" : "un", type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
331                 }
332                 else
333                 {
334                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Only operators may %sset %s mode %c",
335                                         adding ? "" : "un", type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
336                 }
337                 return MODEACTION_DENY;
338         }
339
340         /* Call the handler for the mode */
341         ModeAction ma = mh->OnModeChange(user, targetuser, chan, parameter, adding);
342
343         if ((needs_param) && (parameter.empty()))
344                 return MODEACTION_DENY;
345
346         if (ma != MODEACTION_ALLOW)
347                 return ma;
348
349         itpair = modewatchermap.equal_range(mh->name);
350         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
351         {
352                 ModeWatcher* mw = i->second;
353                 if (mw->GetModeType() == type)
354                         mw->AfterMode(user, targetuser, chan, parameter, adding);
355         }
356
357         return MODEACTION_ALLOW;
358 }
359
360 void ModeParser::ModeParamsToChangeList(User* user, ModeType type, const std::vector<std::string>& parameters, Modes::ChangeList& changelist, unsigned int beginindex, unsigned int endindex)
361 {
362         if (endindex > parameters.size())
363                 endindex = parameters.size();
364
365         const std::string& mode_sequence = parameters[beginindex];
366
367         bool adding = true;
368         unsigned int param_at = beginindex+1;
369
370         for (std::string::const_iterator letter = mode_sequence.begin(); letter != mode_sequence.end(); letter++)
371         {
372                 unsigned char modechar = *letter;
373                 if (modechar == '+' || modechar == '-')
374                 {
375                         adding = (modechar == '+');
376                         continue;
377                 }
378
379                 ModeHandler *mh = this->FindMode(modechar, type);
380                 if (!mh)
381                 {
382                         /* No mode handler? Unknown mode character then. */
383                         user->WriteNumeric(type == MODETYPE_CHANNEL ? ERR_UNKNOWNMODE : ERR_UNKNOWNSNOMASK, modechar, "is an unknown mode character");
384                         continue;
385                 }
386
387                 std::string parameter;
388                 if ((mh->NeedsParam(adding)) && (param_at < endindex))
389                         parameter = parameters[param_at++];
390
391                 changelist.push(mh, adding, parameter);
392         }
393 }
394
395 static bool IsModeParamValid(User* user, Channel* targetchannel, User* targetuser, const Modes::Change& item)
396 {
397         // An empty parameter is never acceptable
398         if (item.param.empty())
399         {
400                 item.mh->OnParameterMissing(user, targetuser, targetchannel);
401                 return false;
402         }
403
404         // The parameter cannot begin with a ':' character or contain a space
405         if ((item.param[0] == ':') || (item.param.find(' ') != std::string::npos))
406                 return false;
407
408         return true;
409 }
410
411 // Returns true if we should apply a merged mode, false if we should skip it
412 static bool ShouldApplyMergedMode(Channel* chan, Modes::Change& item)
413 {
414         ModeHandler* mh = item.mh;
415         if ((!chan) || (!chan->IsModeSet(mh)) || (mh->IsListMode()))
416                 // Mode not set here or merge is not applicable, apply the incoming mode
417                 return true;
418
419         // Mode handler decides
420         std::string ours = chan->GetModeParameter(mh);
421         return mh->ResolveModeConflict(item.param, ours, chan);
422 }
423
424 void ModeParser::Process(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags)
425 {
426         // Call ProcessSingle until the entire list is processed, but at least once to ensure
427         // LastParse and LastChangeList are cleared
428         unsigned int processed = 0;
429         do
430         {
431                 unsigned int n = ProcessSingle(user, targetchannel, targetuser, changelist, flags, processed);
432                 processed += n;
433         }
434         while (processed < changelist.size());
435 }
436
437 unsigned int ModeParser::ProcessSingle(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags, unsigned int beginindex)
438 {
439         LastChangeList.clear();
440
441         unsigned int modes_processed = 0;
442         Modes::ChangeList::List& list = changelist.getlist();
443         for (Modes::ChangeList::List::iterator i = list.begin()+beginindex; i != list.end(); ++i)
444         {
445                 modes_processed++;
446
447                 Modes::Change& item = *i;
448                 ModeHandler* mh = item.mh;
449
450                 // If a mode change has been given for a mode that does not exist then reject
451                 // it. This can happen when core_reloadmodule attempts to restore a mode that
452                 // no longer exists.
453                 if (!mh)
454                         continue;
455
456                 // If the mode is supposed to have a parameter then we first take a look at item.param
457                 // and, if we were asked to, also handle mode merges now
458                 if (mh->NeedsParam(item.adding))
459                 {
460                         // Skip the mode if the parameter does not pass basic validation
461                         if (!IsModeParamValid(user, targetchannel, targetuser, item))
462                                 continue;
463
464                         // If this is a merge and we won we don't apply this mode
465                         if ((flags & MODE_MERGE) && (!ShouldApplyMergedMode(targetchannel, item)))
466                                 continue;
467                 }
468
469                 ModeAction ma = TryMode(user, targetuser, targetchannel, item, (!(flags & MODE_CHECKACCESS)));
470
471                 if (ma != MODEACTION_ALLOW)
472                         continue;
473
474                 LastChangeList.push(mh, item.adding, item.param);
475
476                 if (LastChangeList.size() >= ServerInstance->Config->Limits.MaxModes)
477                 {
478                         /* mode sequence is getting too long */
479                         break;
480                 }
481         }
482
483         if (!LastChangeList.empty())
484         {
485                 ClientProtocol::Events::Mode modeevent(user, targetchannel, targetuser, LastChangeList);
486                 if (targetchannel)
487                 {
488                         targetchannel->Write(modeevent);
489                 }
490                 else
491                 {
492                         LocalUser* localtarget = IS_LOCAL(targetuser);
493                         if (localtarget)
494                                 localtarget->Send(modeevent);
495                 }
496
497                 FOREACH_MOD(OnMode, (user, targetuser, targetchannel, LastChangeList, flags));
498         }
499
500         return modes_processed;
501 }
502
503 void ModeParser::ShowListModeList(User* user, Channel* chan, ModeHandler* mh)
504 {
505         {
506                 ModResult MOD_RESULT;
507                 FIRST_MOD_RESULT(OnRawMode, MOD_RESULT, (user, chan, mh, "", true));
508                 if (MOD_RESULT == MOD_RES_DENY)
509                         return;
510
511                 bool display = true;
512
513                 // Ask mode watchers whether it's OK to show the list
514                 std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mh->name);
515                 for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
516                 {
517                         ModeWatcher* mw = i->second;
518                         if (mw->GetModeType() == MODETYPE_CHANNEL)
519                         {
520                                 std::string dummyparam;
521
522                                 if (!mw->BeforeMode(user, NULL, chan, dummyparam, true))
523                                 {
524                                         // A mode watcher doesn't want us to show the list
525                                         display = false;
526                                         break;
527                                 }
528                         }
529                 }
530
531                 if (display)
532                         mh->DisplayList(user, chan);
533                 else
534                         mh->DisplayEmptyList(user, chan);
535         }
536 }
537
538 void ModeParser::CleanMask(std::string &mask)
539 {
540         std::string::size_type pos_of_pling = mask.find_first_of('!');
541         std::string::size_type pos_of_at = mask.find_first_of('@');
542         std::string::size_type pos_of_dot = mask.find_first_of('.');
543         std::string::size_type pos_of_colons = mask.find("::"); /* Because ipv6 addresses are colon delimited -- double so it treats extban as nick */
544
545         if (mask.length() >= 2 && mask[1] == ':')
546                 return; // if it's an extban, don't even try guess how it needs to be formed.
547
548         if ((pos_of_pling == std::string::npos) && (pos_of_at == std::string::npos))
549         {
550                 /* Just a nick, or just a host - or clearly ipv6 (starting with :) */
551                 if ((pos_of_dot == std::string::npos) && (pos_of_colons == std::string::npos) && mask[0] != ':')
552                 {
553                         /* It has no '.' in it, it must be a nick. */
554                         mask.append("!*@*");
555                 }
556                 else
557                 {
558                         /* Got a dot in it? Has to be a host */
559                         mask = "*!*@" + mask;
560                 }
561         }
562         else if ((pos_of_pling == std::string::npos) && (pos_of_at != std::string::npos))
563         {
564                 /* Has an @ but no !, its a user@host */
565                  mask = "*!" + mask;
566         }
567         else if ((pos_of_pling != std::string::npos) && (pos_of_at == std::string::npos))
568         {
569                 /* Has a ! but no @, it must be a nick!ident */
570                 mask.append("@*");
571         }
572 }
573
574 ModeHandler::Id ModeParser::AllocateModeId(ModeType mt)
575 {
576         for (ModeHandler::Id i = 0; i != MODEID_MAX; ++i)
577         {
578                 if (!modehandlersbyid[mt][i])
579                         return i;
580         }
581
582         throw ModuleException("Out of ModeIds");
583 }
584
585 void ModeParser::AddMode(ModeHandler* mh)
586 {
587         if (!ModeParser::IsModeChar(mh->GetModeChar()))
588                 throw ModuleException(InspIRCd::Format("Mode letter for %s is invalid: %c",
589                         mh->name.c_str(), mh->GetModeChar()));
590
591         /* A mode prefix of ',' is not acceptable, it would fuck up server to server.
592          * A mode prefix of ':' will fuck up both server to server, and client to server.
593          * A mode prefix of '#' will mess up /whois and /privmsg
594          */
595         PrefixMode* pm = mh->IsPrefixMode();
596         if (pm)
597         {
598                 if ((pm->GetPrefix() > 126) || (pm->GetPrefix() == ',') || (pm->GetPrefix() == ':') || (pm->GetPrefix() == '#'))
599                         throw ModuleException(InspIRCd::Format("Mode prefix for %s is invalid: %c",
600                                 mh->name.c_str(), pm->GetPrefix()));
601
602                 PrefixMode* otherpm = FindPrefix(pm->GetPrefix());
603                 if (otherpm)
604                         throw ModuleException(InspIRCd::Format("Mode prefix for %s already used by %s from %s: %c",
605                                 mh->name.c_str(), otherpm->name.c_str(), otherpm->creator->ModuleSourceFile.c_str(), pm->GetPrefix()));
606         }
607
608         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
609         if (slot)
610                 throw ModuleException(InspIRCd::Format("Mode letter for %s already used by %s from %s: %c",
611                         mh->name.c_str(), slot->name.c_str(), slot->creator->ModuleSourceFile.c_str(), mh->GetModeChar()));
612
613         // The mode needs an id if it is either a user mode, a simple mode (flag) or a parameter mode.
614         // Otherwise (for listmodes and prefix modes) the id remains MODEID_MAX, which is invalid.
615         ModeHandler::Id modeid = MODEID_MAX;
616         if ((mh->GetModeType() == MODETYPE_USER) || (mh->IsParameterMode()) || (!mh->IsListMode()))
617                 modeid = AllocateModeId(mh->GetModeType());
618
619         std::pair<ModeHandlerMap::iterator, bool> res = modehandlersbyname[mh->GetModeType()].insert(std::make_pair(mh->name, mh));
620         if (!res.second)
621         {
622                 ModeHandler* othermh = res.first->second;
623                 throw ModuleException(InspIRCd::Format("Mode name %s already used by %c from %s",
624                         mh->name.c_str(), othermh->GetModeChar(), othermh->creator->ModuleSourceFile.c_str()));
625         }
626
627         // Everything is fine, add the mode
628
629         // If we allocated an id for this mode then save it and put the mode handler into the slot
630         if (modeid != MODEID_MAX)
631         {
632                 mh->modeid = modeid;
633                 modehandlersbyid[mh->GetModeType()][modeid] = mh;
634         }
635
636         slot = mh;
637         if (pm)
638                 mhlist.prefix.push_back(pm);
639         else if (mh->IsListModeBase())
640                 mhlist.list.push_back(mh->IsListModeBase());
641 }
642
643 bool ModeParser::DelMode(ModeHandler* mh)
644 {
645         if (!ModeParser::IsModeChar(mh->GetModeChar()))
646                 return false;
647
648         ModeHandlerMap& mhmap = modehandlersbyname[mh->GetModeType()];
649         ModeHandlerMap::iterator mhmapit = mhmap.find(mh->name);
650         if ((mhmapit == mhmap.end()) || (mhmapit->second != mh))
651                 return false;
652
653         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
654         if (slot != mh)
655                 return false;
656
657         /* Note: We can't stack here, as we have modes potentially being removed across many different channels.
658          * To stack here we have to make the algorithm slower. Discuss.
659          */
660         switch (mh->GetModeType())
661         {
662                 case MODETYPE_USER:
663                 {
664                         const user_hash& users = ServerInstance->Users->GetUsers();
665                         for (user_hash::const_iterator i = users.begin(); i != users.end(); )
666                         {
667                                 User* user = i->second;
668                                 ++i;
669                                 mh->RemoveMode(user);
670                         }
671                 }
672                 break;
673                 case MODETYPE_CHANNEL:
674                 {
675                         const chan_hash& chans = ServerInstance->GetChans();
676                         for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); )
677                         {
678                                 // The channel may not be in the hash after RemoveMode(), see m_permchannels
679                                 Channel* chan = i->second;
680                                 ++i;
681
682                                 Modes::ChangeList changelist;
683                                 mh->RemoveMode(chan, changelist);
684                                 this->Process(ServerInstance->FakeClient, chan, NULL, changelist, MODE_LOCALONLY);
685                         }
686                 }
687                 break;
688         }
689
690         mhmap.erase(mhmapit);
691         if (mh->GetId() != MODEID_MAX)
692                 modehandlersbyid[mh->GetModeType()][mh->GetId()] = NULL;
693         slot = NULL;
694         if (mh->IsPrefixMode())
695                 mhlist.prefix.erase(std::find(mhlist.prefix.begin(), mhlist.prefix.end(), mh->IsPrefixMode()));
696         else if (mh->IsListModeBase())
697                 mhlist.list.erase(std::find(mhlist.list.begin(), mhlist.list.end(), mh->IsListModeBase()));
698         return true;
699 }
700
701 ModeHandler* ModeParser::FindMode(const std::string& modename, ModeType mt)
702 {
703         ModeHandlerMap& mhmap = modehandlersbyname[mt];
704         ModeHandlerMap::const_iterator it = mhmap.find(modename);
705         if (it != mhmap.end())
706                 return it->second;
707
708         return NULL;
709 }
710
711 ModeHandler* ModeParser::FindMode(unsigned const char modeletter, ModeType mt)
712 {
713         if (!ModeParser::IsModeChar(modeletter))
714                 return NULL;
715
716         return modehandlers[mt][modeletter-65];
717 }
718
719 PrefixMode* ModeParser::FindPrefixMode(unsigned char modeletter)
720 {
721         ModeHandler* mh = FindMode(modeletter, MODETYPE_CHANNEL);
722         if (!mh)
723                 return NULL;
724         return mh->IsPrefixMode();
725 }
726
727 PrefixMode* ModeParser::FindPrefix(unsigned const char pfxletter)
728 {
729         const PrefixModeList& list = GetPrefixModes();
730         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
731         {
732                 PrefixMode* pm = *i;
733                 if (pm->GetPrefix() == pfxletter)
734                         return pm;
735         }
736         return NULL;
737 }
738
739 std::string ModeParser::GiveModeList(ModeType mt)
740 {
741         std::string type1;      /* Listmodes EXCEPT those with a prefix */
742         std::string type2;      /* Modes that take a param when adding or removing */
743         std::string type3;      /* Modes that only take a param when adding */
744         std::string type4;      /* Modes that dont take a param */
745
746         for (unsigned char mode = 'A'; mode <= 'z'; mode++)
747         {
748                 ModeHandler* mh = modehandlers[mt][mode-65];
749                  /* One parameter when adding */
750                 if (mh)
751                 {
752                         if (mh->NeedsParam(true))
753                         {
754                                 PrefixMode* pm = mh->IsPrefixMode();
755                                 if ((mh->IsListMode()) && ((!pm) || (pm->GetPrefix() == 0)))
756                                 {
757                                         type1 += mh->GetModeChar();
758                                 }
759                                 else
760                                 {
761                                         /* ... and one parameter when removing */
762                                         if (mh->NeedsParam(false))
763                                         {
764                                                 /* But not a list mode */
765                                                 if (!pm)
766                                                 {
767                                                         type2 += mh->GetModeChar();
768                                                 }
769                                         }
770                                         else
771                                         {
772                                                 /* No parameters when removing */
773                                                 type3 += mh->GetModeChar();
774                                         }
775                                 }
776                         }
777                         else
778                         {
779                                 type4 += mh->GetModeChar();
780                         }
781                 }
782         }
783
784         return type1 + "," + type2 + "," + type3 + "," + type4;
785 }
786
787 struct PrefixModeSorter
788 {
789         bool operator()(PrefixMode* lhs, PrefixMode* rhs)
790         {
791                 return lhs->GetPrefixRank() < rhs->GetPrefixRank();
792         }
793 };
794
795 std::string ModeParser::BuildPrefixes(bool lettersAndModes)
796 {
797         std::string mletters;
798         std::string mprefixes;
799         std::vector<PrefixMode*> prefixes;
800
801         const PrefixModeList& list = GetPrefixModes();
802         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
803         {
804                 PrefixMode* pm = *i;
805                 if (pm->GetPrefix())
806                         prefixes.push_back(pm);
807         }
808
809         std::sort(prefixes.begin(), prefixes.end(), PrefixModeSorter());
810         for (std::vector<PrefixMode*>::const_reverse_iterator n = prefixes.rbegin(); n != prefixes.rend(); ++n)
811         {
812                 mletters += (*n)->GetPrefix();
813                 mprefixes += (*n)->GetModeChar();
814         }
815
816         return lettersAndModes ? "(" + mprefixes + ")" + mletters : mletters;
817 }
818
819 void ModeParser::AddModeWatcher(ModeWatcher* mw)
820 {
821         modewatchermap.insert(std::make_pair(mw->GetModeName(), mw));
822 }
823
824 bool ModeParser::DelModeWatcher(ModeWatcher* mw)
825 {
826         std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mw->GetModeName());
827         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
828         {
829                 if (i->second == mw)
830                 {
831                         modewatchermap.erase(i);
832                         return true;
833                 }
834         }
835
836         return false;
837 }
838
839 void ModeHandler::RemoveMode(User* user)
840 {
841         // Remove the mode if it's set on the user
842         if (user->IsModeSet(this->GetModeChar()))
843         {
844                 Modes::ChangeList changelist;
845                 changelist.push_remove(this);
846                 ServerInstance->Modes->Process(ServerInstance->FakeClient, NULL, user, changelist, ModeParser::MODE_LOCALONLY);
847         }
848 }
849
850 void ModeHandler::RemoveMode(Channel* channel, Modes::ChangeList& changelist)
851 {
852         if (channel->IsModeSet(this))
853         {
854                 if (this->NeedsParam(false))
855                         // Removing this mode requires a parameter
856                         changelist.push_remove(this, channel->GetModeParameter(this));
857                 else
858                         changelist.push_remove(this);
859         }
860 }
861
862 void PrefixMode::RemoveMode(Channel* chan, Modes::ChangeList& changelist)
863 {
864         const Channel::MemberMap& userlist = chan->GetUsers();
865         for (Channel::MemberMap::const_iterator i = userlist.begin(); i != userlist.end(); ++i)
866         {
867                 if (i->second->HasMode(this))
868                         changelist.push_remove(this, i->first->nick);
869         }
870 }
871
872 bool ModeParser::IsModeChar(char chr)
873 {
874         return ((chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z'));
875 }
876
877 ModeParser::ModeParser()
878 {
879         /* Clear mode handler list */
880         memset(modehandlers, 0, sizeof(modehandlers));
881         memset(modehandlersbyid, 0, sizeof(modehandlersbyid));
882 }
883
884 ModeParser::~ModeParser()
885 {
886 }