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