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