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