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