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