]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
4010f819a39d102c6b93ac9d56fb0bd3f5849b65
[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 /* $Core */
27
28 #include "inspircd.h"
29 #include "listmode.h"
30 #include <cstdarg>
31 #include "mode.h"
32
33 static ModeReference ban(NULL, "ban");
34
35 Channel::Channel(const std::string &cname, time_t ts)
36 {
37         if (!ServerInstance->chanlist->insert(std::make_pair(cname, this)).second)
38                 throw CoreException("Cannot create duplicate channel " + cname);
39
40         this->name = cname;
41         this->age = ts ? ts : ServerInstance->Time();
42
43         topicset = 0;
44         modes.reset();
45 }
46
47 void Channel::SetMode(char mode,bool mode_on)
48 {
49         modes[mode-65] = mode_on;
50 }
51
52 void Channel::SetMode(ModeHandler* mh, bool on)
53 {
54         modes[mh->GetModeChar() - 65] = on;
55 }
56
57 void Channel::SetModeParam(char mode, const std::string& parameter)
58 {
59         CustomModeList::iterator n = custom_mode_params.find(mode);
60         // always erase, even if changing, so that the map gets the new value
61         if (n != custom_mode_params.end())
62                 custom_mode_params.erase(n);
63         if (parameter.empty())
64         {
65                 modes[mode-65] = false;
66         }
67         else
68         {
69                 custom_mode_params[mode] = parameter;
70                 modes[mode-65] = true;
71         }
72 }
73
74 void Channel::SetModeParam(ModeHandler* mode, const std::string& parameter)
75 {
76         SetModeParam(mode->GetModeChar(), parameter);
77 }
78
79 std::string Channel::GetModeParameter(char mode)
80 {
81         CustomModeList::iterator n = custom_mode_params.find(mode);
82         if (n != custom_mode_params.end())
83                 return n->second;
84         return "";
85 }
86
87 std::string Channel::GetModeParameter(ModeHandler* mode)
88 {
89         CustomModeList::iterator n = custom_mode_params.find(mode->GetModeChar());
90         if (n != custom_mode_params.end())
91                 return n->second;
92         return "";
93 }
94
95 int Channel::SetTopic(User *u, std::string &ntopic, bool forceset)
96 {
97         if (!u)
98                 u = ServerInstance->FakeClient;
99         if (IS_LOCAL(u) && !forceset)
100         {
101                 ModResult res;
102                 FIRST_MOD_RESULT(OnPreTopicChange, res, (u,this,ntopic));
103
104                 if (res == MOD_RES_DENY)
105                         return CMD_FAILURE;
106                 if (res != MOD_RES_ALLOW)
107                 {
108                         if (!this->HasUser(u))
109                         {
110                                 u->WriteNumeric(442, "%s %s :You're not on that channel!",u->nick.c_str(), this->name.c_str());
111                                 return CMD_FAILURE;
112                         }
113                         if (IsModeSet('t') && !ServerInstance->OnCheckExemption(u,this,"topiclock").check(GetPrefixValue(u) >= HALFOP_VALUE))
114                         {
115                                 u->WriteNumeric(482, "%s %s :You do not have access to change the topic on this channel", u->nick.c_str(), this->name.c_str());
116                                 return CMD_FAILURE;
117                         }
118                 }
119         }
120
121         this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
122         if (u)
123         {
124                 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
125                 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
126         }
127         else
128         {
129                 this->setby.assign(ServerInstance->Config->ServerName);
130                 this->WriteChannelWithServ(ServerInstance->Config->ServerName, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
131         }
132
133         this->topicset = ServerInstance->Time();
134
135         FOREACH_MOD(I_OnPostTopicChange,OnPostTopicChange(u, this, this->topic));
136
137         return CMD_SUCCESS;
138 }
139
140 Membership* Channel::AddUser(User* user)
141 {
142         Membership*& memb = userlist[user];
143         if (memb)
144                 return NULL;
145
146         memb = new Membership(user, this);
147         return memb;
148 }
149
150 void Channel::DelUser(User* user)
151 {
152         UserMembIter a = userlist.find(user);
153
154         if (a != userlist.end())
155         {
156                 a->second->cull();
157                 delete a->second;
158                 userlist.erase(a);
159         }
160
161         if (userlist.empty())
162         {
163                 ModResult res;
164                 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
165                 if (res == MOD_RES_DENY)
166                         return;
167                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
168                 /* kill the record */
169                 if (iter != ServerInstance->chanlist->end())
170                 {
171                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
172                         ServerInstance->chanlist->erase(iter);
173                 }
174
175                 ClearInvites();
176                 ServerInstance->GlobalCulls.AddItem(this);
177         }
178 }
179
180 Membership* Channel::GetUser(User* user)
181 {
182         UserMembIter i = userlist.find(user);
183         if (i == userlist.end())
184                 return NULL;
185         return i->second;
186 }
187
188 void Channel::SetDefaultModes()
189 {
190         ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
191                 ServerInstance->Config->DefaultModes.c_str());
192         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
193         std::string modeseq;
194         std::string parameter;
195
196         list.GetToken(modeseq);
197
198         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
199         {
200                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
201                 if (mode)
202                 {
203                         if (mode->GetNumParams(true))
204                                 list.GetToken(parameter);
205                         else
206                                 parameter.clear();
207
208                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
209                 }
210         }
211 }
212
213 /*
214  * add a channel to a user, creating the record for it if needed and linking
215  * it to the user record
216  */
217 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
218 {
219         if (user->registered != REG_ALL)
220         {
221                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
222                 return NULL;
223         }
224
225         /*
226          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
227          * We restrict local users to MaxChans channels.
228          * We restrict local operators to OperMaxChans channels.
229          * This is a lot more logical than how it was formerly. -- w00t
230          */
231         if (!override)
232         {
233                 if (user->HasPrivPermission("channels/high-join-limit"))
234                 {
235                         if (user->chans.size() >= ServerInstance->Config->OperMaxChans)
236                         {
237                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cname.c_str());
238                                 return NULL;
239                         }
240                 }
241                 else
242                 {
243                         unsigned int maxchans = user->GetClass()->maxchans;
244                         if (!maxchans)
245                                 maxchans = ServerInstance->Config->MaxChans;
246                         if (user->chans.size() >= maxchans)
247                         {
248                                 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cname.c_str());
249                                 return NULL;
250                         }
251                 }
252         }
253
254         // Crop channel name if it's too long
255         if (cname.length() > ServerInstance->Config->Limits.ChanMax)
256                 cname.resize(ServerInstance->Config->Limits.ChanMax);
257
258         Channel* chan = ServerInstance->FindChan(cname);
259         bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
260         std::string privs; // Prefix mode(letter)s to give to the joining user
261
262         if (!chan)
263         {
264                 privs = "o";
265
266                 if (override == false)
267                 {
268                         // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
269                         ModResult MOD_RESULT;
270                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
271                         if (MOD_RESULT == MOD_RES_DENY)
272                                 return NULL; // A module wasn't happy with the join, abort
273                 }
274
275                 chan = new Channel(cname, ServerInstance->Time());
276                 // Set the default modes on the channel (<options:defaultmodes>)
277                 chan->SetDefaultModes();
278         }
279         else
280         {
281                 /* Already on the channel */
282                 if (chan->HasUser(user))
283                         return NULL;
284
285                 if (override == false)
286                 {
287                         ModResult MOD_RESULT;
288                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
289
290                         // A module explicitly denied the join and (hopefully) generated a message
291                         // describing the situation, so we may stop here without sending anything
292                         if (MOD_RESULT == MOD_RES_DENY)
293                                 return NULL;
294
295                         // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
296                         // most of the time) then proceed to check channel modes +k, +i, +l and bans,
297                         // in this order.
298                         // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
299                         // then this entire section is skipped
300                         if (MOD_RESULT == MOD_RES_PASSTHRU)
301                         {
302                                 std::string ckey = chan->GetModeParameter('k');
303                                 bool invited = user->IsInvited(chan);
304                                 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
305
306                                 if (!ckey.empty())
307                                 {
308                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
309                                         if (!MOD_RESULT.check((ckey == key) || can_bypass))
310                                         {
311                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
312                                                 user->WriteNumeric(ERR_BADCHANNELKEY, "%s %s :Cannot join channel (Incorrect channel key)",user->nick.c_str(), chan->name.c_str());
313                                                 return NULL;
314                                         }
315                                 }
316
317                                 if (chan->IsModeSet('i'))
318                                 {
319                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
320                                         if (!MOD_RESULT.check(invited))
321                                         {
322                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s %s :Cannot join channel (Invite only)",user->nick.c_str(), chan->name.c_str());
323                                                 return NULL;
324                                         }
325                                 }
326
327                                 std::string limit = chan->GetModeParameter('l');
328                                 if (!limit.empty())
329                                 {
330                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
331                                         if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
332                                         {
333                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s %s :Cannot join channel (Channel is full)",user->nick.c_str(), chan->name.c_str());
334                                                 return NULL;
335                                         }
336                                 }
337
338                                 if (chan->IsBanned(user) && !can_bypass)
339                                 {
340                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s %s :Cannot join channel (You're banned)",user->nick.c_str(), chan->name.c_str());
341                                         return NULL;
342                                 }
343
344                                 /*
345                                  * If the user has invites for this channel, remove them now
346                                  * after a successful join so they don't build up.
347                                  */
348                                 if (invited)
349                                 {
350                                         user->RemoveInvite(chan);
351                                 }
352                         }
353                 }
354         }
355
356         // We figured that this join is allowed and also created the
357         // channel if it didn't exist before, now do the actual join
358         chan->ForceJoin(user, &privs, false, created_by_local);
359         return chan;
360 }
361
362 void Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
363 {
364         Membership* memb = this->AddUser(user);
365         if (!memb)
366                 return; // Already on the channel
367
368         if (IS_SERVER(user))
369         {
370                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
371                 return;
372         }
373
374         user->chans.insert(this);
375
376         if (privs)
377         {
378                 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
379                 // remote user and his own server set the modes), then set them internally now
380                 memb->modes = *privs;
381                 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
382                 {
383                         ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
384                         if (mh)
385                         {
386                                 std::string nick = user->nick;
387                                 /* Set, and make sure that the mode handler knows this mode was now set */
388                                 this->SetPrefix(user, mh->GetModeChar(), true);
389                                 mh->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, nick, true);
390                         }
391                 }
392         }
393
394         // 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
395         CUList except_list;
396         FOREACH_MOD(I_OnUserJoin,OnUserJoin(memb, bursting, created_by_local, except_list));
397
398         this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
399
400         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
401         if ((GetUserCounter() > 1) && (!memb->modes.empty()))
402         {
403                 std::string ms = memb->modes;
404                 for(unsigned int i=0; i < memb->modes.length(); i++)
405                         ms.append(" ").append(user->nick);
406
407                 except_list.insert(user);
408                 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
409         }
410
411         if (IS_LOCAL(user))
412         {
413                 if (this->topicset)
414                 {
415                         user->WriteNumeric(RPL_TOPIC, "%s %s :%s", user->nick.c_str(), this->name.c_str(), this->topic.c_str());
416                         user->WriteNumeric(RPL_TOPICTIME, "%s %s %s %lu", user->nick.c_str(), this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
417                 }
418                 this->UserList(user);
419         }
420
421         FOREACH_MOD(I_OnPostJoin,OnPostJoin(memb));
422 }
423
424 bool Channel::IsBanned(User* user)
425 {
426         ModResult result;
427         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
428
429         if (result != MOD_RES_PASSTHRU)
430                 return (result == MOD_RES_DENY);
431
432         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
433         const ListModeBase::ModeList* bans = banlm->GetList(this);
434         if (bans)
435         {
436                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
437                 {
438                         if (CheckBan(user, it->mask))
439                                 return true;
440                 }
441         }
442         return false;
443 }
444
445 bool Channel::CheckBan(User* user, const std::string& mask)
446 {
447         ModResult result;
448         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
449         if (result != MOD_RES_PASSTHRU)
450                 return (result == MOD_RES_DENY);
451
452         // extbans were handled above, if this is one it obviously didn't match
453         if ((mask.length() <= 2) || (mask[1] == ':'))
454                 return false;
455
456         std::string::size_type at = mask.find('@');
457         if (at == std::string::npos)
458                 return false;
459
460         const std::string nickIdent = user->nick + "!" + user->ident;
461         std::string prefix = mask.substr(0, at);
462         if (InspIRCd::Match(nickIdent, prefix, NULL))
463         {
464                 std::string suffix = mask.substr(at + 1);
465                 if (InspIRCd::Match(user->host, suffix, NULL) ||
466                         InspIRCd::Match(user->dhost, suffix, NULL) ||
467                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
468                         return true;
469         }
470         return false;
471 }
472
473 ModResult Channel::GetExtBanStatus(User *user, char type)
474 {
475         ModResult rv;
476         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
477         if (rv != MOD_RES_PASSTHRU)
478                 return rv;
479
480         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
481         const ListModeBase::ModeList* bans = banlm->GetList(this);
482         if (bans)
483
484         {
485                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
486                 {
487                         if (CheckBan(user, it->mask))
488                                 return MOD_RES_DENY;
489                 }
490         }
491         return MOD_RES_PASSTHRU;
492 }
493
494 /* Channel::PartUser
495  * remove a channel from a users record, and return the number of users left.
496  * Therefore, if this function returns 0 the caller should delete the Channel.
497  */
498 void Channel::PartUser(User *user, std::string &reason)
499 {
500         if (!user)
501                 return;
502
503         Membership* memb = GetUser(user);
504
505         if (memb)
506         {
507                 CUList except_list;
508                 FOREACH_MOD(I_OnUserPart,OnUserPart(memb, reason, except_list));
509
510                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
511
512                 user->chans.erase(this);
513                 this->RemoveAllPrefixes(user);
514         }
515
516         this->DelUser(user);
517 }
518
519 void Channel::KickUser(User *src, User *user, const std::string& reason)
520 {
521         if (!src || !user)
522                 return;
523
524         Membership* memb = GetUser(user);
525         if (IS_LOCAL(src))
526         {
527                 if (!memb)
528                 {
529                         src->WriteNumeric(ERR_USERNOTINCHANNEL, "%s %s %s :They are not on that channel",src->nick.c_str(), user->nick.c_str(), this->name.c_str());
530                         return;
531                 }
532                 if ((ServerInstance->ULine(user->server)) && (!ServerInstance->ULine(src->server)))
533                 {
534                         src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :Only a u-line may kick a u-line from a channel.",src->nick.c_str(), this->name.c_str());
535                         return;
536                 }
537
538                 ModResult res;
539                 if (ServerInstance->ULine(src->server))
540                         res = MOD_RES_ALLOW;
541                 else
542                         FIRST_MOD_RESULT(OnUserPreKick, res, (src,memb,reason));
543
544                 if (res == MOD_RES_DENY)
545                         return;
546
547                 if (res == MOD_RES_PASSTHRU)
548                 {
549                         unsigned int them = this->GetPrefixValue(src);
550                         unsigned int req = HALFOP_VALUE;
551                         for (std::string::size_type i = 0; i < memb->modes.length(); i++)
552                         {
553                                 ModeHandler* mh = ServerInstance->Modes->FindMode(memb->modes[i], MODETYPE_CHANNEL);
554                                 if (mh && mh->GetLevelRequired() > req)
555                                         req = mh->GetLevelRequired();
556                         }
557
558                         if (them < req)
559                         {
560                                 src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator",
561                                         src->nick.c_str(), this->name.c_str(), req > HALFOP_VALUE ? "" : "half-");
562                                 return;
563                         }
564                 }
565         }
566
567         if (memb)
568         {
569                 CUList except_list;
570                 FOREACH_MOD(I_OnUserKick,OnUserKick(src, memb, reason, except_list));
571
572                 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), user->nick.c_str(), reason.c_str());
573
574                 user->chans.erase(this);
575                 this->RemoveAllPrefixes(user);
576         }
577
578         this->DelUser(user);
579 }
580
581 void Channel::WriteChannel(User* user, const char* text, ...)
582 {
583         if (!user || !text)
584                 return;
585
586         std::string textbuffer;
587         VAFORMAT(textbuffer, text, text);
588         this->WriteChannel(user, textbuffer);
589 }
590
591 void Channel::WriteChannel(User* user, const std::string &text)
592 {
593         if (!user)
594                 return;
595
596         const std::string message = ":" + user->GetFullHost() + " " + text;
597
598         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
599         {
600                 if (IS_LOCAL(i->first))
601                         i->first->Write(message);
602         }
603 }
604
605 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
606 {
607         if (!text)
608                 return;
609
610         std::string textbuffer;
611         VAFORMAT(textbuffer, text, text);
612         this->WriteChannelWithServ(ServName, textbuffer);
613 }
614
615 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
616 {
617         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
618
619         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
620         {
621                 if (IS_LOCAL(i->first))
622                         i->first->Write(message);
623         }
624 }
625
626 /* write formatted text from a source user to all users on a channel except
627  * for the sender (for privmsg etc) */
628 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
629 {
630         if (!text)
631                 return;
632
633         std::string textbuffer;
634         VAFORMAT(textbuffer, text, text);
635         this->WriteAllExceptSender(user, serversource, status, textbuffer);
636 }
637
638 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
639 {
640         if (!text)
641                 return;
642
643         std::string textbuffer;
644         VAFORMAT(textbuffer, text, text);
645         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
646         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
647 }
648
649 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
650 {
651         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
652         this->RawWriteAllExcept(user, serversource, status, except_list, message);
653 }
654
655 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
656 {
657         unsigned int minrank = 0;
658         if (status)
659         {
660                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
661                 if (mh)
662                         minrank = mh->GetPrefixRank();
663         }
664         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
665         {
666                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
667                 {
668                         /* User doesn't have the status we're after */
669                         if (minrank && i->second->getRank() < minrank)
670                                 continue;
671
672                         i->first->Write(out);
673                 }
674         }
675 }
676
677 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
678 {
679         CUList except_list;
680         except_list.insert(user);
681         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
682 }
683
684 /*
685  * return a count of the users on a specific channel accounting for
686  * invisible users who won't increase the count. e.g. for /LIST
687  */
688 int Channel::CountInvisible()
689 {
690         int count = 0;
691         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
692         {
693                 if (!i->first->quitting && !i->first->IsModeSet('i'))
694                         count++;
695         }
696
697         return count;
698 }
699
700 const char* Channel::ChanModes(bool showkey)
701 {
702         static std::string scratch;
703         std::string sparam;
704
705         scratch.clear();
706
707         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
708         for(int n = 0; n < 64; n++)
709         {
710                 if(this->modes[n])
711                 {
712                         scratch.push_back(n + 65);
713                         if (n == 'k' - 65 && !showkey)
714                         {
715                                 sparam += " <key>";
716                         }
717                         else
718                         {
719                                 const std::string param = this->GetModeParameter(n + 65);
720                                 if (!param.empty())
721                                 {
722                                         sparam += ' ';
723                                         sparam += param;
724                                 }
725                         }
726                 }
727         }
728
729         scratch += sparam;
730         return scratch.c_str();
731 }
732
733 /* compile a userlist of a channel into a string, each nick seperated by
734  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
735  */
736 void Channel::UserList(User *user)
737 {
738         char list[MAXBUF];
739         size_t dlen, curlen;
740
741         if (!IS_LOCAL(user))
742                 return;
743
744         if (this->IsModeSet('s') && !this->HasUser(user) && !user->HasPrivPermission("channels/auspex"))
745         {
746                 user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
747                 return;
748         }
749
750         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name.c_str());
751
752         int numusers = 0;
753         char* ptr = list + dlen;
754
755         /* Improvement by Brain - this doesnt change in value, so why was it inside
756          * the loop?
757          */
758         bool has_user = this->HasUser(user);
759
760         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
761         {
762                 if (i->first->quitting)
763                         continue;
764                 if ((!has_user) && (i->first->IsModeSet('i')))
765                 {
766                         /*
767                          * user is +i, and source not on the channel, does not show
768                          * nick in NAMES list
769                          */
770                         continue;
771                 }
772
773                 std::string prefixlist = this->GetPrefixChar(i->first);
774                 std::string nick = i->first->nick;
775
776                 FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->second, prefixlist, nick));
777
778                 /* Nick was nuked, a module wants us to skip it */
779                 if (nick.empty())
780                         continue;
781
782                 size_t ptrlen = 0;
783
784                 if (curlen + prefixlist.length() + nick.length() + 1 > 480)
785                 {
786                         /* list overflowed into multiple numerics */
787                         user->WriteNumeric(RPL_NAMREPLY, std::string(list));
788
789                         /* reset our lengths */
790                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name.c_str());
791                         ptr = list + dlen;
792
793                         numusers = 0;
794                 }
795
796                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
797
798                 curlen += ptrlen;
799                 ptr += ptrlen;
800
801                 numusers++;
802         }
803
804         /* if whats left in the list isnt empty, send it */
805         if (numusers)
806         {
807                 user->WriteNumeric(RPL_NAMREPLY, std::string(list));
808         }
809
810         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
811 }
812
813 /* returns the status character for a given user on a channel, e.g. @ for op,
814  * % for halfop etc. If the user has several modes set, the highest mode
815  * the user has must be returned.
816  */
817 const char* Channel::GetPrefixChar(User *user)
818 {
819         static char pf[2] = {0, 0};
820         *pf = 0;
821         unsigned int bestrank = 0;
822
823         UserMembIter m = userlist.find(user);
824         if (m != userlist.end())
825         {
826                 for(unsigned int i=0; i < m->second->modes.length(); i++)
827                 {
828                         char mchar = m->second->modes[i];
829                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
830                         if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
831                         {
832                                 bestrank = mh->GetPrefixRank();
833                                 pf[0] = mh->GetPrefix();
834                         }
835                 }
836         }
837         return pf;
838 }
839
840 unsigned int Membership::getRank()
841 {
842         char mchar = modes.c_str()[0];
843         unsigned int rv = 0;
844         if (mchar)
845         {
846                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
847                 if (mh)
848                         rv = mh->GetPrefixRank();
849         }
850         return rv;
851 }
852
853 const char* Channel::GetAllPrefixChars(User* user)
854 {
855         static char prefix[64];
856         int ctr = 0;
857
858         UserMembIter m = userlist.find(user);
859         if (m != userlist.end())
860         {
861                 for(unsigned int i=0; i < m->second->modes.length(); i++)
862                 {
863                         char mchar = m->second->modes[i];
864                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
865                         if (mh && mh->GetPrefix())
866                                 prefix[ctr++] = mh->GetPrefix();
867                 }
868         }
869         prefix[ctr] = 0;
870
871         return prefix;
872 }
873
874 unsigned int Channel::GetPrefixValue(User* user)
875 {
876         UserMembIter m = userlist.find(user);
877         if (m == userlist.end())
878                 return 0;
879         return m->second->getRank();
880 }
881
882 bool Channel::SetPrefix(User* user, char prefix, bool adding)
883 {
884         ModeHandler* delta_mh = ServerInstance->Modes->FindMode(prefix, MODETYPE_CHANNEL);
885         if (!delta_mh)
886                 return false;
887         UserMembIter m = userlist.find(user);
888         if (m == userlist.end())
889                 return false;
890         for(unsigned int i=0; i < m->second->modes.length(); i++)
891         {
892                 char mchar = m->second->modes[i];
893                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
894                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
895                 {
896                         m->second->modes =
897                                 m->second->modes.substr(0,i) +
898                                 (adding ? std::string(1, prefix) : "") +
899                                 m->second->modes.substr(mchar == prefix ? i+1 : i);
900                         return adding != (mchar == prefix);
901                 }
902         }
903         if (adding)
904                 m->second->modes += std::string(1, prefix);
905         return adding;
906 }
907
908 void Channel::RemoveAllPrefixes(User* user)
909 {
910         UserMembIter m = userlist.find(user);
911         if (m != userlist.end())
912         {
913                 m->second->modes.clear();
914         }
915 }
916
917 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
918 {
919         if ((timeout != 0) && (ServerInstance->Time() >= timeout))
920                 // Expired, don't bother
921                 return;
922
923         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
924
925         Invitation* inv = Invitation::Find(c, u, false);
926         if (inv)
927         {
928                  if ((inv->expiry == 0) || (inv->expiry > timeout))
929                         return;
930                 inv->expiry = timeout;
931                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
932         }
933         else
934         {
935                 inv = new Invitation(c, u, timeout);
936                 c->invites.push_back(inv);
937                 u->invites.push_back(inv);
938                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
939         }
940 }
941
942 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
943 {
944         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find chan=%s user=%s check_expired=%d", c ? c->name.c_str() : "NULL", u ? u->uuid.c_str() : "NULL", check_expired);
945         if (!u || u->invites.empty())
946                 return NULL;
947
948         InviteList locallist;
949         locallist.swap(u->invites);
950
951         Invitation* result = NULL;
952         for (InviteList::iterator i = locallist.begin(); i != locallist.end(); )
953         {
954                 Invitation* inv = *i;
955                 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
956                 {
957                         /* Expired invite, remove it. */
958                         std::string expiration = ServerInstance->TimeString(inv->expiry);
959                         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
960                         i = locallist.erase(i);
961                         inv->cull();
962                         delete inv;
963                 }
964                 else
965                 {
966                         /* Is it what we're searching for? */
967                         if (inv->chan == c)
968                         {
969                                 result = inv;
970                                 break;
971                         }
972                         ++i;
973                 }
974         }
975
976         locallist.swap(u->invites);
977         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
978         return result;
979 }
980
981 Invitation::~Invitation()
982 {
983         // Remove this entry from both lists
984         InviteList::iterator it = std::find(chan->invites.begin(), chan->invites.end(), this);
985         if (it != chan->invites.end())
986                 chan->invites.erase(it);
987         it = std::find(user->invites.begin(), user->invites.end(), this);
988         if (it != user->invites.end())
989                 user->invites.erase(it);
990 }
991
992 void InviteBase::ClearInvites()
993 {
994         ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "InviteBase::ClearInvites %p", (void*) this);
995         InviteList locallist;
996         locallist.swap(invites);
997         for (InviteList::const_iterator i = locallist.begin(); i != locallist.end(); ++i)
998         {
999                 (*i)->cull();
1000                 delete *i;
1001         }
1002 }