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