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