]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
99da0070810b1f6b4463977e58c078c436b651d4
[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)
50 {
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();
55
56         FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
57 }
58
59 Membership* Channel::AddUser(User* user)
60 {
61         std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
62         if (!ret.second)
63                 return NULL;
64
65         Membership* memb = new(ret.first->second) Membership(user, this);
66         return memb;
67 }
68
69 void Channel::DelUser(User* user)
70 {
71         MemberMap::iterator it = userlist.find(user);
72         if (it != userlist.end())
73                 DelUser(it);
74 }
75
76 void Channel::CheckDestroy()
77 {
78         if (!userlist.empty())
79                 return;
80
81         ModResult res;
82         FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
83         if (res == MOD_RES_DENY)
84                 return;
85
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))
89                 return;
90
91         FOREACH_MOD(OnChannelDelete, (this));
92         ServerInstance->chanlist.erase(iter);
93         ServerInstance->GlobalCulls.AddItem(this);
94 }
95
96 void Channel::DelUser(const MemberMap::iterator& membiter)
97 {
98         Membership* memb = membiter->second;
99         memb->cull();
100         memb->~Membership();
101         userlist.erase(membiter);
102
103         // If this channel became empty then it should be removed
104         CheckDestroy();
105 }
106
107 Membership* Channel::GetUser(User* user)
108 {
109         MemberMap::iterator i = userlist.find(user);
110         if (i == userlist.end())
111                 return NULL;
112         return i->second;
113 }
114
115 void Channel::SetDefaultModes()
116 {
117         ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
118                 ServerInstance->Config->DefaultModes.c_str());
119         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
120         std::string modeseq;
121         std::string parameter;
122
123         list.GetToken(modeseq);
124
125         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
126         {
127                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
128                 if (mode)
129                 {
130                         if (mode->IsPrefixMode())
131                                 continue;
132
133                         if (mode->GetNumParams(true))
134                         {
135                                 list.GetToken(parameter);
136                                 // If the parameter begins with a ':' then it's invalid
137                                 if (parameter.c_str()[0] == ':')
138                                         continue;
139                         }
140                         else
141                                 parameter.clear();
142
143                         if ((mode->GetNumParams(true)) && (parameter.empty()))
144                                 continue;
145
146                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
147                 }
148         }
149 }
150
151 /*
152  * add a channel to a user, creating the record for it if needed and linking
153  * it to the user record
154  */
155 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
156 {
157         if (user->registered != REG_ALL)
158         {
159                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
160                 return NULL;
161         }
162
163         /*
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
168          */
169         if (!override)
170         {
171                 unsigned int maxchans = user->GetClass()->maxchans;
172                 if (user->IsOper())
173                 {
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
176                         if (!opermaxchans)
177                                 opermaxchans = ServerInstance->Config->OperMaxChans;
178                         if (opermaxchans)
179                                 maxchans = opermaxchans;
180                 }
181                 if (user->chans.size() >= maxchans)
182                 {
183                         user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
184                         return NULL;
185                 }
186         }
187
188         // Crop channel name if it's too long
189         if (cname.length() > ServerInstance->Config->Limits.ChanMax)
190                 cname.resize(ServerInstance->Config->Limits.ChanMax);
191
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
195
196         if (!chan)
197         {
198                 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
199
200                 if (override == false)
201                 {
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
207                 }
208
209                 chan = new Channel(cname, ServerInstance->Time());
210                 // Set the default modes on the channel (<options:defaultmodes>)
211                 chan->SetDefaultModes();
212         }
213         else
214         {
215                 /* Already on the channel */
216                 if (chan->HasUser(user))
217                         return NULL;
218
219                 if (override == false)
220                 {
221                         ModResult MOD_RESULT;
222                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
223
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)
227                                 return NULL;
228
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,
231                         // in this order.
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)
235                         {
236                                 std::string ckey = chan->GetModeParameter(keymode);
237                                 if (!ckey.empty())
238                                 {
239                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
240                                         if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
241                                         {
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, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
244                                                 return NULL;
245                                         }
246                                 }
247
248                                 if (chan->IsModeSet(inviteonlymode))
249                                 {
250                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
251                                         if (MOD_RESULT != MOD_RES_ALLOW)
252                                         {
253                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
254                                                 return NULL;
255                                         }
256                                 }
257
258                                 std::string limit = chan->GetModeParameter(limitmode);
259                                 if (!limit.empty())
260                                 {
261                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
262                                         if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
263                                         {
264                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
265                                                 return NULL;
266                                         }
267                                 }
268
269                                 if (chan->IsBanned(user))
270                                 {
271                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
272                                         return NULL;
273                                 }
274                         }
275                 }
276         }
277
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);
281         return chan;
282 }
283
284 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
285 {
286         if (IS_SERVER(user))
287         {
288                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
289                 return NULL;
290         }
291
292         Membership* memb = this->AddUser(user);
293         if (!memb)
294                 return NULL; // Already on the channel
295
296         user->chans.push_front(memb);
297
298         if (privs)
299         {
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)
303                 {
304                         PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
305                         if (mh)
306                         {
307                                 std::string nick = user->nick;
308                                 // Set the mode on the user
309                                 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
310                         }
311                 }
312         }
313
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
315         CUList except_list;
316         FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
317
318         this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
319
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()))
322         {
323                 std::string ms = memb->modes;
324                 for(unsigned int i=0; i < memb->modes.length(); i++)
325                         ms.append(" ").append(user->nick);
326
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());
329         }
330
331         FOREACH_MOD(OnPostJoin, (memb));
332         return memb;
333 }
334
335 bool Channel::IsBanned(User* user)
336 {
337         ModResult result;
338         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
339
340         if (result != MOD_RES_PASSTHRU)
341                 return (result == MOD_RES_DENY);
342
343         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
344         const ListModeBase::ModeList* bans = banlm->GetList(this);
345         if (bans)
346         {
347                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
348                 {
349                         if (CheckBan(user, it->mask))
350                                 return true;
351                 }
352         }
353         return false;
354 }
355
356 bool Channel::CheckBan(User* user, const std::string& mask)
357 {
358         ModResult result;
359         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
360         if (result != MOD_RES_PASSTHRU)
361                 return (result == MOD_RES_DENY);
362
363         // extbans were handled above, if this is one it obviously didn't match
364         if ((mask.length() <= 2) || (mask[1] == ':'))
365                 return false;
366
367         std::string::size_type at = mask.find('@');
368         if (at == std::string::npos)
369                 return false;
370
371         const std::string nickIdent = user->nick + "!" + user->ident;
372         std::string prefix(mask, 0, at);
373         if (InspIRCd::Match(nickIdent, prefix, NULL))
374         {
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))
379                         return true;
380         }
381         return false;
382 }
383
384 ModResult Channel::GetExtBanStatus(User *user, char type)
385 {
386         ModResult rv;
387         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
388         if (rv != MOD_RES_PASSTHRU)
389                 return rv;
390
391         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
392         const ListModeBase::ModeList* bans = banlm->GetList(this);
393         if (bans)
394         {
395                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
396                 {
397                         if (CheckBan(user, it->mask))
398                                 return MOD_RES_DENY;
399                 }
400         }
401         return MOD_RES_PASSTHRU;
402 }
403
404 /* Channel::PartUser
405  * Remove a channel from a users record, remove the reference to the Membership object
406  * from the channel and destroy it.
407  */
408 bool Channel::PartUser(User* user, std::string& reason)
409 {
410         MemberMap::iterator membiter = userlist.find(user);
411
412         if (membiter == userlist.end())
413                 return false;
414
415         Membership* memb = membiter->second;
416         CUList except_list;
417         FOREACH_MOD(OnUserPart, (memb, reason, except_list));
418
419         WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
420
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);
425
426         return true;
427 }
428
429 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
430 {
431         Membership* memb = victimiter->second;
432         CUList except_list;
433         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
434
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());
437
438         victim->chans.erase(memb);
439         this->DelUser(victimiter);
440 }
441
442 void Channel::WriteChannel(User* user, const char* text, ...)
443 {
444         std::string textbuffer;
445         VAFORMAT(textbuffer, text, text);
446         this->WriteChannel(user, textbuffer);
447 }
448
449 void Channel::WriteChannel(User* user, const std::string &text)
450 {
451         const std::string message = ":" + user->GetFullHost() + " " + text;
452
453         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
454         {
455                 if (IS_LOCAL(i->first))
456                         i->first->Write(message);
457         }
458 }
459
460 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
461 {
462         std::string textbuffer;
463         VAFORMAT(textbuffer, text, text);
464         this->WriteChannelWithServ(ServName, textbuffer);
465 }
466
467 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
468 {
469         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
470
471         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
472         {
473                 if (IS_LOCAL(i->first))
474                         i->first->Write(message);
475         }
476 }
477
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, ...)
481 {
482         std::string textbuffer;
483         VAFORMAT(textbuffer, text, text);
484         this->WriteAllExceptSender(user, serversource, status, textbuffer);
485 }
486
487 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
488 {
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);
493 }
494
495 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
496 {
497         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
498         this->RawWriteAllExcept(user, serversource, status, except_list, message);
499 }
500
501 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
502 {
503         unsigned int minrank = 0;
504         if (status)
505         {
506                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
507                 if (mh)
508                         minrank = mh->GetPrefixRank();
509         }
510         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
511         {
512                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
513                 {
514                         /* User doesn't have the status we're after */
515                         if (minrank && i->second->getRank() < minrank)
516                                 continue;
517
518                         i->first->Write(out);
519                 }
520         }
521 }
522
523 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
524 {
525         CUList except_list;
526         except_list.insert(user);
527         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
528 }
529
530 const char* Channel::ChanModes(bool showkey)
531 {
532         static std::string scratch;
533         std::string sparam;
534
535         scratch.clear();
536
537         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
538         for(int n = 0; n < 64; n++)
539         {
540                 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
541                 if (mh && IsModeSet(mh))
542                 {
543                         scratch.push_back(n + 65);
544
545                         ParamModeBase* pm = mh->IsParameterMode();
546                         if (!pm)
547                                 continue;
548
549                         if (n == 'k' - 65 && !showkey)
550                         {
551                                 sparam += " <key>";
552                         }
553                         else
554                         {
555                                 sparam += ' ';
556                                 pm->GetParameter(this, sparam);
557                         }
558                 }
559         }
560
561         scratch += sparam;
562         return scratch.c_str();
563 }
564
565 /* returns the status character for a given user on a channel, e.g. @ for op,
566  * % for halfop etc. If the user has several modes set, the highest mode
567  * the user has must be returned.
568  */
569 char Membership::GetPrefixChar() const
570 {
571         char pf = 0;
572         unsigned int bestrank = 0;
573
574         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
575         {
576                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
577                 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
578                 {
579                         bestrank = mh->GetPrefixRank();
580                         pf = mh->GetPrefix();
581                 }
582         }
583         return pf;
584 }
585
586 unsigned int Membership::getRank()
587 {
588         char mchar = modes.c_str()[0];
589         unsigned int rv = 0;
590         if (mchar)
591         {
592                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
593                 if (mh)
594                         rv = mh->GetPrefixRank();
595         }
596         return rv;
597 }
598
599 const char* Membership::GetAllPrefixChars() const
600 {
601         static char prefix[64];
602         int ctr = 0;
603
604         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
605         {
606                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
607                 if (mh && mh->GetPrefix())
608                         prefix[ctr++] = mh->GetPrefix();
609         }
610         prefix[ctr] = 0;
611
612         return prefix;
613 }
614
615 unsigned int Channel::GetPrefixValue(User* user)
616 {
617         MemberMap::iterator m = userlist.find(user);
618         if (m == userlist.end())
619                 return 0;
620         return m->second->getRank();
621 }
622
623 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
624 {
625         char prefix = delta_mh->GetModeChar();
626         for (unsigned int i = 0; i < modes.length(); i++)
627         {
628                 char mchar = modes[i];
629                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
630                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
631                 {
632                         modes = modes.substr(0,i) +
633                                 (adding ? std::string(1, prefix) : "") +
634                                 modes.substr(mchar == prefix ? i+1 : i);
635                         return adding != (mchar == prefix);
636                 }
637         }
638         if (adding)
639                 modes.push_back(prefix);
640         return adding;
641 }