]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Merge pull request #1225 from SaberUK/master+cppflags
[user/henk/code/inspircd.git] / src / channels.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2006, 2008 Oliver Lupton <oliverlupton@gmail.com>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
9  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
10  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
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 "listmode.h"
28
29 namespace
30 {
31         ChanModeReference ban(NULL, "ban");
32         ChanModeReference inviteonlymode(NULL, "inviteonly");
33         ChanModeReference keymode(NULL, "key");
34         ChanModeReference limitmode(NULL, "limit");
35 }
36
37 Channel::Channel(const std::string &cname, time_t ts)
38         : name(cname), age(ts), topicset(0)
39 {
40         if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
41                 throw CoreException("Cannot create duplicate channel " + cname);
42 }
43
44 void Channel::SetMode(ModeHandler* mh, bool on)
45 {
46         modes[mh->GetId()] = on;
47 }
48
49 void Channel::SetTopic(User* u, const std::string& ntopic, time_t topicts, const std::string* setter)
50 {
51         // Send a TOPIC message to the channel only if the new topic text differs
52         if (this->topic != ntopic)
53         {
54                 this->topic = ntopic;
55                 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
56         }
57
58         // Always update setter and set time
59         if (!setter)
60                 setter = ServerInstance->Config->FullHostInTopic ? &u->GetFullHost() : &u->nick;
61         this->setby.assign(*setter, 0, ServerInstance->Config->Limits.GetMaxMask());
62         this->topicset = topicts;
63
64         FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
65 }
66
67 Membership* Channel::AddUser(User* user)
68 {
69         std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
70         if (!ret.second)
71                 return NULL;
72
73         Membership* memb = new(ret.first->second) Membership(user, this);
74         return memb;
75 }
76
77 void Channel::DelUser(User* user)
78 {
79         MemberMap::iterator it = userlist.find(user);
80         if (it != userlist.end())
81                 DelUser(it);
82 }
83
84 void Channel::CheckDestroy()
85 {
86         if (!userlist.empty())
87                 return;
88
89         ModResult res;
90         FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
91         if (res == MOD_RES_DENY)
92                 return;
93
94         // If the channel isn't in chanlist then it is already in the cull list, don't add it again
95         chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
96         if ((iter == ServerInstance->chanlist.end()) || (iter->second != this))
97                 return;
98
99         FOREACH_MOD(OnChannelDelete, (this));
100         ServerInstance->chanlist.erase(iter);
101         ServerInstance->GlobalCulls.AddItem(this);
102 }
103
104 void Channel::DelUser(const MemberMap::iterator& membiter)
105 {
106         Membership* memb = membiter->second;
107         memb->cull();
108         memb->~Membership();
109         userlist.erase(membiter);
110
111         // If this channel became empty then it should be removed
112         CheckDestroy();
113 }
114
115 Membership* Channel::GetUser(User* user)
116 {
117         MemberMap::iterator i = userlist.find(user);
118         if (i == userlist.end())
119                 return NULL;
120         return i->second;
121 }
122
123 void Channel::SetDefaultModes()
124 {
125         ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
126                 ServerInstance->Config->DefaultModes.c_str());
127         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
128         std::string modeseq;
129         std::string parameter;
130
131         list.GetToken(modeseq);
132
133         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
134         {
135                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
136                 if (mode)
137                 {
138                         if (mode->IsPrefixMode())
139                                 continue;
140
141                         if (mode->NeedsParam(true))
142                         {
143                                 list.GetToken(parameter);
144                                 // If the parameter begins with a ':' then it's invalid
145                                 if (parameter.c_str()[0] == ':')
146                                         continue;
147                         }
148                         else
149                                 parameter.clear();
150
151                         if ((mode->NeedsParam(true)) && (parameter.empty()))
152                                 continue;
153
154                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
155                 }
156         }
157 }
158
159 /*
160  * add a channel to a user, creating the record for it if needed and linking
161  * it to the user record
162  */
163 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
164 {
165         if (user->registered != REG_ALL)
166         {
167                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
168                 return NULL;
169         }
170
171         /*
172          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
173          * We restrict local users to <connect:maxchans> channels.
174          * We restrict local operators to <oper:maxchans> channels.
175          * This is a lot more logical than how it was formerly. -- w00t
176          */
177         if (!override)
178         {
179                 unsigned int maxchans = user->GetClass()->maxchans;
180                 if (user->IsOper())
181                 {
182                         unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
183                         // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
184                         if (!opermaxchans && user->HasPrivPermission("channels/high-join-limit"))
185                                 opermaxchans = ServerInstance->Config->OperMaxChans;
186                         if (opermaxchans)
187                                 maxchans = opermaxchans;
188                 }
189                 if (user->chans.size() >= maxchans)
190                 {
191                         user->WriteNumeric(ERR_TOOMANYCHANNELS, cname, "You are on too many channels");
192                         return NULL;
193                 }
194         }
195
196         // Crop channel name if it's too long
197         if (cname.length() > ServerInstance->Config->Limits.ChanMax)
198                 cname.resize(ServerInstance->Config->Limits.ChanMax);
199
200         Channel* chan = ServerInstance->FindChan(cname);
201         bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
202         std::string privs; // Prefix mode(letter)s to give to the joining user
203
204         if (!chan)
205         {
206                 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
207
208                 if (override == false)
209                 {
210                         // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
211                         ModResult MOD_RESULT;
212                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
213                         if (MOD_RESULT == MOD_RES_DENY)
214                                 return NULL; // A module wasn't happy with the join, abort
215                 }
216
217                 chan = new Channel(cname, ServerInstance->Time());
218                 // Set the default modes on the channel (<options:defaultmodes>)
219                 chan->SetDefaultModes();
220         }
221         else
222         {
223                 /* Already on the channel */
224                 if (chan->HasUser(user))
225                         return NULL;
226
227                 if (override == false)
228                 {
229                         ModResult MOD_RESULT;
230                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
231
232                         // A module explicitly denied the join and (hopefully) generated a message
233                         // describing the situation, so we may stop here without sending anything
234                         if (MOD_RESULT == MOD_RES_DENY)
235                                 return NULL;
236
237                         // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
238                         // most of the time) then proceed to check channel modes +k, +i, +l and bans,
239                         // in this order.
240                         // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
241                         // then this entire section is skipped
242                         if (MOD_RESULT == MOD_RES_PASSTHRU)
243                         {
244                                 std::string ckey = chan->GetModeParameter(keymode);
245                                 if (!ckey.empty())
246                                 {
247                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
248                                         if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
249                                         {
250                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
251                                                 user->WriteNumeric(ERR_BADCHANNELKEY, chan->name, "Cannot join channel (Incorrect channel key)");
252                                                 return NULL;
253                                         }
254                                 }
255
256                                 if (chan->IsModeSet(inviteonlymode))
257                                 {
258                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
259                                         if (MOD_RESULT != MOD_RES_ALLOW)
260                                         {
261                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, chan->name, "Cannot join channel (Invite only)");
262                                                 return NULL;
263                                         }
264                                 }
265
266                                 std::string limit = chan->GetModeParameter(limitmode);
267                                 if (!limit.empty())
268                                 {
269                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
270                                         if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
271                                         {
272                                                 user->WriteNumeric(ERR_CHANNELISFULL, chan->name, "Cannot join channel (Channel is full)");
273                                                 return NULL;
274                                         }
275                                 }
276
277                                 if (chan->IsBanned(user))
278                                 {
279                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, chan->name, "Cannot join channel (You're banned)");
280                                         return NULL;
281                                 }
282                         }
283                 }
284         }
285
286         // We figured that this join is allowed and also created the
287         // channel if it didn't exist before, now do the actual join
288         chan->ForceJoin(user, &privs, false, created_by_local);
289         return chan;
290 }
291
292 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
293 {
294         if (IS_SERVER(user))
295         {
296                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
297                 return NULL;
298         }
299
300         Membership* memb = this->AddUser(user);
301         if (!memb)
302                 return NULL; // Already on the channel
303
304         user->chans.push_front(memb);
305
306         if (privs)
307         {
308                 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
309                 // remote user and his own server set the modes), then set them internally now
310                 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
311                 {
312                         PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
313                         if (mh)
314                         {
315                                 std::string nick = user->nick;
316                                 // Set the mode on the user
317                                 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
318                         }
319                 }
320         }
321
322         // Tell modules about this join, they have the chance now to populate except_list with users we won't send the JOIN (and possibly MODE) to
323         CUList except_list;
324         FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
325
326         this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
327
328         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
329         if ((GetUserCounter() > 1) && (!memb->modes.empty()))
330         {
331                 std::string ms = memb->modes;
332                 for(unsigned int i=0; i < memb->modes.length(); i++)
333                         ms.append(" ").append(user->nick);
334
335                 except_list.insert(user);
336                 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
337         }
338
339         FOREACH_MOD(OnPostJoin, (memb));
340         return memb;
341 }
342
343 bool Channel::IsBanned(User* user)
344 {
345         ModResult result;
346         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
347
348         if (result != MOD_RES_PASSTHRU)
349                 return (result == MOD_RES_DENY);
350
351         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
352         const ListModeBase::ModeList* bans = banlm->GetList(this);
353         if (bans)
354         {
355                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
356                 {
357                         if (CheckBan(user, it->mask))
358                                 return true;
359                 }
360         }
361         return false;
362 }
363
364 bool Channel::CheckBan(User* user, const std::string& mask)
365 {
366         ModResult result;
367         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
368         if (result != MOD_RES_PASSTHRU)
369                 return (result == MOD_RES_DENY);
370
371         // extbans were handled above, if this is one it obviously didn't match
372         if ((mask.length() <= 2) || (mask[1] == ':'))
373                 return false;
374
375         std::string::size_type at = mask.find('@');
376         if (at == std::string::npos)
377                 return false;
378
379         const std::string nickIdent = user->nick + "!" + user->ident;
380         std::string prefix(mask, 0, at);
381         if (InspIRCd::Match(nickIdent, prefix, NULL))
382         {
383                 std::string suffix(mask, at + 1);
384                 if (InspIRCd::Match(user->host, suffix, NULL) ||
385                         InspIRCd::Match(user->dhost, suffix, NULL) ||
386                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
387                         return true;
388         }
389         return false;
390 }
391
392 ModResult Channel::GetExtBanStatus(User *user, char type)
393 {
394         ModResult rv;
395         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
396         if (rv != MOD_RES_PASSTHRU)
397                 return rv;
398
399         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
400         const ListModeBase::ModeList* bans = banlm->GetList(this);
401         if (bans)
402         {
403                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
404                 {
405                         if (CheckBan(user, it->mask))
406                                 return MOD_RES_DENY;
407                 }
408         }
409         return MOD_RES_PASSTHRU;
410 }
411
412 /* Channel::PartUser
413  * Remove a channel from a users record, remove the reference to the Membership object
414  * from the channel and destroy it.
415  */
416 bool Channel::PartUser(User* user, std::string& reason)
417 {
418         MemberMap::iterator membiter = userlist.find(user);
419
420         if (membiter == userlist.end())
421                 return false;
422
423         Membership* memb = membiter->second;
424         CUList except_list;
425         FOREACH_MOD(OnUserPart, (memb, reason, except_list));
426
427         WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
428
429         // Remove this channel from the user's chanlist
430         user->chans.erase(memb);
431         // Remove the Membership from this channel's userlist and destroy it
432         this->DelUser(membiter);
433
434         return true;
435 }
436
437 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
438 {
439         Membership* memb = victimiter->second;
440         CUList except_list;
441         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
442
443         User* victim = memb->user;
444         WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
445
446         victim->chans.erase(memb);
447         this->DelUser(victimiter);
448 }
449
450 void Channel::WriteChannel(User* user, const char* text, ...)
451 {
452         std::string textbuffer;
453         VAFORMAT(textbuffer, text, text);
454         this->WriteChannel(user, textbuffer);
455 }
456
457 void Channel::WriteChannel(User* user, const std::string &text)
458 {
459         const std::string message = ":" + user->GetFullHost() + " " + text;
460
461         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
462         {
463                 if (IS_LOCAL(i->first))
464                         i->first->Write(message);
465         }
466 }
467
468 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
469 {
470         std::string textbuffer;
471         VAFORMAT(textbuffer, text, text);
472         this->WriteChannelWithServ(ServName, textbuffer);
473 }
474
475 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
476 {
477         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
478
479         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
480         {
481                 if (IS_LOCAL(i->first))
482                         i->first->Write(message);
483         }
484 }
485
486 /* write formatted text from a source user to all users on a channel except
487  * for the sender (for privmsg etc) */
488 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
489 {
490         std::string textbuffer;
491         VAFORMAT(textbuffer, text, text);
492         this->WriteAllExceptSender(user, serversource, status, textbuffer);
493 }
494
495 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
496 {
497         std::string textbuffer;
498         VAFORMAT(textbuffer, text, text);
499         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
500         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
501 }
502
503 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
504 {
505         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
506         this->RawWriteAllExcept(user, serversource, status, except_list, message);
507 }
508
509 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
510 {
511         unsigned int minrank = 0;
512         if (status)
513         {
514                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
515                 if (mh)
516                         minrank = mh->GetPrefixRank();
517         }
518         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
519         {
520                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
521                 {
522                         /* User doesn't have the status we're after */
523                         if (minrank && i->second->getRank() < minrank)
524                                 continue;
525
526                         i->first->Write(out);
527                 }
528         }
529 }
530
531 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
532 {
533         CUList except_list;
534         except_list.insert(user);
535         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
536 }
537
538 const char* Channel::ChanModes(bool showkey)
539 {
540         static std::string scratch;
541         std::string sparam;
542
543         scratch.clear();
544
545         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
546         for(int n = 0; n < 64; n++)
547         {
548                 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
549                 if (mh && IsModeSet(mh))
550                 {
551                         scratch.push_back(n + 65);
552
553                         ParamModeBase* pm = mh->IsParameterMode();
554                         if (!pm)
555                                 continue;
556
557                         if (n == 'k' - 65 && !showkey)
558                         {
559                                 sparam += " <key>";
560                         }
561                         else
562                         {
563                                 sparam += ' ';
564                                 pm->GetParameter(this, sparam);
565                         }
566                 }
567         }
568
569         scratch += sparam;
570         return scratch.c_str();
571 }
572
573 void Channel::WriteNotice(const std::string& text)
574 {
575         std::string rawmsg = "NOTICE ";
576         rawmsg.append(this->name).append(" :").append(text);
577         WriteChannelWithServ(ServerInstance->Config->ServerName, rawmsg);
578 }
579
580 /* returns the status character for a given user on a channel, e.g. @ for op,
581  * % for halfop etc. If the user has several modes set, the highest mode
582  * the user has must be returned.
583  */
584 char Membership::GetPrefixChar() const
585 {
586         char pf = 0;
587         unsigned int bestrank = 0;
588
589         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
590         {
591                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
592                 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
593                 {
594                         bestrank = mh->GetPrefixRank();
595                         pf = mh->GetPrefix();
596                 }
597         }
598         return pf;
599 }
600
601 unsigned int Membership::getRank()
602 {
603         char mchar = modes.c_str()[0];
604         unsigned int rv = 0;
605         if (mchar)
606         {
607                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
608                 if (mh)
609                         rv = mh->GetPrefixRank();
610         }
611         return rv;
612 }
613
614 std::string Membership::GetAllPrefixChars() const
615 {
616         std::string ret;
617         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
618         {
619                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
620                 if (mh && mh->GetPrefix())
621                         ret.push_back(mh->GetPrefix());
622         }
623
624         return ret;
625 }
626
627 unsigned int Channel::GetPrefixValue(User* user)
628 {
629         MemberMap::iterator m = userlist.find(user);
630         if (m == userlist.end())
631                 return 0;
632         return m->second->getRank();
633 }
634
635 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
636 {
637         char prefix = delta_mh->GetModeChar();
638         for (unsigned int i = 0; i < modes.length(); i++)
639         {
640                 char mchar = modes[i];
641                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
642                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
643                 {
644                         modes = modes.substr(0,i) +
645                                 (adding ? std::string(1, prefix) : "") +
646                                 modes.substr(mchar == prefix ? i+1 : i);
647                         return adding != (mchar == prefix);
648                 }
649         }
650         if (adding)
651                 modes.push_back(prefix);
652         return adding;
653 }