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