]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Invert if in Channel::PartUser()
[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 void Channel::PartUser(User *user, std::string &reason)
409 {
410         MemberMap::iterator membiter = userlist.find(user);
411
412         if (membiter == userlist.end())
413                 return;
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
427 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
428 {
429         Membership* memb = victimiter->second;
430         CUList except_list;
431         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
432
433         User* victim = memb->user;
434         WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
435
436         victim->chans.erase(memb);
437         this->DelUser(victimiter);
438 }
439
440 void Channel::WriteChannel(User* user, const char* text, ...)
441 {
442         std::string textbuffer;
443         VAFORMAT(textbuffer, text, text);
444         this->WriteChannel(user, textbuffer);
445 }
446
447 void Channel::WriteChannel(User* user, const std::string &text)
448 {
449         const std::string message = ":" + user->GetFullHost() + " " + text;
450
451         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
452         {
453                 if (IS_LOCAL(i->first))
454                         i->first->Write(message);
455         }
456 }
457
458 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
459 {
460         std::string textbuffer;
461         VAFORMAT(textbuffer, text, text);
462         this->WriteChannelWithServ(ServName, textbuffer);
463 }
464
465 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
466 {
467         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
468
469         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
470         {
471                 if (IS_LOCAL(i->first))
472                         i->first->Write(message);
473         }
474 }
475
476 /* write formatted text from a source user to all users on a channel except
477  * for the sender (for privmsg etc) */
478 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
479 {
480         std::string textbuffer;
481         VAFORMAT(textbuffer, text, text);
482         this->WriteAllExceptSender(user, serversource, status, textbuffer);
483 }
484
485 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
486 {
487         std::string textbuffer;
488         VAFORMAT(textbuffer, text, text);
489         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
490         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
491 }
492
493 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
494 {
495         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
496         this->RawWriteAllExcept(user, serversource, status, except_list, message);
497 }
498
499 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
500 {
501         unsigned int minrank = 0;
502         if (status)
503         {
504                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
505                 if (mh)
506                         minrank = mh->GetPrefixRank();
507         }
508         for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
509         {
510                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
511                 {
512                         /* User doesn't have the status we're after */
513                         if (minrank && i->second->getRank() < minrank)
514                                 continue;
515
516                         i->first->Write(out);
517                 }
518         }
519 }
520
521 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
522 {
523         CUList except_list;
524         except_list.insert(user);
525         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
526 }
527
528 const char* Channel::ChanModes(bool showkey)
529 {
530         static std::string scratch;
531         std::string sparam;
532
533         scratch.clear();
534
535         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
536         for(int n = 0; n < 64; n++)
537         {
538                 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
539                 if (mh && IsModeSet(mh))
540                 {
541                         scratch.push_back(n + 65);
542
543                         ParamModeBase* pm = mh->IsParameterMode();
544                         if (!pm)
545                                 continue;
546
547                         if (n == 'k' - 65 && !showkey)
548                         {
549                                 sparam += " <key>";
550                         }
551                         else
552                         {
553                                 sparam += ' ';
554                                 pm->GetParameter(this, sparam);
555                         }
556                 }
557         }
558
559         scratch += sparam;
560         return scratch.c_str();
561 }
562
563 /* returns the status character for a given user on a channel, e.g. @ for op,
564  * % for halfop etc. If the user has several modes set, the highest mode
565  * the user has must be returned.
566  */
567 char Membership::GetPrefixChar() const
568 {
569         char pf = 0;
570         unsigned int bestrank = 0;
571
572         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
573         {
574                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
575                 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
576                 {
577                         bestrank = mh->GetPrefixRank();
578                         pf = mh->GetPrefix();
579                 }
580         }
581         return pf;
582 }
583
584 unsigned int Membership::getRank()
585 {
586         char mchar = modes.c_str()[0];
587         unsigned int rv = 0;
588         if (mchar)
589         {
590                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
591                 if (mh)
592                         rv = mh->GetPrefixRank();
593         }
594         return rv;
595 }
596
597 const char* Membership::GetAllPrefixChars() const
598 {
599         static char prefix[64];
600         int ctr = 0;
601
602         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
603         {
604                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
605                 if (mh && mh->GetPrefix())
606                         prefix[ctr++] = mh->GetPrefix();
607         }
608         prefix[ctr] = 0;
609
610         return prefix;
611 }
612
613 unsigned int Channel::GetPrefixValue(User* user)
614 {
615         MemberMap::iterator m = userlist.find(user);
616         if (m == userlist.end())
617                 return 0;
618         return m->second->getRank();
619 }
620
621 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
622 {
623         char prefix = delta_mh->GetModeChar();
624         for (unsigned int i = 0; i < modes.length(); i++)
625         {
626                 char mchar = modes[i];
627                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
628                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
629                 {
630                         modes = modes.substr(0,i) +
631                                 (adding ? std::string(1, prefix) : "") +
632                                 modes.substr(mchar == prefix ? i+1 : i);
633                         return adding != (mchar == prefix);
634                 }
635         }
636         if (adding)
637                 modes.push_back(prefix);
638         return adding;
639 }