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");
37 Channel::Channel(const std::string &cname, time_t ts)
38 : name(cname), age(ts), topicset(0)
40 if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
41 throw CoreException("Cannot create duplicate channel " + cname);
44 void Channel::SetMode(ModeHandler* mh, bool on)
46 modes[mh->GetId()] = on;
49 void Channel::SetTopic(User* u, const std::string& ntopic)
51 this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
52 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
53 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
54 this->topicset = ServerInstance->Time();
56 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
59 Membership* Channel::AddUser(User* user)
61 std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
65 Membership* memb = new(ret.first->second) Membership(user, this);
69 void Channel::DelUser(User* user)
71 MemberMap::iterator it = userlist.find(user);
72 if (it != userlist.end())
76 void Channel::CheckDestroy()
78 if (!userlist.empty())
82 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
83 if (res == MOD_RES_DENY)
86 // If the channel isn't in chanlist then it is already in the cull list, don't add it again
87 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
88 if ((iter == ServerInstance->chanlist.end()) || (iter->second != this))
91 FOREACH_MOD(OnChannelDelete, (this));
92 ServerInstance->chanlist.erase(iter);
93 ServerInstance->GlobalCulls.AddItem(this);
96 void Channel::DelUser(const MemberMap::iterator& membiter)
98 Membership* memb = membiter->second;
101 userlist.erase(membiter);
103 // If this channel became empty then it should be removed
107 Membership* Channel::GetUser(User* user)
109 MemberMap::iterator i = userlist.find(user);
110 if (i == userlist.end())
115 void Channel::SetDefaultModes()
117 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
118 ServerInstance->Config->DefaultModes.c_str());
119 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
121 std::string parameter;
123 list.GetToken(modeseq);
125 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
127 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
130 if (mode->IsPrefixMode())
133 if (mode->GetNumParams(true))
135 list.GetToken(parameter);
136 // If the parameter begins with a ':' then it's invalid
137 if (parameter.c_str()[0] == ':')
143 if ((mode->GetNumParams(true)) && (parameter.empty()))
146 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
152 * add a channel to a user, creating the record for it if needed and linking
153 * it to the user record
155 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
157 if (user->registered != REG_ALL)
159 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
164 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
165 * We restrict local users to <connect:maxchans> channels.
166 * We restrict local operators to <oper:maxchans> channels.
167 * This is a lot more logical than how it was formerly. -- w00t
171 unsigned int maxchans = user->GetClass()->maxchans;
174 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
175 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
177 opermaxchans = ServerInstance->Config->OperMaxChans;
179 maxchans = opermaxchans;
181 if (user->chans.size() >= maxchans)
183 user->WriteNumeric(ERR_TOOMANYCHANNELS, cname, "You are on too many channels");
188 // Crop channel name if it's too long
189 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
190 cname.resize(ServerInstance->Config->Limits.ChanMax);
192 Channel* chan = ServerInstance->FindChan(cname);
193 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
194 std::string privs; // Prefix mode(letter)s to give to the joining user
198 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
200 if (override == false)
202 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
203 ModResult MOD_RESULT;
204 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
205 if (MOD_RESULT == MOD_RES_DENY)
206 return NULL; // A module wasn't happy with the join, abort
209 chan = new Channel(cname, ServerInstance->Time());
210 // Set the default modes on the channel (<options:defaultmodes>)
211 chan->SetDefaultModes();
215 /* Already on the channel */
216 if (chan->HasUser(user))
219 if (override == false)
221 ModResult MOD_RESULT;
222 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
224 // A module explicitly denied the join and (hopefully) generated a message
225 // describing the situation, so we may stop here without sending anything
226 if (MOD_RESULT == MOD_RES_DENY)
229 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
230 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
232 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
233 // then this entire section is skipped
234 if (MOD_RESULT == MOD_RES_PASSTHRU)
236 std::string ckey = chan->GetModeParameter(keymode);
239 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
240 if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
242 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
243 user->WriteNumeric(ERR_BADCHANNELKEY, chan->name, "Cannot join channel (Incorrect channel key)");
248 if (chan->IsModeSet(inviteonlymode))
250 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
251 if (MOD_RESULT != MOD_RES_ALLOW)
253 user->WriteNumeric(ERR_INVITEONLYCHAN, chan->name, "Cannot join channel (Invite only)");
258 std::string limit = chan->GetModeParameter(limitmode);
261 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
262 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
264 user->WriteNumeric(ERR_CHANNELISFULL, chan->name, "Cannot join channel (Channel is full)");
269 if (chan->IsBanned(user))
271 user->WriteNumeric(ERR_BANNEDFROMCHAN, chan->name, "Cannot join channel (You're banned)");
278 // We figured that this join is allowed and also created the
279 // channel if it didn't exist before, now do the actual join
280 chan->ForceJoin(user, &privs, false, created_by_local);
284 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
288 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
292 Membership* memb = this->AddUser(user);
294 return NULL; // Already on the channel
296 user->chans.push_front(memb);
300 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
301 // remote user and his own server set the modes), then set them internally now
302 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
304 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
307 std::string nick = user->nick;
308 // Set the mode on the user
309 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
314 // 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
316 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
318 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
320 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
321 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
323 std::string ms = memb->modes;
324 for(unsigned int i=0; i < memb->modes.length(); i++)
325 ms.append(" ").append(user->nick);
327 except_list.insert(user);
328 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
331 FOREACH_MOD(OnPostJoin, (memb));
335 bool Channel::IsBanned(User* user)
338 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
340 if (result != MOD_RES_PASSTHRU)
341 return (result == MOD_RES_DENY);
343 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
344 const ListModeBase::ModeList* bans = banlm->GetList(this);
347 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
349 if (CheckBan(user, it->mask))
356 bool Channel::CheckBan(User* user, const std::string& mask)
359 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
360 if (result != MOD_RES_PASSTHRU)
361 return (result == MOD_RES_DENY);
363 // extbans were handled above, if this is one it obviously didn't match
364 if ((mask.length() <= 2) || (mask[1] == ':'))
367 std::string::size_type at = mask.find('@');
368 if (at == std::string::npos)
371 const std::string nickIdent = user->nick + "!" + user->ident;
372 std::string prefix(mask, 0, at);
373 if (InspIRCd::Match(nickIdent, prefix, NULL))
375 std::string suffix(mask, at + 1);
376 if (InspIRCd::Match(user->host, suffix, NULL) ||
377 InspIRCd::Match(user->dhost, suffix, NULL) ||
378 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
384 ModResult Channel::GetExtBanStatus(User *user, char type)
387 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
388 if (rv != MOD_RES_PASSTHRU)
391 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
392 const ListModeBase::ModeList* bans = banlm->GetList(this);
395 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
397 if (CheckBan(user, it->mask))
401 return MOD_RES_PASSTHRU;
405 * Remove a channel from a users record, remove the reference to the Membership object
406 * from the channel and destroy it.
408 bool Channel::PartUser(User* user, std::string& reason)
410 MemberMap::iterator membiter = userlist.find(user);
412 if (membiter == userlist.end())
415 Membership* memb = membiter->second;
417 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
419 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
421 // Remove this channel from the user's chanlist
422 user->chans.erase(memb);
423 // Remove the Membership from this channel's userlist and destroy it
424 this->DelUser(membiter);
429 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
431 Membership* memb = victimiter->second;
433 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
435 User* victim = memb->user;
436 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
438 victim->chans.erase(memb);
439 this->DelUser(victimiter);
442 void Channel::WriteChannel(User* user, const char* text, ...)
444 std::string textbuffer;
445 VAFORMAT(textbuffer, text, text);
446 this->WriteChannel(user, textbuffer);
449 void Channel::WriteChannel(User* user, const std::string &text)
451 const std::string message = ":" + user->GetFullHost() + " " + text;
453 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
455 if (IS_LOCAL(i->first))
456 i->first->Write(message);
460 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
462 std::string textbuffer;
463 VAFORMAT(textbuffer, text, text);
464 this->WriteChannelWithServ(ServName, textbuffer);
467 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
469 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
471 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
473 if (IS_LOCAL(i->first))
474 i->first->Write(message);
478 /* write formatted text from a source user to all users on a channel except
479 * for the sender (for privmsg etc) */
480 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
482 std::string textbuffer;
483 VAFORMAT(textbuffer, text, text);
484 this->WriteAllExceptSender(user, serversource, status, textbuffer);
487 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
489 std::string textbuffer;
490 VAFORMAT(textbuffer, text, text);
491 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
492 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
495 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
497 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
498 this->RawWriteAllExcept(user, serversource, status, except_list, message);
501 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
503 unsigned int minrank = 0;
506 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
508 minrank = mh->GetPrefixRank();
510 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
512 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
514 /* User doesn't have the status we're after */
515 if (minrank && i->second->getRank() < minrank)
518 i->first->Write(out);
523 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
526 except_list.insert(user);
527 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
530 const char* Channel::ChanModes(bool showkey)
532 static std::string scratch;
537 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
538 for(int n = 0; n < 64; n++)
540 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
541 if (mh && IsModeSet(mh))
543 scratch.push_back(n + 65);
545 ParamModeBase* pm = mh->IsParameterMode();
549 if (n == 'k' - 65 && !showkey)
556 pm->GetParameter(this, sparam);
562 return scratch.c_str();
565 void Channel::WriteNotice(const std::string& text)
567 std::string rawmsg = "NOTICE ";
568 rawmsg.append(this->name).append(" :").append(text);
569 WriteChannelWithServ(ServerInstance->Config->ServerName, rawmsg);
572 /* returns the status character for a given user on a channel, e.g. @ for op,
573 * % for halfop etc. If the user has several modes set, the highest mode
574 * the user has must be returned.
576 char Membership::GetPrefixChar() const
579 unsigned int bestrank = 0;
581 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
583 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
584 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
586 bestrank = mh->GetPrefixRank();
587 pf = mh->GetPrefix();
593 unsigned int Membership::getRank()
595 char mchar = modes.c_str()[0];
599 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
601 rv = mh->GetPrefixRank();
606 const char* Membership::GetAllPrefixChars() const
608 static char prefix[64];
611 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
613 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
614 if (mh && mh->GetPrefix())
615 prefix[ctr++] = mh->GetPrefix();
622 unsigned int Channel::GetPrefixValue(User* user)
624 MemberMap::iterator m = userlist.find(user);
625 if (m == userlist.end())
627 return m->second->getRank();
630 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
632 char prefix = delta_mh->GetModeChar();
633 for (unsigned int i = 0; i < modes.length(); i++)
635 char mchar = modes[i];
636 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
637 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
639 modes = modes.substr(0,i) +
640 (adding ? std::string(1, prefix) : "") +
641 modes.substr(mchar == prefix ? i+1 : i);
642 return adding != (mchar == prefix);
646 modes.push_back(prefix);