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