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