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/>.
33 ChanModeReference ban(NULL, "ban");
34 ChanModeReference inviteonlymode(NULL, "inviteonly");
35 ChanModeReference keymode(NULL, "key");
36 ChanModeReference limitmode(NULL, "limit");
37 ChanModeReference secretmode(NULL, "secret");
38 ChanModeReference privatemode(NULL, "private");
39 UserModeReference invisiblemode(NULL, "invisible");
42 Channel::Channel(const std::string &cname, time_t ts)
43 : name(cname), age(ts), topicset(0)
45 if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
46 throw CoreException("Cannot create duplicate channel " + cname);
49 void Channel::SetMode(ModeHandler* mh, bool on)
51 modes[mh->GetId()] = on;
54 void Channel::SetTopic(User* u, const std::string& ntopic)
56 this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
57 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
58 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
59 this->topicset = ServerInstance->Time();
61 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
64 Membership* Channel::AddUser(User* user)
66 Membership*& memb = userlist[user];
70 memb = new Membership(user, this);
74 void Channel::DelUser(User* user)
76 UserMembIter it = userlist.find(user);
77 if (it != userlist.end())
81 void Channel::CheckDestroy()
83 if (!userlist.empty())
87 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
88 if (res == MOD_RES_DENY)
91 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
93 if (iter != ServerInstance->chanlist.end())
95 FOREACH_MOD(OnChannelDelete, (this));
96 ServerInstance->chanlist.erase(iter);
100 ServerInstance->GlobalCulls.AddItem(this);
103 void Channel::DelUser(const UserMembIter& membiter)
105 Membership* memb = membiter->second;
108 userlist.erase(membiter);
110 // If this channel became empty then it should be removed
114 Membership* Channel::GetUser(User* user)
116 UserMembIter i = userlist.find(user);
117 if (i == userlist.end())
122 void Channel::SetDefaultModes()
124 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
125 ServerInstance->Config->DefaultModes.c_str());
126 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
128 std::string parameter;
130 list.GetToken(modeseq);
132 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
134 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
137 if (mode->IsPrefixMode())
140 if (mode->GetNumParams(true))
141 list.GetToken(parameter);
145 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
151 * add a channel to a user, creating the record for it if needed and linking
152 * it to the user record
154 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
156 if (user->registered != REG_ALL)
158 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
163 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
164 * We restrict local users to <connect:maxchans> channels.
165 * We restrict local operators to <oper:maxchans> channels.
166 * This is a lot more logical than how it was formerly. -- w00t
170 unsigned int maxchans = user->GetClass()->maxchans;
173 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
174 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
176 opermaxchans = ServerInstance->Config->OperMaxChans;
178 maxchans = opermaxchans;
180 if (user->chans.size() >= maxchans)
182 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
187 // Crop channel name if it's too long
188 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
189 cname.resize(ServerInstance->Config->Limits.ChanMax);
191 Channel* chan = ServerInstance->FindChan(cname);
192 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
193 std::string privs; // Prefix mode(letter)s to give to the joining user
197 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
199 if (override == false)
201 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
202 ModResult MOD_RESULT;
203 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
204 if (MOD_RESULT == MOD_RES_DENY)
205 return NULL; // A module wasn't happy with the join, abort
208 chan = new Channel(cname, ServerInstance->Time());
209 // Set the default modes on the channel (<options:defaultmodes>)
210 chan->SetDefaultModes();
214 /* Already on the channel */
215 if (chan->HasUser(user))
218 if (override == false)
220 ModResult MOD_RESULT;
221 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
223 // A module explicitly denied the join and (hopefully) generated a message
224 // describing the situation, so we may stop here without sending anything
225 if (MOD_RESULT == MOD_RES_DENY)
228 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
229 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
231 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
232 // then this entire section is skipped
233 if (MOD_RESULT == MOD_RES_PASSTHRU)
235 std::string ckey = chan->GetModeParameter(keymode);
236 bool invited = user->IsInvited(chan);
237 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
241 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
242 if (!MOD_RESULT.check((ckey == key) || can_bypass))
244 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
245 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
250 if (chan->IsModeSet(inviteonlymode))
252 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
253 if (!MOD_RESULT.check(invited))
255 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
260 std::string limit = chan->GetModeParameter(limitmode);
263 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
264 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
266 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
271 if (chan->IsBanned(user) && !can_bypass)
273 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
278 * If the user has invites for this channel, remove them now
279 * after a successful join so they don't build up.
283 user->RemoveInvite(chan);
289 // We figured that this join is allowed and also created the
290 // channel if it didn't exist before, now do the actual join
291 chan->ForceJoin(user, &privs, false, created_by_local);
295 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
299 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
303 Membership* memb = this->AddUser(user);
305 return NULL; // Already on the channel
307 user->chans.push_front(memb);
311 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
312 // remote user and his own server set the modes), then set them internally now
313 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
315 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
318 std::string nick = user->nick;
319 // Set the mode on the user
320 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
325 // 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
327 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
329 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
331 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
332 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
334 std::string ms = memb->modes;
335 for(unsigned int i=0; i < memb->modes.length(); i++)
336 ms.append(" ").append(user->nick);
338 except_list.insert(user);
339 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
346 user->WriteNumeric(RPL_TOPIC, "%s :%s", this->name.c_str(), this->topic.c_str());
347 user->WriteNumeric(RPL_TOPICTIME, "%s %s %lu", this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
349 this->UserList(user);
352 FOREACH_MOD(OnPostJoin, (memb));
356 bool Channel::IsBanned(User* user)
359 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
361 if (result != MOD_RES_PASSTHRU)
362 return (result == MOD_RES_DENY);
364 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
365 const ListModeBase::ModeList* bans = banlm->GetList(this);
368 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
370 if (CheckBan(user, it->mask))
377 bool Channel::CheckBan(User* user, const std::string& mask)
380 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
381 if (result != MOD_RES_PASSTHRU)
382 return (result == MOD_RES_DENY);
384 // extbans were handled above, if this is one it obviously didn't match
385 if ((mask.length() <= 2) || (mask[1] == ':'))
388 std::string::size_type at = mask.find('@');
389 if (at == std::string::npos)
392 const std::string nickIdent = user->nick + "!" + user->ident;
393 std::string prefix = mask.substr(0, at);
394 if (InspIRCd::Match(nickIdent, prefix, NULL))
396 std::string suffix = mask.substr(at + 1);
397 if (InspIRCd::Match(user->host, suffix, NULL) ||
398 InspIRCd::Match(user->dhost, suffix, NULL) ||
399 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
405 ModResult Channel::GetExtBanStatus(User *user, char type)
408 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
409 if (rv != MOD_RES_PASSTHRU)
412 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
413 const ListModeBase::ModeList* bans = banlm->GetList(this);
416 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
418 if (CheckBan(user, it->mask))
422 return MOD_RES_PASSTHRU;
426 * Remove a channel from a users record, remove the reference to the Membership object
427 * from the channel and destroy it.
429 void Channel::PartUser(User *user, std::string &reason)
431 UserMembIter membiter = userlist.find(user);
433 if (membiter != userlist.end())
435 Membership* memb = membiter->second;
437 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
439 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
441 // Remove this channel from the user's chanlist
442 user->chans.erase(memb);
443 // Remove the Membership from this channel's userlist and destroy it
444 this->DelUser(membiter);
448 void Channel::KickUser(User* src, const UserMembIter& victimiter, const std::string& reason)
450 Membership* memb = victimiter->second;
452 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
454 User* victim = memb->user;
455 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
457 victim->chans.erase(memb);
458 this->DelUser(victimiter);
461 void Channel::WriteChannel(User* user, const char* text, ...)
463 std::string textbuffer;
464 VAFORMAT(textbuffer, text, text);
465 this->WriteChannel(user, textbuffer);
468 void Channel::WriteChannel(User* user, const std::string &text)
470 const std::string message = ":" + user->GetFullHost() + " " + text;
472 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
474 if (IS_LOCAL(i->first))
475 i->first->Write(message);
479 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
481 std::string textbuffer;
482 VAFORMAT(textbuffer, text, text);
483 this->WriteChannelWithServ(ServName, textbuffer);
486 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
488 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
490 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
492 if (IS_LOCAL(i->first))
493 i->first->Write(message);
497 /* write formatted text from a source user to all users on a channel except
498 * for the sender (for privmsg etc) */
499 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
501 std::string textbuffer;
502 VAFORMAT(textbuffer, text, text);
503 this->WriteAllExceptSender(user, serversource, status, textbuffer);
506 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
508 std::string textbuffer;
509 VAFORMAT(textbuffer, text, text);
510 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
511 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
514 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
516 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
517 this->RawWriteAllExcept(user, serversource, status, except_list, message);
520 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
522 unsigned int minrank = 0;
525 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
527 minrank = mh->GetPrefixRank();
529 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
531 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
533 /* User doesn't have the status we're after */
534 if (minrank && i->second->getRank() < minrank)
537 i->first->Write(out);
542 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
545 except_list.insert(user);
546 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
549 const char* Channel::ChanModes(bool showkey)
551 static std::string scratch;
556 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
557 for(int n = 0; n < 64; n++)
559 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
560 if (mh && IsModeSet(mh))
562 scratch.push_back(n + 65);
564 ParamModeBase* pm = mh->IsParameterMode();
568 if (n == 'k' - 65 && !showkey)
575 pm->GetParameter(this, sparam);
581 return scratch.c_str();
584 /* compile a userlist of a channel into a string, each nick seperated by
585 * spaces and op, voice etc status shown as @ and +, and send it to 'user'
587 void Channel::UserList(User* user, bool has_user)
589 bool has_privs = user->HasPrivPermission("channels/auspex");
591 list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
593 list.append(this->name).append(" :");
594 std::string::size_type pos = list.size();
596 const size_t maxlen = ServerInstance->Config->Limits.MaxLine - 10 - ServerInstance->Config->ServerName.size();
597 std::string prefixlist;
599 for (UserMembIter i = userlist.begin(); i != userlist.end(); ++i)
601 if ((!has_user) && (i->first->IsModeSet(invisiblemode)) && (!has_privs))
604 * user is +i, and source not on the channel, does not show
610 Membership* memb = i->second;
613 char prefix = memb->GetPrefixChar();
615 prefixlist.push_back(prefix);
616 nick = i->first->nick;
619 FIRST_MOD_RESULT(OnNamesListItem, res, (user, memb, prefixlist, nick));
621 // See if a module wants us to exclude this user from NAMES
622 if (res == MOD_RES_DENY)
625 if (list.size() + prefixlist.length() + nick.length() + 1 > maxlen)
627 /* list overflowed into multiple numerics */
628 user->WriteNumeric(RPL_NAMREPLY, list);
630 // Erase all nicks, keep the constant part
634 list.append(prefixlist).append(nick).push_back(' ');
637 // Only send the user list numeric if there is at least one user in it
638 if (list.size() != pos)
639 user->WriteNumeric(RPL_NAMREPLY, list);
641 user->WriteNumeric(RPL_ENDOFNAMES, "%s :End of /NAMES list.", this->name.c_str());
644 /* returns the status character for a given user on a channel, e.g. @ for op,
645 * % for halfop etc. If the user has several modes set, the highest mode
646 * the user has must be returned.
648 char Membership::GetPrefixChar() const
651 unsigned int bestrank = 0;
653 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
655 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
656 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
658 bestrank = mh->GetPrefixRank();
659 pf = mh->GetPrefix();
665 unsigned int Membership::getRank()
667 char mchar = modes.c_str()[0];
671 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
673 rv = mh->GetPrefixRank();
678 const char* Membership::GetAllPrefixChars() const
680 static char prefix[64];
683 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
685 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
686 if (mh && mh->GetPrefix())
687 prefix[ctr++] = mh->GetPrefix();
694 unsigned int Channel::GetPrefixValue(User* user)
696 UserMembIter m = userlist.find(user);
697 if (m == userlist.end())
699 return m->second->getRank();
702 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
704 char prefix = delta_mh->GetModeChar();
705 for (unsigned int i = 0; i < modes.length(); i++)
707 char mchar = modes[i];
708 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
709 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
711 modes = modes.substr(0,i) +
712 (adding ? std::string(1, prefix) : "") +
713 modes.substr(mchar == prefix ? i+1 : i);
714 return adding != (mchar == prefix);
718 modes.push_back(prefix);
722 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
724 if ((timeout != 0) && (ServerInstance->Time() >= timeout))
725 // Expired, don't bother
728 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
730 Invitation* inv = Invitation::Find(c, u, false);
733 if ((inv->expiry == 0) || (inv->expiry > timeout))
735 inv->expiry = timeout;
736 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
740 inv = new Invitation(c, u, timeout);
741 c->invites.push_front(inv);
742 u->invites.push_front(inv);
743 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
747 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
749 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);
751 Invitation* result = NULL;
752 for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
754 Invitation* inv = *i;
757 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
759 /* Expired invite, remove it. */
760 std::string expiration = InspIRCd::TimeString(inv->expiry);
761 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
766 /* Is it what we're searching for? */
775 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
779 Invitation::~Invitation()
781 // Remove this entry from both lists
782 chan->invites.erase(this);
783 user->invites.erase(this);
784 ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);