]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/mode.cpp
Check perms for removal of oper-only channel modes.
[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 ((chan || (!chan && adding)) && IS_LOCAL(user) && mh->NeedsOper() && !user->HasModePermission(mh))
316         {
317                 /* It's an oper only mode, and they don't have access to it. */
318                 if (user->IsOper())
319                 {
320                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to %sset %s mode %c",
321                                         user->oper->name.c_str(), adding ? "" : "un", type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
322                 }
323                 else
324                 {
325                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Only operators may %sset %s mode %c",
326                                         adding ? "" : "un", type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
327                 }
328                 return MODEACTION_DENY;
329         }
330
331         /* Call the handler for the mode */
332         ModeAction ma = mh->OnModeChange(user, targetuser, chan, parameter, adding);
333
334         if ((needs_param) && (parameter.empty()))
335                 return MODEACTION_DENY;
336
337         if (ma != MODEACTION_ALLOW)
338                 return ma;
339
340         itpair = modewatchermap.equal_range(mh->name);
341         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
342         {
343                 ModeWatcher* mw = i->second;
344                 if (mw->GetModeType() == type)
345                         mw->AfterMode(user, targetuser, chan, parameter, adding);
346         }
347
348         return MODEACTION_ALLOW;
349 }
350
351 void ModeParser::ModeParamsToChangeList(User* user, ModeType type, const std::vector<std::string>& parameters, Modes::ChangeList& changelist, unsigned int beginindex, unsigned int endindex)
352 {
353         if (endindex > parameters.size())
354                 endindex = parameters.size();
355
356         const std::string& mode_sequence = parameters[beginindex];
357
358         bool adding = true;
359         unsigned int param_at = beginindex+1;
360
361         for (std::string::const_iterator letter = mode_sequence.begin(); letter != mode_sequence.end(); letter++)
362         {
363                 unsigned char modechar = *letter;
364                 if (modechar == '+' || modechar == '-')
365                 {
366                         adding = (modechar == '+');
367                         continue;
368                 }
369
370                 ModeHandler *mh = this->FindMode(modechar, type);
371                 if (!mh)
372                 {
373                         /* No mode handler? Unknown mode character then. */
374                         user->WriteNumeric(type == MODETYPE_CHANNEL ? ERR_UNKNOWNMODE : ERR_UNKNOWNSNOMASK, modechar, "is unknown mode char to me");
375                         continue;
376                 }
377
378                 std::string parameter;
379                 if ((mh->NeedsParam(adding)) && (param_at < endindex))
380                         parameter = parameters[param_at++];
381
382                 changelist.push(mh, adding, parameter);
383         }
384 }
385
386 static bool IsModeParamValid(User* user, Channel* targetchannel, User* targetuser, const Modes::Change& item)
387 {
388         // An empty parameter is never acceptable
389         if (item.param.empty())
390         {
391                 item.mh->OnParameterMissing(user, targetuser, targetchannel);
392                 return false;
393         }
394
395         // The parameter cannot begin with a ':' character or contain a space
396         if ((item.param[0] == ':') || (item.param.find(' ') != std::string::npos))
397                 return false;
398
399         return true;
400 }
401
402 // Returns true if we should apply a merged mode, false if we should skip it
403 static bool ShouldApplyMergedMode(Channel* chan, Modes::Change& item)
404 {
405         ModeHandler* mh = item.mh;
406         if ((!chan) || (!chan->IsModeSet(mh)) || (mh->IsListMode()))
407                 // Mode not set here or merge is not applicable, apply the incoming mode
408                 return true;
409
410         // Mode handler decides
411         std::string ours = chan->GetModeParameter(mh);
412         return mh->ResolveModeConflict(item.param, ours, chan);
413 }
414
415 void ModeParser::Process(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags)
416 {
417         // Call ProcessSingle until the entire list is processed, but at least once to ensure
418         // LastParse and LastChangeList are cleared
419         unsigned int processed = 0;
420         do
421         {
422                 unsigned int n = ProcessSingle(user, targetchannel, targetuser, changelist, flags, processed);
423                 processed += n;
424         }
425         while (processed < changelist.size());
426 }
427
428 unsigned int ModeParser::ProcessSingle(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags, unsigned int beginindex)
429 {
430         LastChangeList.clear();
431
432         unsigned int modes_processed = 0;
433         Modes::ChangeList::List& list = changelist.getlist();
434         for (Modes::ChangeList::List::iterator i = list.begin()+beginindex; i != list.end(); ++i)
435         {
436                 modes_processed++;
437
438                 Modes::Change& item = *i;
439                 ModeHandler* mh = item.mh;
440
441                 // If a mode change has been given for a mode that does not exist then reject
442                 // it. This can happen when core_reloadmodule attempts to restore a mode that
443                 // no longer exists.
444                 if (!mh)
445                         continue;
446
447                 // If the mode is supposed to have a parameter then we first take a look at item.param
448                 // and, if we were asked to, also handle mode merges now
449                 if (mh->NeedsParam(item.adding))
450                 {
451                         // Skip the mode if the parameter does not pass basic validation
452                         if (!IsModeParamValid(user, targetchannel, targetuser, item))
453                                 continue;
454
455                         // If this is a merge and we won we don't apply this mode
456                         if ((flags & MODE_MERGE) && (!ShouldApplyMergedMode(targetchannel, item)))
457                                 continue;
458                 }
459
460                 ModeAction ma = TryMode(user, targetuser, targetchannel, item, (!(flags & MODE_CHECKACCESS)));
461
462                 if (ma != MODEACTION_ALLOW)
463                         continue;
464
465                 LastChangeList.push(mh, item.adding, item.param);
466
467                 if (LastChangeList.size() >= ServerInstance->Config->Limits.MaxModes)
468                 {
469                         /* mode sequence is getting too long */
470                         break;
471                 }
472         }
473
474         if (!LastChangeList.empty())
475         {
476                 ClientProtocol::Events::Mode modeevent(user, targetchannel, targetuser, LastChangeList);
477                 if (targetchannel)
478                 {
479                         targetchannel->Write(modeevent);
480                 }
481                 else
482                 {
483                         LocalUser* localtarget = IS_LOCAL(targetuser);
484                         if (localtarget)
485                                 localtarget->Send(modeevent);
486                 }
487
488                 FOREACH_MOD(OnMode, (user, targetuser, targetchannel, LastChangeList, flags));
489         }
490
491         return modes_processed;
492 }
493
494 void ModeParser::ShowListModeList(User* user, Channel* chan, ModeHandler* mh)
495 {
496         {
497                 ModResult MOD_RESULT;
498                 FIRST_MOD_RESULT(OnRawMode, MOD_RESULT, (user, chan, mh, "", true));
499                 if (MOD_RESULT == MOD_RES_DENY)
500                         return;
501
502                 bool display = true;
503
504                 // Ask mode watchers whether it's OK to show the list
505                 std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mh->name);
506                 for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
507                 {
508                         ModeWatcher* mw = i->second;
509                         if (mw->GetModeType() == MODETYPE_CHANNEL)
510                         {
511                                 std::string dummyparam;
512
513                                 if (!mw->BeforeMode(user, NULL, chan, dummyparam, true))
514                                 {
515                                         // A mode watcher doesn't want us to show the list
516                                         display = false;
517                                         break;
518                                 }
519                         }
520                 }
521
522                 if (display)
523                         mh->DisplayList(user, chan);
524                 else
525                         mh->DisplayEmptyList(user, chan);
526         }
527 }
528
529 void ModeParser::CleanMask(std::string &mask)
530 {
531         std::string::size_type pos_of_pling = mask.find_first_of('!');
532         std::string::size_type pos_of_at = mask.find_first_of('@');
533         std::string::size_type pos_of_dot = mask.find_first_of('.');
534         std::string::size_type pos_of_colons = mask.find("::"); /* Because ipv6 addresses are colon delimited -- double so it treats extban as nick */
535
536         if (mask.length() >= 2 && mask[1] == ':')
537                 return; // if it's an extban, don't even try guess how it needs to be formed.
538
539         if ((pos_of_pling == std::string::npos) && (pos_of_at == std::string::npos))
540         {
541                 /* Just a nick, or just a host - or clearly ipv6 (starting with :) */
542                 if ((pos_of_dot == std::string::npos) && (pos_of_colons == std::string::npos) && mask[0] != ':')
543                 {
544                         /* It has no '.' in it, it must be a nick. */
545                         mask.append("!*@*");
546                 }
547                 else
548                 {
549                         /* Got a dot in it? Has to be a host */
550                         mask = "*!*@" + mask;
551                 }
552         }
553         else if ((pos_of_pling == std::string::npos) && (pos_of_at != std::string::npos))
554         {
555                 /* Has an @ but no !, its a user@host */
556                  mask = "*!" + mask;
557         }
558         else if ((pos_of_pling != std::string::npos) && (pos_of_at == std::string::npos))
559         {
560                 /* Has a ! but no @, it must be a nick!ident */
561                 mask.append("@*");
562         }
563 }
564
565 ModeHandler::Id ModeParser::AllocateModeId(ModeType mt)
566 {
567         for (ModeHandler::Id i = 0; i != MODEID_MAX; ++i)
568         {
569                 if (!modehandlersbyid[mt][i])
570                         return i;
571         }
572
573         throw ModuleException("Out of ModeIds");
574 }
575
576 void ModeParser::AddMode(ModeHandler* mh)
577 {
578         if (!ModeParser::IsModeChar(mh->GetModeChar()))
579                 throw ModuleException(InspIRCd::Format("Mode letter for %s is invalid: %c",
580                         mh->name.c_str(), mh->GetModeChar()));
581
582         /* A mode prefix of ',' is not acceptable, it would fuck up server to server.
583          * A mode prefix of ':' will fuck up both server to server, and client to server.
584          * A mode prefix of '#' will mess up /whois and /privmsg
585          */
586         PrefixMode* pm = mh->IsPrefixMode();
587         if (pm)
588         {
589                 if ((pm->GetPrefix() > 126) || (pm->GetPrefix() == ',') || (pm->GetPrefix() == ':') || (pm->GetPrefix() == '#'))
590                         throw ModuleException(InspIRCd::Format("Mode prefix for %s is invalid: %c",
591                                 mh->name.c_str(), pm->GetPrefix()));
592
593                 PrefixMode* otherpm = FindPrefix(pm->GetPrefix());
594                 if (otherpm)
595                         throw ModuleException(InspIRCd::Format("Mode prefix for %s already used by %s from %s: %c",
596                                 mh->name.c_str(), otherpm->name.c_str(), otherpm->creator->ModuleSourceFile.c_str(), pm->GetPrefix()));
597         }
598
599         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
600         if (slot)
601                 throw ModuleException(InspIRCd::Format("Mode letter for %s already used by %s from %s: %c",
602                         mh->name.c_str(), slot->name.c_str(), slot->creator->ModuleSourceFile.c_str(), mh->GetModeChar()));
603
604         // The mode needs an id if it is either a user mode, a simple mode (flag) or a parameter mode.
605         // Otherwise (for listmodes and prefix modes) the id remains MODEID_MAX, which is invalid.
606         ModeHandler::Id modeid = MODEID_MAX;
607         if ((mh->GetModeType() == MODETYPE_USER) || (mh->IsParameterMode()) || (!mh->IsListMode()))
608                 modeid = AllocateModeId(mh->GetModeType());
609
610         std::pair<ModeHandlerMap::iterator, bool> res = modehandlersbyname[mh->GetModeType()].insert(std::make_pair(mh->name, mh));
611         if (!res.second)
612         {
613                 ModeHandler* othermh = res.first->second;
614                 throw ModuleException(InspIRCd::Format("Mode name %s already used by %c from %s",
615                         mh->name.c_str(), othermh->GetModeChar(), othermh->creator->ModuleSourceFile.c_str()));
616         }
617
618         // Everything is fine, add the mode
619
620         // If we allocated an id for this mode then save it and put the mode handler into the slot
621         if (modeid != MODEID_MAX)
622         {
623                 mh->modeid = modeid;
624                 modehandlersbyid[mh->GetModeType()][modeid] = mh;
625         }
626
627         slot = mh;
628         if (pm)
629                 mhlist.prefix.push_back(pm);
630         else if (mh->IsListModeBase())
631                 mhlist.list.push_back(mh->IsListModeBase());
632 }
633
634 bool ModeParser::DelMode(ModeHandler* mh)
635 {
636         if (!ModeParser::IsModeChar(mh->GetModeChar()))
637                 return false;
638
639         ModeHandlerMap& mhmap = modehandlersbyname[mh->GetModeType()];
640         ModeHandlerMap::iterator mhmapit = mhmap.find(mh->name);
641         if ((mhmapit == mhmap.end()) || (mhmapit->second != mh))
642                 return false;
643
644         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
645         if (slot != mh)
646                 return false;
647
648         /* Note: We can't stack here, as we have modes potentially being removed across many different channels.
649          * To stack here we have to make the algorithm slower. Discuss.
650          */
651         switch (mh->GetModeType())
652         {
653                 case MODETYPE_USER:
654                 {
655                         const user_hash& users = ServerInstance->Users->GetUsers();
656                         for (user_hash::const_iterator i = users.begin(); i != users.end(); )
657                         {
658                                 User* user = i->second;
659                                 ++i;
660                                 mh->RemoveMode(user);
661                         }
662                 }
663                 break;
664                 case MODETYPE_CHANNEL:
665                 {
666                         const chan_hash& chans = ServerInstance->GetChans();
667                         for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); )
668                         {
669                                 // The channel may not be in the hash after RemoveMode(), see m_permchannels
670                                 Channel* chan = i->second;
671                                 ++i;
672
673                                 Modes::ChangeList changelist;
674                                 mh->RemoveMode(chan, changelist);
675                                 this->Process(ServerInstance->FakeClient, chan, NULL, changelist, MODE_LOCALONLY);
676                         }
677                 }
678                 break;
679         }
680
681         mhmap.erase(mhmapit);
682         if (mh->GetId() != MODEID_MAX)
683                 modehandlersbyid[mh->GetModeType()][mh->GetId()] = NULL;
684         slot = NULL;
685         if (mh->IsPrefixMode())
686                 mhlist.prefix.erase(std::find(mhlist.prefix.begin(), mhlist.prefix.end(), mh->IsPrefixMode()));
687         else if (mh->IsListModeBase())
688                 mhlist.list.erase(std::find(mhlist.list.begin(), mhlist.list.end(), mh->IsListModeBase()));
689         return true;
690 }
691
692 ModeHandler* ModeParser::FindMode(const std::string& modename, ModeType mt)
693 {
694         ModeHandlerMap& mhmap = modehandlersbyname[mt];
695         ModeHandlerMap::const_iterator it = mhmap.find(modename);
696         if (it != mhmap.end())
697                 return it->second;
698
699         return NULL;
700 }
701
702 ModeHandler* ModeParser::FindMode(unsigned const char modeletter, ModeType mt)
703 {
704         if (!ModeParser::IsModeChar(modeletter))
705                 return NULL;
706
707         return modehandlers[mt][modeletter-65];
708 }
709
710 PrefixMode* ModeParser::FindPrefixMode(unsigned char modeletter)
711 {
712         ModeHandler* mh = FindMode(modeletter, MODETYPE_CHANNEL);
713         if (!mh)
714                 return NULL;
715         return mh->IsPrefixMode();
716 }
717
718 PrefixMode* ModeParser::FindPrefix(unsigned const char pfxletter)
719 {
720         const PrefixModeList& list = GetPrefixModes();
721         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
722         {
723                 PrefixMode* pm = *i;
724                 if (pm->GetPrefix() == pfxletter)
725                         return pm;
726         }
727         return NULL;
728 }
729
730 std::string ModeParser::GiveModeList(ModeType mt)
731 {
732         std::string type1;      /* Listmodes EXCEPT those with a prefix */
733         std::string type2;      /* Modes that take a param when adding or removing */
734         std::string type3;      /* Modes that only take a param when adding */
735         std::string type4;      /* Modes that dont take a param */
736
737         for (unsigned char mode = 'A'; mode <= 'z'; mode++)
738         {
739                 ModeHandler* mh = modehandlers[mt][mode-65];
740                  /* One parameter when adding */
741                 if (mh)
742                 {
743                         if (mh->NeedsParam(true))
744                         {
745                                 PrefixMode* pm = mh->IsPrefixMode();
746                                 if ((mh->IsListMode()) && ((!pm) || (pm->GetPrefix() == 0)))
747                                 {
748                                         type1 += mh->GetModeChar();
749                                 }
750                                 else
751                                 {
752                                         /* ... and one parameter when removing */
753                                         if (mh->NeedsParam(false))
754                                         {
755                                                 /* But not a list mode */
756                                                 if (!pm)
757                                                 {
758                                                         type2 += mh->GetModeChar();
759                                                 }
760                                         }
761                                         else
762                                         {
763                                                 /* No parameters when removing */
764                                                 type3 += mh->GetModeChar();
765                                         }
766                                 }
767                         }
768                         else
769                         {
770                                 type4 += mh->GetModeChar();
771                         }
772                 }
773         }
774
775         return type1 + "," + type2 + "," + type3 + "," + type4;
776 }
777
778 struct PrefixModeSorter
779 {
780         bool operator()(PrefixMode* lhs, PrefixMode* rhs)
781         {
782                 return lhs->GetPrefixRank() < rhs->GetPrefixRank();
783         }
784 };
785
786 std::string ModeParser::BuildPrefixes(bool lettersAndModes)
787 {
788         std::string mletters;
789         std::string mprefixes;
790         std::vector<PrefixMode*> prefixes;
791
792         const PrefixModeList& list = GetPrefixModes();
793         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
794         {
795                 PrefixMode* pm = *i;
796                 if (pm->GetPrefix())
797                         prefixes.push_back(pm);
798         }
799
800         std::sort(prefixes.begin(), prefixes.end(), PrefixModeSorter());
801         for (std::vector<PrefixMode*>::const_reverse_iterator n = prefixes.rbegin(); n != prefixes.rend(); ++n)
802         {
803                 mletters += (*n)->GetPrefix();
804                 mprefixes += (*n)->GetModeChar();
805         }
806
807         return lettersAndModes ? "(" + mprefixes + ")" + mletters : mletters;
808 }
809
810 void ModeParser::AddModeWatcher(ModeWatcher* mw)
811 {
812         modewatchermap.insert(std::make_pair(mw->GetModeName(), mw));
813 }
814
815 bool ModeParser::DelModeWatcher(ModeWatcher* mw)
816 {
817         std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mw->GetModeName());
818         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
819         {
820                 if (i->second == mw)
821                 {
822                         modewatchermap.erase(i);
823                         return true;
824                 }
825         }
826
827         return false;
828 }
829
830 void ModeHandler::RemoveMode(User* user)
831 {
832         // Remove the mode if it's set on the user
833         if (user->IsModeSet(this->GetModeChar()))
834         {
835                 Modes::ChangeList changelist;
836                 changelist.push_remove(this);
837                 ServerInstance->Modes->Process(ServerInstance->FakeClient, NULL, user, changelist, ModeParser::MODE_LOCALONLY);
838         }
839 }
840
841 void ModeHandler::RemoveMode(Channel* channel, Modes::ChangeList& changelist)
842 {
843         if (channel->IsModeSet(this))
844         {
845                 if (this->NeedsParam(false))
846                         // Removing this mode requires a parameter
847                         changelist.push_remove(this, channel->GetModeParameter(this));
848                 else
849                         changelist.push_remove(this);
850         }
851 }
852
853 void PrefixMode::RemoveMode(Channel* chan, Modes::ChangeList& changelist)
854 {
855         const Channel::MemberMap& userlist = chan->GetUsers();
856         for (Channel::MemberMap::const_iterator i = userlist.begin(); i != userlist.end(); ++i)
857         {
858                 if (i->second->HasMode(this))
859                         changelist.push_remove(this, i->first->nick);
860         }
861 }
862
863 bool ModeParser::IsModeChar(char chr)
864 {
865         return ((chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z'));
866 }
867
868 ModeParser::ModeParser()
869 {
870         /* Clear mode handler list */
871         memset(modehandlers, 0, sizeof(modehandlers));
872         memset(modehandlersbyid, 0, sizeof(modehandlersbyid));
873 }
874
875 ModeParser::~ModeParser()
876 {
877 }