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