2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
31 ChanModeReference ban(NULL, "ban");
32 ChanModeReference inviteonlymode(NULL, "inviteonly");
33 ChanModeReference keymode(NULL, "key");
34 ChanModeReference limitmode(NULL, "limit");
35 ChanModeReference secretmode(NULL, "secret");
36 ChanModeReference privatemode(NULL, "private");
37 UserModeReference invisiblemode(NULL, "invisible");
40 Channel::Channel(const std::string &cname, time_t ts)
41 : name(cname), age(ts), topicset(0)
43 if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
44 throw CoreException("Cannot create duplicate channel " + cname);
47 void Channel::SetMode(ModeHandler* mh, bool on)
49 modes[mh->GetId()] = on;
52 void Channel::SetTopic(User* u, const std::string& ntopic)
54 this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
55 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
56 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
57 this->topicset = ServerInstance->Time();
59 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
62 Membership* Channel::AddUser(User* user)
64 std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
68 Membership* memb = new(ret.first->second) Membership(user, this);
72 void Channel::DelUser(User* user)
74 MemberMap::iterator it = userlist.find(user);
75 if (it != userlist.end())
79 void Channel::CheckDestroy()
81 if (!userlist.empty())
85 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
86 if (res == MOD_RES_DENY)
89 // If the channel isn't in chanlist then it is already in the cull list, don't add it again
90 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
91 if ((iter == ServerInstance->chanlist.end()) || (iter->second != this))
94 FOREACH_MOD(OnChannelDelete, (this));
95 ServerInstance->chanlist.erase(iter);
97 ServerInstance->GlobalCulls.AddItem(this);
100 void Channel::DelUser(const MemberMap::iterator& membiter)
102 Membership* memb = membiter->second;
105 userlist.erase(membiter);
107 // If this channel became empty then it should be removed
111 Membership* Channel::GetUser(User* user)
113 MemberMap::iterator i = userlist.find(user);
114 if (i == userlist.end())
119 void Channel::SetDefaultModes()
121 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
122 ServerInstance->Config->DefaultModes.c_str());
123 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
125 std::string parameter;
127 list.GetToken(modeseq);
129 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
131 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
134 if (mode->IsPrefixMode())
137 if (mode->GetNumParams(true))
139 list.GetToken(parameter);
140 // If the parameter begins with a ':' then it's invalid
141 if (parameter.c_str()[0] == ':')
147 if ((mode->GetNumParams(true)) && (parameter.empty()))
150 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
156 * add a channel to a user, creating the record for it if needed and linking
157 * it to the user record
159 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
161 if (user->registered != REG_ALL)
163 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
168 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
169 * We restrict local users to <connect:maxchans> channels.
170 * We restrict local operators to <oper:maxchans> channels.
171 * This is a lot more logical than how it was formerly. -- w00t
175 unsigned int maxchans = user->GetClass()->maxchans;
178 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
179 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
181 opermaxchans = ServerInstance->Config->OperMaxChans;
183 maxchans = opermaxchans;
185 if (user->chans.size() >= maxchans)
187 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
192 // Crop channel name if it's too long
193 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
194 cname.resize(ServerInstance->Config->Limits.ChanMax);
196 Channel* chan = ServerInstance->FindChan(cname);
197 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
198 std::string privs; // Prefix mode(letter)s to give to the joining user
202 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
204 if (override == false)
206 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
207 ModResult MOD_RESULT;
208 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
209 if (MOD_RESULT == MOD_RES_DENY)
210 return NULL; // A module wasn't happy with the join, abort
213 chan = new Channel(cname, ServerInstance->Time());
214 // Set the default modes on the channel (<options:defaultmodes>)
215 chan->SetDefaultModes();
219 /* Already on the channel */
220 if (chan->HasUser(user))
223 if (override == false)
225 ModResult MOD_RESULT;
226 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
228 // A module explicitly denied the join and (hopefully) generated a message
229 // describing the situation, so we may stop here without sending anything
230 if (MOD_RESULT == MOD_RES_DENY)
233 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
234 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
236 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
237 // then this entire section is skipped
238 if (MOD_RESULT == MOD_RES_PASSTHRU)
240 std::string ckey = chan->GetModeParameter(keymode);
241 bool invited = user->IsInvited(chan);
242 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
246 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
247 if (!MOD_RESULT.check((ckey == key) || can_bypass))
249 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
250 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
255 if (chan->IsModeSet(inviteonlymode))
257 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
258 if (!MOD_RESULT.check(invited))
260 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
265 std::string limit = chan->GetModeParameter(limitmode);
268 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
269 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
271 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
276 if (chan->IsBanned(user) && !can_bypass)
278 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
283 * If the user has invites for this channel, remove them now
284 * after a successful join so they don't build up.
288 user->RemoveInvite(chan);
294 // We figured that this join is allowed and also created the
295 // channel if it didn't exist before, now do the actual join
296 chan->ForceJoin(user, &privs, false, created_by_local);
300 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
304 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
308 Membership* memb = this->AddUser(user);
310 return NULL; // Already on the channel
312 user->chans.push_front(memb);
316 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
317 // remote user and his own server set the modes), then set them internally now
318 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
320 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
323 std::string nick = user->nick;
324 // Set the mode on the user
325 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
330 // 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
332 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
334 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
336 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
337 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
339 std::string ms = memb->modes;
340 for(unsigned int i=0; i < memb->modes.length(); i++)
341 ms.append(" ").append(user->nick);
343 except_list.insert(user);
344 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
351 user->WriteNumeric(RPL_TOPIC, "%s :%s", this->name.c_str(), this->topic.c_str());
352 user->WriteNumeric(RPL_TOPICTIME, "%s %s %lu", this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
354 this->UserList(user);
357 FOREACH_MOD(OnPostJoin, (memb));
361 bool Channel::IsBanned(User* user)
364 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
366 if (result != MOD_RES_PASSTHRU)
367 return (result == MOD_RES_DENY);
369 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
370 const ListModeBase::ModeList* bans = banlm->GetList(this);
373 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
375 if (CheckBan(user, it->mask))
382 bool Channel::CheckBan(User* user, const std::string& mask)
385 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
386 if (result != MOD_RES_PASSTHRU)
387 return (result == MOD_RES_DENY);
389 // extbans were handled above, if this is one it obviously didn't match
390 if ((mask.length() <= 2) || (mask[1] == ':'))
393 std::string::size_type at = mask.find('@');
394 if (at == std::string::npos)
397 const std::string nickIdent = user->nick + "!" + user->ident;
398 std::string prefix(mask, 0, at);
399 if (InspIRCd::Match(nickIdent, prefix, NULL))
401 std::string suffix(mask, at + 1);
402 if (InspIRCd::Match(user->host, suffix, NULL) ||
403 InspIRCd::Match(user->dhost, suffix, NULL) ||
404 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
410 ModResult Channel::GetExtBanStatus(User *user, char type)
413 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
414 if (rv != MOD_RES_PASSTHRU)
417 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
418 const ListModeBase::ModeList* bans = banlm->GetList(this);
421 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
423 if (CheckBan(user, it->mask))
427 return MOD_RES_PASSTHRU;
431 * Remove a channel from a users record, remove the reference to the Membership object
432 * from the channel and destroy it.
434 void Channel::PartUser(User *user, std::string &reason)
436 MemberMap::iterator membiter = userlist.find(user);
438 if (membiter != userlist.end())
440 Membership* memb = membiter->second;
442 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
444 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
446 // Remove this channel from the user's chanlist
447 user->chans.erase(memb);
448 // Remove the Membership from this channel's userlist and destroy it
449 this->DelUser(membiter);
453 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
455 Membership* memb = victimiter->second;
457 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
459 User* victim = memb->user;
460 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
462 victim->chans.erase(memb);
463 this->DelUser(victimiter);
466 void Channel::WriteChannel(User* user, const char* text, ...)
468 std::string textbuffer;
469 VAFORMAT(textbuffer, text, text);
470 this->WriteChannel(user, textbuffer);
473 void Channel::WriteChannel(User* user, const std::string &text)
475 const std::string message = ":" + user->GetFullHost() + " " + text;
477 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
479 if (IS_LOCAL(i->first))
480 i->first->Write(message);
484 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
486 std::string textbuffer;
487 VAFORMAT(textbuffer, text, text);
488 this->WriteChannelWithServ(ServName, textbuffer);
491 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
493 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
495 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
497 if (IS_LOCAL(i->first))
498 i->first->Write(message);
502 /* write formatted text from a source user to all users on a channel except
503 * for the sender (for privmsg etc) */
504 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
506 std::string textbuffer;
507 VAFORMAT(textbuffer, text, text);
508 this->WriteAllExceptSender(user, serversource, status, textbuffer);
511 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
513 std::string textbuffer;
514 VAFORMAT(textbuffer, text, text);
515 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
516 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
519 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
521 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
522 this->RawWriteAllExcept(user, serversource, status, except_list, message);
525 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
527 unsigned int minrank = 0;
530 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
532 minrank = mh->GetPrefixRank();
534 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
536 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
538 /* User doesn't have the status we're after */
539 if (minrank && i->second->getRank() < minrank)
542 i->first->Write(out);
547 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
550 except_list.insert(user);
551 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
554 const char* Channel::ChanModes(bool showkey)
556 static std::string scratch;
561 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
562 for(int n = 0; n < 64; n++)
564 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
565 if (mh && IsModeSet(mh))
567 scratch.push_back(n + 65);
569 ParamModeBase* pm = mh->IsParameterMode();
573 if (n == 'k' - 65 && !showkey)
580 pm->GetParameter(this, sparam);
586 return scratch.c_str();
589 /* compile a userlist of a channel into a string, each nick seperated by
590 * spaces and op, voice etc status shown as @ and +, and send it to 'user'
592 void Channel::UserList(User* user, bool has_user)
594 bool has_privs = user->HasPrivPermission("channels/auspex");
596 list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
598 list.append(this->name).append(" :");
599 std::string::size_type pos = list.size();
601 const size_t maxlen = ServerInstance->Config->Limits.MaxLine - 10 - ServerInstance->Config->ServerName.size();
602 std::string prefixlist;
604 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); ++i)
606 if ((!has_user) && (i->first->IsModeSet(invisiblemode)) && (!has_privs))
609 * user is +i, and source not on the channel, does not show
615 Membership* memb = i->second;
618 char prefix = memb->GetPrefixChar();
620 prefixlist.push_back(prefix);
621 nick = i->first->nick;
624 FIRST_MOD_RESULT(OnNamesListItem, res, (user, memb, prefixlist, nick));
626 // See if a module wants us to exclude this user from NAMES
627 if (res == MOD_RES_DENY)
630 if (list.size() + prefixlist.length() + nick.length() + 1 > maxlen)
632 /* list overflowed into multiple numerics */
633 user->WriteNumeric(RPL_NAMREPLY, list);
635 // Erase all nicks, keep the constant part
639 list.append(prefixlist).append(nick).push_back(' ');
642 // Only send the user list numeric if there is at least one user in it
643 if (list.size() != pos)
644 user->WriteNumeric(RPL_NAMREPLY, list);
646 user->WriteNumeric(RPL_ENDOFNAMES, "%s :End of /NAMES list.", this->name.c_str());
649 /* returns the status character for a given user on a channel, e.g. @ for op,
650 * % for halfop etc. If the user has several modes set, the highest mode
651 * the user has must be returned.
653 char Membership::GetPrefixChar() const
656 unsigned int bestrank = 0;
658 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
660 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
661 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
663 bestrank = mh->GetPrefixRank();
664 pf = mh->GetPrefix();
670 unsigned int Membership::getRank()
672 char mchar = modes.c_str()[0];
676 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
678 rv = mh->GetPrefixRank();
683 const char* Membership::GetAllPrefixChars() const
685 static char prefix[64];
688 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
690 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
691 if (mh && mh->GetPrefix())
692 prefix[ctr++] = mh->GetPrefix();
699 unsigned int Channel::GetPrefixValue(User* user)
701 MemberMap::iterator m = userlist.find(user);
702 if (m == userlist.end())
704 return m->second->getRank();
707 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
709 char prefix = delta_mh->GetModeChar();
710 for (unsigned int i = 0; i < modes.length(); i++)
712 char mchar = modes[i];
713 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
714 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
716 modes = modes.substr(0,i) +
717 (adding ? std::string(1, prefix) : "") +
718 modes.substr(mchar == prefix ? i+1 : i);
719 return adding != (mchar == prefix);
723 modes.push_back(prefix);
727 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
729 if ((timeout != 0) && (ServerInstance->Time() >= timeout))
730 // Expired, don't bother
733 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
735 Invitation* inv = Invitation::Find(c, u, false);
738 if ((inv->expiry == 0) || (inv->expiry > timeout))
740 inv->expiry = timeout;
741 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
745 inv = new Invitation(c, u, timeout);
746 c->invites.push_front(inv);
747 u->invites.push_front(inv);
748 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
752 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
754 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find chan=%s user=%s check_expired=%d", c ? c->name.c_str() : "NULL", u ? u->uuid.c_str() : "NULL", check_expired);
756 Invitation* result = NULL;
757 for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
759 Invitation* inv = *i;
762 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
764 /* Expired invite, remove it. */
765 std::string expiration = InspIRCd::TimeString(inv->expiry);
766 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
771 /* Is it what we're searching for? */
780 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
784 Invitation::~Invitation()
786 // Remove this entry from both lists
787 chan->invites.erase(this);
788 user->invites.erase(this);
789 ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);