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