]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/mode.cpp
Replace irc::modestacker usage with the new ModeParser::Process()
[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)
429 {
430         const std::string& mode_sequence = parameters[1];
431
432         bool adding = true;
433         unsigned int param_at = 2;
434
435         for (std::string::const_iterator letter = mode_sequence.begin(); letter != mode_sequence.end(); letter++)
436         {
437                 unsigned char modechar = *letter;
438                 if (modechar == '+' || modechar == '-')
439                 {
440                         adding = (modechar == '+');
441                         continue;
442                 }
443
444                 ModeHandler *mh = this->FindMode(modechar, type);
445                 if (!mh)
446                 {
447                         /* No mode handler? Unknown mode character then. */
448                         user->WriteNumeric(type == MODETYPE_CHANNEL ? ERR_UNKNOWNMODE : ERR_UNKNOWNSNOMASK, "%c :is unknown mode char to me", modechar);
449                         continue;
450                 }
451
452                 std::string parameter;
453                 if (mh->GetNumParams(adding) && param_at < parameters.size())
454                         parameter = parameters[param_at++];
455
456                 changelist.push(mh, adding, parameter);
457         }
458 }
459
460 static bool IsModeParamValid(User* user, Channel* targetchannel, User* targetuser, const Modes::Change& item)
461 {
462         // An empty parameter is never acceptable
463         if (item.param.empty())
464         {
465                 item.mh->OnParameterMissing(user, targetuser, targetchannel);
466                 return false;
467         }
468
469         // The parameter cannot begin with a ':' character or contain a space
470         if ((item.param[0] == ':') || (item.param.find(' ') != std::string::npos))
471                 return false;
472
473         return true;
474 }
475
476 // Returns true if we should apply a merged mode, false if we should skip it
477 static bool ShouldApplyMergedMode(Channel* chan, Modes::Change& item)
478 {
479         ModeHandler* mh = item.mh;
480         if ((!chan) || (!chan->IsModeSet(mh)) || (mh->IsListMode()))
481                 // Mode not set here or merge is not applicable, apply the incoming mode
482                 return true;
483
484         // Mode handler decides
485         std::string ours = chan->GetModeParameter(mh);
486         return mh->ResolveModeConflict(item.param, ours, chan);
487 }
488
489 void ModeParser::Process(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags)
490 {
491         // Call ProcessSingle until the entire list is processed, but at least once to ensure
492         // LastParse and LastChangeList are cleared
493         unsigned int processed = 0;
494         do
495         {
496                 unsigned int n = ProcessSingle(user, targetchannel, targetuser, changelist, flags, processed);
497                 processed += n;
498         }
499         while (processed < changelist.size());
500 }
501
502 unsigned int ModeParser::ProcessSingle(User* user, Channel* targetchannel, User* targetuser, Modes::ChangeList& changelist, ModeProcessFlag flags, unsigned int beginindex)
503 {
504         LastParse.clear();
505         LastChangeList.clear();
506
507         unsigned int modes_processed = 0;
508         std::string output_mode;
509         std::string output_parameters;
510
511         char output_pm = '\0'; // current output state, '+' or '-'
512         Modes::ChangeList::List& list = changelist.getlist();
513         for (Modes::ChangeList::List::iterator i = list.begin()+beginindex; i != list.end(); ++i)
514         {
515                 modes_processed++;
516
517                 Modes::Change& item = *i;
518                 ModeHandler* mh = item.mh;
519
520                 // If the mode is supposed to have a parameter then we first take a look at item.param
521                 // and, if we were asked to, also handle mode merges now
522                 if (mh->GetNumParams(item.adding))
523                 {
524                         // Skip the mode if the parameter does not pass basic validation
525                         if (!IsModeParamValid(user, targetchannel, targetuser, item))
526                                 continue;
527
528                         // If this is a merge and we won we don't apply this mode
529                         if ((flags & MODE_MERGE) && (!ShouldApplyMergedMode(targetchannel, item)))
530                                 continue;
531                 }
532
533                 ModeAction ma = TryMode(user, targetuser, targetchannel, item, (!(flags & MODE_CHECKACCESS)));
534
535                 if (ma != MODEACTION_ALLOW)
536                         continue;
537
538                 char needed_pm = item.adding ? '+' : '-';
539                 if (needed_pm != output_pm)
540                 {
541                         output_pm = needed_pm;
542                         output_mode.append(1, output_pm);
543                 }
544                 output_mode.push_back(mh->GetModeChar());
545
546                 if (!item.param.empty())
547                 {
548                         output_parameters.push_back(' ');
549                         output_parameters.append(item.param);
550                 }
551                 LastChangeList.push(mh, item.adding, item.param);
552
553                 if ((output_mode.length() + output_parameters.length() > 450)
554                                 || (output_mode.length() > 100)
555                                 || (LastChangeList.size() >= ServerInstance->Config->Limits.MaxModes))
556                 {
557                         /* mode sequence is getting too long */
558                         break;
559                 }
560         }
561
562         if (!output_mode.empty())
563         {
564                 LastParse = targetchannel ? targetchannel->name : targetuser->nick;
565                 LastParse.append(" ");
566                 LastParse.append(output_mode);
567                 LastParse.append(output_parameters);
568
569                 if (targetchannel)
570                         targetchannel->WriteChannel(user, "MODE " + LastParse);
571                 else
572                         targetuser->WriteFrom(user, "MODE " + LastParse);
573
574                 FOREACH_MOD(OnMode, (user, targetuser, targetchannel, LastChangeList, flags, output_mode));
575         }
576
577         return modes_processed;
578 }
579
580 void ModeParser::DisplayListModes(User* user, Channel* chan, const std::string& mode_sequence)
581 {
582         seq++;
583
584         for (std::string::const_iterator letter = mode_sequence.begin(); letter != mode_sequence.end(); letter++)
585         {
586                 unsigned char mletter = *letter;
587                 if (mletter == '+')
588                         continue;
589
590                 /* Ensure the user doesnt request the same mode twice,
591                  * so they cant flood themselves off out of idiocy.
592                  */
593                 if (sent[mletter] == seq)
594                         continue;
595
596                 sent[mletter] = seq;
597
598                 ModeHandler *mh = this->FindMode(mletter, MODETYPE_CHANNEL);
599
600                 if (!mh || !mh->IsListMode())
601                         return;
602
603                 ModResult MOD_RESULT;
604                 FIRST_MOD_RESULT(OnRawMode, MOD_RESULT, (user, chan, mh, "", true));
605                 if (MOD_RESULT == MOD_RES_DENY)
606                         continue;
607
608                 bool display = true;
609                 if (!user->HasPrivPermission("channels/auspex") && ServerInstance->Config->HideModeLists[mletter] && (chan->GetPrefixValue(user) < HALFOP_VALUE))
610                 {
611                         user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You do not have access to view the +%c list",
612                                 chan->name.c_str(), mletter);
613                         display = false;
614                 }
615
616                 // Ask mode watchers whether it's OK to show the list
617                 std::pair<ModeWatchIter, ModeWatchIter> itpair = modewatchermap.equal_range(mh->name);
618                 for (ModeWatchIter i = itpair.first; i != itpair.second; ++i)
619                 {
620                         ModeWatcher* mw = i->second;
621                         if (mw->GetModeType() == MODETYPE_CHANNEL)
622                         {
623                                 std::string dummyparam;
624
625                                 if (!mw->BeforeMode(user, NULL, chan, dummyparam, true))
626                                 {
627                                         // A mode watcher doesn't want us to show the list
628                                         display = false;
629                                         break;
630                                 }
631                         }
632                 }
633
634                 if (display)
635                         mh->DisplayList(user, chan);
636                 else
637                         mh->DisplayEmptyList(user, chan);
638         }
639 }
640
641 void ModeParser::CleanMask(std::string &mask)
642 {
643         std::string::size_type pos_of_pling = mask.find_first_of('!');
644         std::string::size_type pos_of_at = mask.find_first_of('@');
645         std::string::size_type pos_of_dot = mask.find_first_of('.');
646         std::string::size_type pos_of_colons = mask.find("::"); /* Because ipv6 addresses are colon delimited -- double so it treats extban as nick */
647
648         if (mask.length() >= 2 && mask[1] == ':')
649                 return; // if it's an extban, don't even try guess how it needs to be formed.
650
651         if ((pos_of_pling == std::string::npos) && (pos_of_at == std::string::npos))
652         {
653                 /* Just a nick, or just a host - or clearly ipv6 (starting with :) */
654                 if ((pos_of_dot == std::string::npos) && (pos_of_colons == std::string::npos) && mask[0] != ':')
655                 {
656                         /* It has no '.' in it, it must be a nick. */
657                         mask.append("!*@*");
658                 }
659                 else
660                 {
661                         /* Got a dot in it? Has to be a host */
662                         mask = "*!*@" + mask;
663                 }
664         }
665         else if ((pos_of_pling == std::string::npos) && (pos_of_at != std::string::npos))
666         {
667                 /* Has an @ but no !, its a user@host */
668                  mask = "*!" + mask;
669         }
670         else if ((pos_of_pling != std::string::npos) && (pos_of_at == std::string::npos))
671         {
672                 /* Has a ! but no @, it must be a nick!ident */
673                 mask.append("@*");
674         }
675 }
676
677 ModeHandler::Id ModeParser::AllocateModeId(ModeType mt)
678 {
679         for (ModeHandler::Id i = 0; i != MODEID_MAX; ++i)
680         {
681                 if (!modehandlersbyid[mt][i])
682                         return i;
683         }
684
685         throw ModuleException("Out of ModeIds");
686 }
687
688 void ModeParser::AddMode(ModeHandler* mh)
689 {
690         /* Yes, i know, this might let people declare modes like '_' or '^'.
691          * If they do that, thats their problem, and if i ever EVER see an
692          * official InspIRCd developer do that, i'll beat them with a paddle!
693          */
694         if ((mh->GetModeChar() < 'A') || (mh->GetModeChar() > 'z'))
695                 throw ModuleException("Invalid letter for mode " + mh->name);
696
697         /* A mode prefix of ',' is not acceptable, it would fuck up server to server.
698          * A mode prefix of ':' will fuck up both server to server, and client to server.
699          * A mode prefix of '#' will mess up /whois and /privmsg
700          */
701         PrefixMode* pm = mh->IsPrefixMode();
702         if (pm)
703         {
704                 if ((pm->GetPrefix() > 126) || (pm->GetPrefix() == ',') || (pm->GetPrefix() == ':') || (pm->GetPrefix() == '#'))
705                         throw ModuleException("Invalid prefix for mode " + mh->name);
706
707                 if (FindPrefix(pm->GetPrefix()))
708                         throw ModuleException("Prefix already exists for mode " + mh->name);
709         }
710
711         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
712         if (slot)
713                 throw ModuleException("Letter is already in use for mode " + mh->name);
714
715         // The mode needs an id if it is either a user mode, a simple mode (flag) or a parameter mode.
716         // Otherwise (for listmodes and prefix modes) the id remains MODEID_MAX, which is invalid.
717         ModeHandler::Id modeid = MODEID_MAX;
718         if ((mh->GetModeType() == MODETYPE_USER) || (mh->IsParameterMode()) || (!mh->IsListMode()))
719                 modeid = AllocateModeId(mh->GetModeType());
720
721         if (!modehandlersbyname[mh->GetModeType()].insert(std::make_pair(mh->name, mh)).second)
722                 throw ModuleException("Mode name already in use: " + mh->name);
723
724         // Everything is fine, add the mode
725
726         // If we allocated an id for this mode then save it and put the mode handler into the slot
727         if (modeid != MODEID_MAX)
728         {
729                 mh->modeid = modeid;
730                 modehandlersbyid[mh->GetModeType()][modeid] = mh;
731         }
732
733         slot = mh;
734         if (pm)
735                 mhlist.prefix.push_back(pm);
736         else if (mh->IsListModeBase())
737                 mhlist.list.push_back(mh->IsListModeBase());
738
739         RecreateModeListFor004Numeric();
740 }
741
742 bool ModeParser::DelMode(ModeHandler* mh)
743 {
744         if ((mh->GetModeChar() < 'A') || (mh->GetModeChar() > 'z'))
745                 return false;
746
747         ModeHandlerMap& mhmap = modehandlersbyname[mh->GetModeType()];
748         ModeHandlerMap::iterator mhmapit = mhmap.find(mh->name);
749         if ((mhmapit == mhmap.end()) || (mhmapit->second != mh))
750                 return false;
751
752         ModeHandler*& slot = modehandlers[mh->GetModeType()][mh->GetModeChar()-65];
753         if (slot != mh)
754                 return false;
755
756         /* Note: We can't stack here, as we have modes potentially being removed across many different channels.
757          * To stack here we have to make the algorithm slower. Discuss.
758          */
759         switch (mh->GetModeType())
760         {
761                 case MODETYPE_USER:
762                 {
763                         const user_hash& users = ServerInstance->Users->GetUsers();
764                         for (user_hash::const_iterator i = users.begin(); i != users.end(); )
765                         {
766                                 User* user = i->second;
767                                 ++i;
768                                 mh->RemoveMode(user);
769                         }
770                 }
771                 break;
772                 case MODETYPE_CHANNEL:
773                 {
774                         const chan_hash& chans = ServerInstance->GetChans();
775                         for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); )
776                         {
777                                 // The channel may not be in the hash after RemoveMode(), see m_permchannels
778                                 Channel* chan = i->second;
779                                 ++i;
780
781                                 irc::modestacker stack(false);
782                                 mh->RemoveMode(chan, stack);
783
784                                 std::vector<std::string> stackresult;
785                                 stackresult.push_back(chan->name);
786                                 while (stack.GetStackedLine(stackresult))
787                                 {
788                                         this->Process(stackresult, ServerInstance->FakeClient, MODE_LOCALONLY);
789                                         stackresult.erase(stackresult.begin() + 1, stackresult.end());
790                                 }
791                         }
792                 }
793                 break;
794         }
795
796         mhmap.erase(mhmapit);
797         if (mh->GetId() != MODEID_MAX)
798                 modehandlersbyid[mh->GetModeType()][mh->GetId()] = NULL;
799         slot = NULL;
800         if (mh->IsPrefixMode())
801                 mhlist.prefix.erase(std::find(mhlist.prefix.begin(), mhlist.prefix.end(), mh->IsPrefixMode()));
802         else if (mh->IsListModeBase())
803                 mhlist.list.erase(std::find(mhlist.list.begin(), mhlist.list.end(), mh->IsListModeBase()));
804
805         RecreateModeListFor004Numeric();
806         return true;
807 }
808
809 ModeHandler* ModeParser::FindMode(const std::string& modename, ModeType mt)
810 {
811         ModeHandlerMap& mhmap = modehandlersbyname[mt];
812         ModeHandlerMap::const_iterator it = mhmap.find(modename);
813         if (it != mhmap.end())
814                 return it->second;
815
816         return NULL;
817 }
818
819 ModeHandler* ModeParser::FindMode(unsigned const char modeletter, ModeType mt)
820 {
821         if ((modeletter < 'A') || (modeletter > 'z'))
822                 return NULL;
823
824         return modehandlers[mt][modeletter-65];
825 }
826
827 PrefixMode* ModeParser::FindPrefixMode(unsigned char modeletter)
828 {
829         ModeHandler* mh = FindMode(modeletter, MODETYPE_CHANNEL);
830         if (!mh)
831                 return NULL;
832         return mh->IsPrefixMode();
833 }
834
835 std::string ModeParser::CreateModeList(ModeType mt, bool needparam)
836 {
837         std::string modestr;
838
839         for (unsigned char mode = 'A'; mode <= 'z'; mode++)
840         {
841                 ModeHandler* mh = modehandlers[mt][mode-65];
842                 if ((mh) && ((!needparam) || (mh->GetNumParams(true))))
843                         modestr.push_back(mode);
844         }
845
846         return modestr;
847 }
848
849 void ModeParser::RecreateModeListFor004Numeric()
850 {
851         Cached004ModeList = CreateModeList(MODETYPE_USER) + " " + CreateModeList(MODETYPE_CHANNEL) + " " + CreateModeList(MODETYPE_CHANNEL, true);
852 }
853
854 PrefixMode* ModeParser::FindPrefix(unsigned const char pfxletter)
855 {
856         const PrefixModeList& list = GetPrefixModes();
857         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
858         {
859                 PrefixMode* pm = *i;
860                 if (pm->GetPrefix() == pfxletter)
861                         return pm;
862         }
863         return NULL;
864 }
865
866 std::string ModeParser::GiveModeList(ModeType mt)
867 {
868         std::string type1;      /* Listmodes EXCEPT those with a prefix */
869         std::string type2;      /* Modes that take a param when adding or removing */
870         std::string type3;      /* Modes that only take a param when adding */
871         std::string type4;      /* Modes that dont take a param */
872
873         for (unsigned char mode = 'A'; mode <= 'z'; mode++)
874         {
875                 ModeHandler* mh = modehandlers[mt][mode-65];
876                  /* One parameter when adding */
877                 if (mh)
878                 {
879                         if (mh->GetNumParams(true))
880                         {
881                                 PrefixMode* pm = mh->IsPrefixMode();
882                                 if ((mh->IsListMode()) && ((!pm) || (pm->GetPrefix() == 0)))
883                                 {
884                                         type1 += mh->GetModeChar();
885                                 }
886                                 else
887                                 {
888                                         /* ... and one parameter when removing */
889                                         if (mh->GetNumParams(false))
890                                         {
891                                                 /* But not a list mode */
892                                                 if (!pm)
893                                                 {
894                                                         type2 += mh->GetModeChar();
895                                                 }
896                                         }
897                                         else
898                                         {
899                                                 /* No parameters when removing */
900                                                 type3 += mh->GetModeChar();
901                                         }
902                                 }
903                         }
904                         else
905                         {
906                                 type4 += mh->GetModeChar();
907                         }
908                 }
909         }
910
911         return type1 + "," + type2 + "," + type3 + "," + type4;
912 }
913
914 std::string ModeParser::BuildPrefixes(bool lettersAndModes)
915 {
916         std::string mletters;
917         std::string mprefixes;
918         std::map<int,std::pair<char,char> > prefixes;
919
920         const PrefixModeList& list = GetPrefixModes();
921         for (PrefixModeList::const_iterator i = list.begin(); i != list.end(); ++i)
922         {
923                 PrefixMode* pm = *i;
924                 if (pm->GetPrefix())
925                         prefixes[pm->GetPrefixRank()] = std::make_pair(pm->GetPrefix(), pm->GetModeChar());
926         }
927
928         for(std::map<int,std::pair<char,char> >::reverse_iterator n = prefixes.rbegin(); n != prefixes.rend(); n++)
929         {
930                 mletters = mletters + n->second.first;
931                 mprefixes = mprefixes + n->second.second;
932         }
933
934         return lettersAndModes ? "(" + mprefixes + ")" + mletters : mletters;
935 }
936
937 void ModeParser::AddModeWatcher(ModeWatcher* mw)
938 {
939         modewatchermap.insert(std::make_pair(mw->GetModeName(), mw));
940 }
941
942 bool ModeParser::DelModeWatcher(ModeWatcher* mw)
943 {
944         std::pair<ModeWatchIter, ModeWatchIter> itpair = modewatchermap.equal_range(mw->GetModeName());
945         for (ModeWatchIter i = itpair.first; i != itpair.second; ++i)
946         {
947                 if (i->second == mw)
948                 {
949                         modewatchermap.erase(i);
950                         return true;
951                 }
952         }
953
954         return false;
955 }
956
957 void ModeHandler::RemoveMode(User* user)
958 {
959         // Remove the mode if it's set on the user
960         if (user->IsModeSet(this->GetModeChar()))
961         {
962                 std::vector<std::string> parameters;
963                 parameters.push_back(user->nick);
964                 parameters.push_back("-");
965                 parameters[1].push_back(this->GetModeChar());
966                 ServerInstance->Modes->Process(parameters, ServerInstance->FakeClient, ModeParser::MODE_LOCALONLY);
967         }
968 }
969
970 void ModeHandler::RemoveMode(Channel* channel, irc::modestacker& stack)
971 {
972         if (channel->IsModeSet(this))
973         {
974                 if (this->GetNumParams(false))
975                         // Removing this mode requires a parameter
976                         stack.Push(this->GetModeChar(), channel->GetModeParameter(this));
977                 else
978                         stack.Push(this->GetModeChar());
979         }
980 }
981
982 void PrefixMode::RemoveMode(Channel* chan, irc::modestacker& stack)
983 {
984         const Channel::MemberMap& userlist = chan->GetUsers();
985         for (Channel::MemberMap::const_iterator i = userlist.begin(); i != userlist.end(); ++i)
986         {
987                 if (i->second->hasMode(this->GetModeChar()))
988                         stack.Push(this->GetModeChar(), i->first->nick);
989         }
990 }
991
992 struct builtin_modes
993 {
994         SimpleChannelModeHandler s;
995         SimpleChannelModeHandler p;
996         SimpleChannelModeHandler m;
997         SimpleChannelModeHandler t;
998
999         SimpleChannelModeHandler n;
1000         SimpleChannelModeHandler i;
1001         ModeChannelKey k;
1002         ModeChannelLimit l;
1003
1004         ModeChannelBan b;
1005         ModeChannelOp o;
1006         ModeChannelVoice v;
1007
1008         SimpleUserModeHandler ui;
1009         ModeUserOperator uo;
1010         ModeUserServerNoticeMask us;
1011
1012         builtin_modes()
1013                 : s(NULL, "secret", 's')
1014                 , p(NULL, "private", 'p')
1015                 , m(NULL, "moderated", 'm')
1016                 , t(NULL, "topiclock", 't')
1017                 , n(NULL, "noextmsg", 'n')
1018                 , i(NULL, "inviteonly", 'i')
1019                 , ui(NULL, "invisible", 'i')
1020         {
1021         }
1022
1023         void init()
1024         {
1025                 ServiceProvider* modes[] = { &s, &p, &m, &t, &n, &i, &k, &l, &b, &o, &v,
1026                                                                          &ui, &uo, &us };
1027                 ServerInstance->Modules->AddServices(modes, sizeof(modes)/sizeof(ServiceProvider*));
1028         }
1029 };
1030
1031 static builtin_modes static_modes;
1032
1033 void ModeParser::InitBuiltinModes()
1034 {
1035         static_modes.init();
1036         static_modes.b.DoRehash();
1037 }
1038
1039 ModeParser::ModeParser()
1040 {
1041         /* Clear mode handler list */
1042         memset(modehandlers, 0, sizeof(modehandlers));
1043         memset(modehandlersbyid, 0, sizeof(modehandlersbyid));
1044
1045         seq = 0;
1046         memset(&sent, 0, sizeof(sent));
1047 }
1048
1049 ModeParser::~ModeParser()
1050 {
1051 }