]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/mode.cpp
Implement IRCv3 message tag support.
[user/henk/code/inspircd.git] / src / mode.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2012 Shawn Smith <shawn@inspircd.org>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2004-2008 Craig Edwards <craigedwards@brainbox.cc>
10  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27
28 ModeHandler::ModeHandler(Module* Creator, const std::string& Name, char modeletter, ParamSpec Params, ModeType type, Class mclass)
29         : ServiceProvider(Creator, Name, SERVICE_MODE)
30         , modeid(ModeParser::MODEID_MAX)
31         , parameters_taken(Params)
32         , mode(modeletter)
33         , oper(false)
34         , list(false)
35         , m_type(type)
36         , type_id(mclass)
37         , ranktoset(HALFOP_VALUE)
38         , ranktounset(HALFOP_VALUE)
39 {
40 }
41
42 CullResult ModeHandler::cull()
43 {
44         if (ServerInstance)
45                 ServerInstance->Modes->DelMode(this);
46         return classbase::cull();
47 }
48
49 ModeHandler::~ModeHandler()
50 {
51 }
52
53 bool ModeHandler::NeedsParam(bool adding) const
54 {
55         switch (parameters_taken)
56         {
57                 case PARAM_ALWAYS:
58                         return true;
59                 case PARAM_SETONLY:
60                         return adding;
61                 case PARAM_NONE:
62                         break;
63         }
64         return false;
65 }
66
67 std::string ModeHandler::GetUserParameter(const User* user) const
68 {
69         return "";
70 }
71
72 ModResult ModeHandler::AccessCheck(User*, Channel*, std::string &, bool)
73 {
74         return MOD_RES_PASSTHRU;
75 }
76
77 ModeAction ModeHandler::OnModeChange(User*, User*, Channel*, std::string&, bool)
78 {
79         return MODEACTION_DENY;
80 }
81
82 void ModeHandler::DisplayList(User*, Channel*)
83 {
84 }
85
86 void ModeHandler::DisplayEmptyList(User*, Channel*)
87 {
88 }
89
90 void ModeHandler::OnParameterMissing(User* user, User* dest, Channel* channel)
91 {
92         const std::string message = InspIRCd::Format("You must specify a parameter for the %s mode", name.c_str());
93         if (channel)
94                 user->WriteNumeric(Numerics::InvalidModeParameter(channel, this, "*", message));
95         else
96                 user->WriteNumeric(Numerics::InvalidModeParameter(dest, this, "*", message));
97 }
98
99 bool ModeHandler::ResolveModeConflict(std::string& theirs, const std::string& ours, Channel*)
100 {
101         return (theirs < ours);
102 }
103
104 void ModeHandler::RegisterService()
105 {
106         ServerInstance->Modes.AddMode(this);
107         ServerInstance->Modules.AddReferent((GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + name, this);
108 }
109
110 ModeAction SimpleUserModeHandler::OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
111 {
112         /* We're either trying to add a mode we already have or
113                 remove a mode we don't have, deny. */
114         if (dest->IsModeSet(this) == adding)
115                 return MODEACTION_DENY;
116
117         /* adding will be either true or false, depending on if we
118                 are adding or removing the mode, since we already checked
119                 to make sure we aren't adding a mode we have or that we
120                 aren't removing a mode we don't have, we don't have to do any
121                 other checks here to see if it's true or false, just add or
122                 remove the mode */
123         dest->SetMode(this, adding);
124
125         return MODEACTION_ALLOW;
126 }
127
128
129 ModeAction SimpleChannelModeHandler::OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
130 {
131         /* We're either trying to add a mode we already have or
132                 remove a mode we don't have, deny. */
133         if (channel->IsModeSet(this) == adding)
134                 return MODEACTION_DENY;
135
136         /* adding will be either true or false, depending on if we
137                 are adding or removing the mode, since we already checked
138                 to make sure we aren't adding a mode we have or that we
139                 aren't removing a mode we don't have, we don't have to do any
140                 other checks here to see if it's true or false, just add or
141                 remove the mode */
142         channel->SetMode(this, adding);
143
144         return MODEACTION_ALLOW;
145 }
146
147 ModeWatcher::ModeWatcher(Module* Creator, const std::string& modename, ModeType type)
148         : mode(modename), m_type(type), creator(Creator)
149 {
150         ServerInstance->Modes->AddModeWatcher(this);
151 }
152
153 ModeWatcher::~ModeWatcher()
154 {
155         ServerInstance->Modes->DelModeWatcher(this);
156 }
157
158 bool ModeWatcher::BeforeMode(User*, User*, Channel*, std::string&, bool)
159 {
160         return true;
161 }
162
163 void ModeWatcher::AfterMode(User*, User*, Channel*, const std::string&, bool)
164 {
165 }
166
167 PrefixMode::PrefixMode(Module* Creator, const std::string& Name, char ModeLetter, unsigned int Rank, char PrefixChar)
168         : ModeHandler(Creator, Name, ModeLetter, PARAM_ALWAYS, MODETYPE_CHANNEL, MC_PREFIX)
169         , prefix(PrefixChar)
170         , prefixrank(Rank)
171         , selfremove(true)
172 {
173         list = true;
174 }
175
176 ModResult PrefixMode::AccessCheck(User* src, Channel*, std::string& value, bool adding)
177 {
178         if (!adding && src->nick == value && selfremove)
179                 return MOD_RES_ALLOW;
180         return MOD_RES_PASSTHRU;
181 }
182
183 ModeAction PrefixMode::OnModeChange(User* source, User*, Channel* chan, std::string& parameter, bool adding)
184 {
185         User* target;
186         if (IS_LOCAL(source))
187                 target = ServerInstance->FindNickOnly(parameter);
188         else
189                 target = ServerInstance->FindNick(parameter);
190
191         if (!target)
192         {
193                 source->WriteNumeric(Numerics::NoSuchNick(parameter));
194                 return MODEACTION_DENY;
195         }
196
197         Membership* memb = chan->GetUser(target);
198         if (!memb)
199                 return MODEACTION_DENY;
200
201         parameter = target->nick;
202         return (memb->SetPrefix(this, adding) ? MODEACTION_ALLOW : MODEACTION_DENY);
203 }
204
205 void PrefixMode::Update(unsigned int rank, unsigned int setrank, unsigned int unsetrank, bool selfrm)
206 {
207         prefixrank = rank;
208         ranktoset = setrank;
209         ranktounset = unsetrank;
210         selfremove = selfrm;
211 }
212
213 ModeAction ParamModeBase::OnModeChange(User* source, User*, Channel* chan, std::string& parameter, bool adding)
214 {
215         if (adding)
216         {
217                 if (chan->GetModeParameter(this) == parameter)
218                         return MODEACTION_DENY;
219
220                 if (OnSet(source, chan, parameter) != MODEACTION_ALLOW)
221                         return MODEACTION_DENY;
222
223                 chan->SetMode(this, true);
224
225                 // Handler might have changed the parameter internally
226                 parameter.clear();
227                 this->GetParameter(chan, parameter);
228         }
229         else
230         {
231                 if (!chan->IsModeSet(this))
232                         return MODEACTION_DENY;
233                 this->OnUnsetInternal(source, chan);
234                 chan->SetMode(this, false);
235         }
236         return MODEACTION_ALLOW;
237 }
238
239 ModeAction ModeParser::TryMode(User* user, User* targetuser, Channel* chan, Modes::Change& mcitem, bool SkipACL)
240 {
241         ModeType type = chan ? MODETYPE_CHANNEL : MODETYPE_USER;
242
243         ModeHandler* mh = mcitem.mh;
244         bool adding = mcitem.adding;
245         const bool needs_param = mh->NeedsParam(adding);
246
247         std::string& parameter = mcitem.param;
248         // crop mode parameter size to 250 characters
249         if (parameter.length() > 250 && adding)
250                 parameter.erase(250);
251
252         ModResult MOD_RESULT;
253         FIRST_MOD_RESULT(OnRawMode, MOD_RESULT, (user, chan, mh, parameter, adding));
254
255         if (IS_LOCAL(user) && (MOD_RESULT == MOD_RES_DENY))
256                 return MODEACTION_DENY;
257
258         const char modechar = mh->GetModeChar();
259
260         if (chan && !SkipACL && (MOD_RESULT != MOD_RES_ALLOW))
261         {
262                 MOD_RESULT = mh->AccessCheck(user, chan, parameter, adding);
263
264                 if (MOD_RESULT == MOD_RES_DENY)
265                         return MODEACTION_DENY;
266                 if (MOD_RESULT == MOD_RES_PASSTHRU)
267                 {
268                         unsigned int neededrank = mh->GetLevelRequired(adding);
269                         /* Compare our rank on the channel against the rank of the required prefix,
270                          * allow if >= ours. Because mIRC and xchat throw a tizz if the modes shown
271                          * in NAMES(X) are not in rank order, we know the most powerful mode is listed
272                          * first, so we don't need to iterate, we just look up the first instead.
273                          */
274                         unsigned int ourrank = chan->GetPrefixValue(user);
275                         if (ourrank < neededrank)
276                         {
277                                 const PrefixMode* neededmh = NULL;
278                                 const PrefixModeList& prefixmodes = GetPrefixModes();
279                                 for (PrefixModeList::const_iterator i = prefixmodes.begin(); i != prefixmodes.end(); ++i)
280                                 {
281                                         const PrefixMode* const privmh = *i;
282                                         if (privmh->GetPrefixRank() >= neededrank)
283                                         {
284                                                 // this mode is sufficient to allow this action
285                                                 if (!neededmh || privmh->GetPrefixRank() < neededmh->GetPrefixRank())
286                                                         neededmh = privmh;
287                                         }
288                                 }
289                                 if (neededmh)
290                                         user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, InspIRCd::Format("You must have channel %s access or above to %sset channel mode %c",
291                                                 neededmh->name.c_str(), adding ? "" : "un", modechar));
292                                 else
293                                         user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, InspIRCd::Format("You cannot %sset channel mode %c", (adding ? "" : "un"), modechar));
294                                 return MODEACTION_DENY;
295                         }
296                 }
297         }
298
299         // Ask mode watchers whether this mode change is OK
300         std::pair<ModeWatcherMap::iterator, ModeWatcherMap::iterator> itpair = modewatchermap.equal_range(mh->name);
301         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
302         {
303                 ModeWatcher* mw = i->second;
304                 if (mw->GetModeType() == type)
305                 {
306                         if (!mw->BeforeMode(user, targetuser, chan, parameter, adding))
307                                 return MODEACTION_DENY;
308
309                         // A module whacked the parameter completely, and there was one. Abort.
310                         if ((needs_param) && (parameter.empty()))
311                                 return MODEACTION_DENY;
312                 }
313         }
314
315         if (IS_LOCAL(user) && !user->IsOper())
316         {
317                 const std::bitset<64>& disabled = (type == MODETYPE_CHANNEL) ? ServerInstance->Config->DisabledCModes : ServerInstance->Config->DisabledUModes;
318                 if (disabled.test(modechar - 'A'))
319                 {
320                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - %s mode %c has been locked by the administrator",
321                                 type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
322                         return MODEACTION_DENY;
323                 }
324         }
325
326         if ((adding) && (IS_LOCAL(user)) && (mh->NeedsOper()) && (!user->HasModePermission(mh)))
327         {
328                 /* It's an oper only mode, and they don't have access to it. */
329                 if (user->IsOper())
330                 {
331                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Oper type %s does not have access to set %s mode %c",
332                                         user->oper->name.c_str(), type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
333                 }
334                 else
335                 {
336                         user->WriteNumeric(ERR_NOPRIVILEGES, InspIRCd::Format("Permission Denied - Only operators may set %s mode %c",
337                                         type == MODETYPE_CHANNEL ? "channel" : "user", modechar));
338                 }
339                 return MODEACTION_DENY;
340         }
341
342         /* Call the handler for the mode */
343         ModeAction ma = mh->OnModeChange(user, targetuser, chan, parameter, adding);
344
345         if ((needs_param) && (parameter.empty()))
346                 return MODEACTION_DENY;
347
348         if (ma != MODEACTION_ALLOW)
349                 return ma;
350
351         itpair = modewatchermap.equal_range(mh->name);
352         for (ModeWatcherMap::iterator i = itpair.first; i != itpair.second; ++i)
353         {
354                 ModeWatcher* mw = i->second;
355                 if (mw->GetModeType() == type)
356                         mw->AfterMode(user, targetuser, chan, parameter, adding);
357         }
358
359         return MODEACTION_ALLOW;
360 }
361
362 void ModeParser::ModeParamsToChangeList(User* user, ModeType type, const std::vector<std::string>& parameters, Modes::ChangeList& changelist, unsigned int beginindex, unsigned int endindex)
363 {
364         if (endindex > parameters.size())
365                 endindex = parameters.size();
366
367         const std::string& mode_sequence = parameters[beginindex];
368
369         bool adding = true;
370         unsigned int param_at = beginindex+1;
371
372         for (std::string::const_iterator letter = mode_sequence.begin(); letter != mode_sequence.end(); letter++)
373         {
374                 unsigned char modechar = *letter;
375                 if (modechar == '+' || modechar == '-')
376                 {
377                         adding = (modechar == '+');
378                         continue;
379                 }
380
381                 ModeHandler *mh = this->FindMode(modechar, type);
382                 if (!mh)
383                 {
384                         /* No mode handler? Unknown mode character then. */
385                         user->WriteNumeric(type == MODETYPE_CHANNEL ? ERR_UNKNOWNMODE : ERR_UNKNOWNSNOMASK, modechar, "is unknown mode char to me");
386                         continue;
387                 }
388
389                 std::string parameter;
390                 if ((mh->NeedsParam(adding)) && (param_at < endindex))
391                         parameter = parameters[param_at++];
392
393                 changelist.push(mh, adding, parameter);
394         }
395 }
396
397 static bool IsModeParamValid(User* user, Channel* targetchannel, User* targetuser, const Modes::Change& item)
398 {
399         // An empty parameter is never acceptable
400         if (item.param.empty())
401         {
402                 item.mh->OnParameterMissing(user, targetuser, targetchannel);
403                 return false;
404         }
405
406         // The parameter cannot begin with a ':' character or contain a space
407         if ((item.param[0] == ':') || (item.param.find(' ') != std::string::npos))
408                 return false;
409
410         return true;
411 }
412
413 // Returns true if we should apply a merged mode, false if we should skip it
414 static bool ShouldApplyMergedMode(Channel* chan, Modes::Change& item)
415 {
416         ModeHandler* mh = item.mh;
417         if ((!chan) || (!chan->IsModeSet(mh)) || (mh->IsListMode()))
418                 // Mode not set here or merge is not applicable, apply the incoming mode
419                 return true;
420
421         // Mode handler decides
422         std::string ours = chan->GetModeParameter(mh);
423         return mh->ResolveModeConflict(item.param, ours, chan);
424 }
425
426 void ModeParser::Process(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags)
427 {
428         // Call ProcessSingle until the entire list is processed, but at least once to ensure
429         // LastParse and LastChangeList are cleared
430         unsigned int processed = 0;
431         do
432         {
433                 unsigned int n = ProcessSingle(user, targetchannel, targetuser, changelist, flags, processed);
434                 processed += n;
435         }
436         while (processed < changelist.size());
437 }
438
439 unsigned int ModeParser::ProcessSingle(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags, unsigned int beginindex)
440 {
441         LastChangeList.clear();
442
443         unsigned int modes_processed = 0;
444         Modes::ChangeList::List& list = changelist.getlist();
445         for (Modes::ChangeList::List::iterator i = list.begin()+beginindex; i != list.end(); ++i)
446         {
447                 modes_processed++;
448
449                 Modes::Change& item = *i;
450                 ModeHandler* mh = item.mh;
451
452                 // If a mode change has been given for a mode that does not exist then reject
453                 // it. This can happen when core_reloadmodule attempts to restore a mode that
454                 // no longer exists.
455                 if (!mh)
456                         continue;
457
458                 // If the mode is supposed to have a parameter then we first take a look at item.param
459                 // and, if we were asked to, also handle mode merges now
460                 if (mh->NeedsParam(item.adding))
461                 {
462                         // Skip the mode if the parameter does not pass basic validation
463                         if (!IsModeParamValid(user, targetchannel, targetuser, item))
464                                 continue;
465
466                         // If this is a merge and we won we don't apply this mode
467                         if ((flags & MODE_MERGE) && (!ShouldApplyMergedMode(targetchannel, item)))
468                                 continue;
469                 }
470
471                 ModeAction ma = TryMode(user, targetuser, targetchannel, item, (!(flags & MODE_CHECKACCESS)));
472
473                 if (ma != MODEACTION_ALLOW)
474                         continue;
475
476                 LastChangeList.push(mh, item.adding, item.param);
477
478                 if (LastChangeList.size() >= ServerInstance->Config->Limits.MaxModes)
479                 {
480                         /* mode sequence is getting too long */
481                         break;
482                 }
483         }
484
485         if (!LastChangeList.empty())
486         {
487                 ClientProtocol::Events::Mode modeevent(user, targetchannel, targetuser, LastChangeList);
488                 if (targetchannel)
489                 {
490                         targetchannel->Write(modeevent);
491                 }
492                 else
493                 {
494                         LocalUser* localtarget = IS_LOCAL(targetuser);
495                         if (localtarget)
496                                 localtarget->Send(modeevent);
497                 }
498
499                 FOREACH_MOD(OnMode, (user, targetuser, targetchannel, LastChangeList, flags));
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 bool ModeParser::IsModeChar(char chr)
890 {
891         return ((chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z'));
892 }
893
894 ModeParser::ModeParser()
895 {
896         /* Clear mode handler list */
897         memset(modehandlers, 0, sizeof(modehandlers));
898         memset(modehandlersbyid, 0, sizeof(modehandlersbyid));
899 }
900
901 ModeParser::~ModeParser()
902 {
903 }