]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
0cc00746496ef196b8de3285df6055f5dba960ac
[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         char textbuffer[MAXBUF];
599         va_list argsPtr;
600
601         if (!user || !text)
602                 return;
603
604         va_start(argsPtr, text);
605         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
606         va_end(argsPtr);
607
608         this->WriteChannel(user, std::string(textbuffer));
609 }
610
611 void Channel::WriteChannel(User* user, const std::string &text)
612 {
613         if (!user)
614                 return;
615
616         const std::string message = ":" + user->GetFullHost() + " " + text;
617
618         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
619         {
620                 if (IS_LOCAL(i->first))
621                         i->first->Write(message);
622         }
623 }
624
625 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
626 {
627         char textbuffer[MAXBUF];
628         va_list argsPtr;
629
630         if (!text)
631                 return;
632
633         va_start(argsPtr, text);
634         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
635         va_end(argsPtr);
636
637         this->WriteChannelWithServ(ServName, std::string(textbuffer));
638 }
639
640 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
641 {
642         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
643
644         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
645         {
646                 if (IS_LOCAL(i->first))
647                         i->first->Write(message);
648         }
649 }
650
651 /* write formatted text from a source user to all users on a channel except
652  * for the sender (for privmsg etc) */
653 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
654 {
655         char textbuffer[MAXBUF];
656         va_list argsPtr;
657
658         if (!text)
659                 return;
660
661         va_start(argsPtr, text);
662         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
663         va_end(argsPtr);
664
665         this->WriteAllExceptSender(user, serversource, status, std::string(textbuffer));
666 }
667
668 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
669 {
670         char textbuffer[MAXBUF];
671         va_list argsPtr;
672
673         if (!text)
674                 return;
675
676         int offset = snprintf(textbuffer,MAXBUF,":%s ", serversource ? ServerInstance->Config->ServerName.c_str() : user->GetFullHost().c_str());
677
678         va_start(argsPtr, text);
679         vsnprintf(textbuffer + offset, MAXBUF - offset, text, argsPtr);
680         va_end(argsPtr);
681
682         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(textbuffer));
683 }
684
685 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
686 {
687         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
688         this->RawWriteAllExcept(user, serversource, status, except_list, message);
689 }
690
691 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
692 {
693         unsigned int minrank = 0;
694         if (status)
695         {
696                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
697                 if (mh)
698                         minrank = mh->GetPrefixRank();
699         }
700         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
701         {
702                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
703                 {
704                         /* User doesn't have the status we're after */
705                         if (minrank && i->second->getRank() < minrank)
706                                 continue;
707
708                         i->first->Write(out);
709                 }
710         }
711 }
712
713 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
714 {
715         CUList except_list;
716         except_list.insert(user);
717         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
718 }
719
720 /*
721  * return a count of the users on a specific channel accounting for
722  * invisible users who won't increase the count. e.g. for /LIST
723  */
724 int Channel::CountInvisible()
725 {
726         int count = 0;
727         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
728         {
729                 if (!i->first->quitting && !i->first->IsModeSet('i'))
730                         count++;
731         }
732
733         return count;
734 }
735
736 const char* Channel::ChanModes(bool showkey)
737 {
738         static std::string scratch;
739         std::string sparam;
740
741         scratch.clear();
742
743         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
744         for(int n = 0; n < 64; n++)
745         {
746                 if(this->modes[n])
747                 {
748                         scratch.push_back(n + 65);
749                         if (n == 'k' - 65 && !showkey)
750                         {
751                                 sparam += " <key>";
752                         }
753                         else
754                         {
755                                 const std::string param = this->GetModeParameter(n + 65);
756                                 if (!param.empty())
757                                 {
758                                         sparam += ' ';
759                                         sparam += param;
760                                 }
761                         }
762                 }
763         }
764
765         scratch += sparam;
766         return scratch.c_str();
767 }
768
769 /* compile a userlist of a channel into a string, each nick seperated by
770  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
771  */
772 void Channel::UserList(User *user)
773 {
774         char list[MAXBUF];
775         size_t dlen, curlen;
776
777         if (!IS_LOCAL(user))
778                 return;
779
780         if (this->IsModeSet('s') && !this->HasUser(user) && !user->HasPrivPermission("channels/auspex"))
781         {
782                 user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
783                 return;
784         }
785
786         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name.c_str());
787
788         int numusers = 0;
789         char* ptr = list + dlen;
790
791         /* Improvement by Brain - this doesnt change in value, so why was it inside
792          * the loop?
793          */
794         bool has_user = this->HasUser(user);
795
796         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
797         {
798                 if (i->first->quitting)
799                         continue;
800                 if ((!has_user) && (i->first->IsModeSet('i')))
801                 {
802                         /*
803                          * user is +i, and source not on the channel, does not show
804                          * nick in NAMES list
805                          */
806                         continue;
807                 }
808
809                 std::string prefixlist = this->GetPrefixChar(i->first);
810                 std::string nick = i->first->nick;
811
812                 FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->second, prefixlist, nick));
813
814                 /* Nick was nuked, a module wants us to skip it */
815                 if (nick.empty())
816                         continue;
817
818                 size_t ptrlen = 0;
819
820                 if (curlen + prefixlist.length() + nick.length() + 1 > 480)
821                 {
822                         /* list overflowed into multiple numerics */
823                         user->WriteNumeric(RPL_NAMREPLY, std::string(list));
824
825                         /* reset our lengths */
826                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name.c_str());
827                         ptr = list + dlen;
828
829                         numusers = 0;
830                 }
831
832                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
833
834                 curlen += ptrlen;
835                 ptr += ptrlen;
836
837                 numusers++;
838         }
839
840         /* if whats left in the list isnt empty, send it */
841         if (numusers)
842         {
843                 user->WriteNumeric(RPL_NAMREPLY, std::string(list));
844         }
845
846         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
847 }
848
849 /* returns the status character for a given user on a channel, e.g. @ for op,
850  * % for halfop etc. If the user has several modes set, the highest mode
851  * the user has must be returned.
852  */
853 const char* Channel::GetPrefixChar(User *user)
854 {
855         static char pf[2] = {0, 0};
856         *pf = 0;
857         unsigned int bestrank = 0;
858
859         UserMembIter m = userlist.find(user);
860         if (m != userlist.end())
861         {
862                 for(unsigned int i=0; i < m->second->modes.length(); i++)
863                 {
864                         char mchar = m->second->modes[i];
865                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
866                         if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
867                         {
868                                 bestrank = mh->GetPrefixRank();
869                                 pf[0] = mh->GetPrefix();
870                         }
871                 }
872         }
873         return pf;
874 }
875
876 unsigned int Membership::getRank()
877 {
878         char mchar = modes.c_str()[0];
879         unsigned int rv = 0;
880         if (mchar)
881         {
882                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
883                 if (mh)
884                         rv = mh->GetPrefixRank();
885         }
886         return rv;
887 }
888
889 const char* Channel::GetAllPrefixChars(User* user)
890 {
891         static char prefix[64];
892         int ctr = 0;
893
894         UserMembIter m = userlist.find(user);
895         if (m != userlist.end())
896         {
897                 for(unsigned int i=0; i < m->second->modes.length(); i++)
898                 {
899                         char mchar = m->second->modes[i];
900                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
901                         if (mh && mh->GetPrefix())
902                                 prefix[ctr++] = mh->GetPrefix();
903                 }
904         }
905         prefix[ctr] = 0;
906
907         return prefix;
908 }
909
910 unsigned int Channel::GetPrefixValue(User* user)
911 {
912         UserMembIter m = userlist.find(user);
913         if (m == userlist.end())
914                 return 0;
915         return m->second->getRank();
916 }
917
918 bool Channel::SetPrefix(User* user, char prefix, bool adding)
919 {
920         ModeHandler* delta_mh = ServerInstance->Modes->FindMode(prefix, MODETYPE_CHANNEL);
921         if (!delta_mh)
922                 return false;
923         UserMembIter m = userlist.find(user);
924         if (m == userlist.end())
925                 return false;
926         for(unsigned int i=0; i < m->second->modes.length(); i++)
927         {
928                 char mchar = m->second->modes[i];
929                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
930                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
931                 {
932                         m->second->modes =
933                                 m->second->modes.substr(0,i) +
934                                 (adding ? std::string(1, prefix) : "") +
935                                 m->second->modes.substr(mchar == prefix ? i+1 : i);
936                         return adding != (mchar == prefix);
937                 }
938         }
939         if (adding)
940                 m->second->modes += std::string(1, prefix);
941         return adding;
942 }
943
944 void Channel::RemoveAllPrefixes(User* user)
945 {
946         UserMembIter m = userlist.find(user);
947         if (m != userlist.end())
948         {
949                 m->second->modes.clear();
950         }
951 }
952
953 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
954 {
955         if ((timeout != 0) && (ServerInstance->Time() >= timeout))
956                 // Expired, don't bother
957                 return;
958
959         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
960
961         Invitation* inv = Invitation::Find(c, u, false);
962         if (inv)
963         {
964                  if ((inv->expiry == 0) || (inv->expiry > timeout))
965                         return;
966                 inv->expiry = timeout;
967                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
968         }
969         else
970         {
971                 inv = new Invitation(c, u, timeout);
972                 c->invites.push_back(inv);
973                 u->invites.push_back(inv);
974                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
975         }
976 }
977
978 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
979 {
980         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);
981         if (!u || u->invites.empty())
982                 return NULL;
983
984         InviteList locallist;
985         locallist.swap(u->invites);
986
987         Invitation* result = NULL;
988         for (InviteList::iterator i = locallist.begin(); i != locallist.end(); )
989         {
990                 Invitation* inv = *i;
991                 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
992                 {
993                         /* Expired invite, remove it. */
994                         std::string expiration = ServerInstance->TimeString(inv->expiry);
995                         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
996                         i = locallist.erase(i);
997                         inv->cull();
998                         delete inv;
999                 }
1000                 else
1001                 {
1002                         /* Is it what we're searching for? */
1003                         if (inv->chan == c)
1004                         {
1005                                 result = inv;
1006                                 break;
1007                         }
1008                         ++i;
1009                 }
1010         }
1011
1012         locallist.swap(u->invites);
1013         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
1014         return result;
1015 }
1016
1017 Invitation::~Invitation()
1018 {
1019         // Remove this entry from both lists
1020         InviteList::iterator it = std::find(chan->invites.begin(), chan->invites.end(), this);
1021         if (it != chan->invites.end())
1022                 chan->invites.erase(it);
1023         it = std::find(user->invites.begin(), user->invites.end(), this);
1024         if (it != user->invites.end())
1025                 user->invites.erase(it);
1026 }
1027
1028 void InviteBase::ClearInvites()
1029 {
1030         ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "InviteBase::ClearInvites %p", (void*) this);
1031         InviteList locallist;
1032         locallist.swap(invites);
1033         for (InviteList::const_iterator i = locallist.begin(); i != locallist.end(); ++i)
1034         {
1035                 (*i)->cull();
1036                 delete *i;
1037         }
1038 }