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