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