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