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