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