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