]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Move the definition of the BanCacheHit constructor into the source file from the...
[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 Membership* 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 NULL;
301         }
302
303         Membership* memb = this->AddUser(user);
304         if (!memb)
305                 return NULL; // 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         return memb;
354 }
355
356 bool Channel::IsBanned(User* user)
357 {
358         ModResult result;
359         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
360
361         if (result != MOD_RES_PASSTHRU)
362                 return (result == MOD_RES_DENY);
363
364         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
365         const ListModeBase::ModeList* bans = banlm->GetList(this);
366         if (bans)
367         {
368                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
369                 {
370                         if (CheckBan(user, it->mask))
371                                 return true;
372                 }
373         }
374         return false;
375 }
376
377 bool Channel::CheckBan(User* user, const std::string& mask)
378 {
379         ModResult result;
380         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
381         if (result != MOD_RES_PASSTHRU)
382                 return (result == MOD_RES_DENY);
383
384         // extbans were handled above, if this is one it obviously didn't match
385         if ((mask.length() <= 2) || (mask[1] == ':'))
386                 return false;
387
388         std::string::size_type at = mask.find('@');
389         if (at == std::string::npos)
390                 return false;
391
392         const std::string nickIdent = user->nick + "!" + user->ident;
393         std::string prefix = mask.substr(0, at);
394         if (InspIRCd::Match(nickIdent, prefix, NULL))
395         {
396                 std::string suffix = mask.substr(at + 1);
397                 if (InspIRCd::Match(user->host, suffix, NULL) ||
398                         InspIRCd::Match(user->dhost, suffix, NULL) ||
399                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
400                         return true;
401         }
402         return false;
403 }
404
405 ModResult Channel::GetExtBanStatus(User *user, char type)
406 {
407         ModResult rv;
408         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
409         if (rv != MOD_RES_PASSTHRU)
410                 return rv;
411
412         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
413         const ListModeBase::ModeList* bans = banlm->GetList(this);
414         if (bans)
415         {
416                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
417                 {
418                         if (CheckBan(user, it->mask))
419                                 return MOD_RES_DENY;
420                 }
421         }
422         return MOD_RES_PASSTHRU;
423 }
424
425 /* Channel::PartUser
426  * Remove a channel from a users record, remove the reference to the Membership object
427  * from the channel and destroy it.
428  */
429 void Channel::PartUser(User *user, std::string &reason)
430 {
431         UserMembIter membiter = userlist.find(user);
432
433         if (membiter != userlist.end())
434         {
435                 Membership* memb = membiter->second;
436                 CUList except_list;
437                 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
438
439                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
440
441                 // Remove this channel from the user's chanlist
442                 user->chans.erase(memb);
443                 // Remove the Membership from this channel's userlist and destroy it
444                 this->DelUser(membiter);
445         }
446 }
447
448 void Channel::KickUser(User* src, const UserMembIter& victimiter, const std::string& reason)
449 {
450         Membership* memb = victimiter->second;
451         CUList except_list;
452         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
453
454         User* victim = memb->user;
455         WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
456
457         victim->chans.erase(memb);
458         this->DelUser(victimiter);
459 }
460
461 void Channel::WriteChannel(User* user, const char* text, ...)
462 {
463         std::string textbuffer;
464         VAFORMAT(textbuffer, text, text);
465         this->WriteChannel(user, textbuffer);
466 }
467
468 void Channel::WriteChannel(User* user, const std::string &text)
469 {
470         const std::string message = ":" + user->GetFullHost() + " " + text;
471
472         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
473         {
474                 if (IS_LOCAL(i->first))
475                         i->first->Write(message);
476         }
477 }
478
479 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
480 {
481         std::string textbuffer;
482         VAFORMAT(textbuffer, text, text);
483         this->WriteChannelWithServ(ServName, textbuffer);
484 }
485
486 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
487 {
488         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
489
490         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
491         {
492                 if (IS_LOCAL(i->first))
493                         i->first->Write(message);
494         }
495 }
496
497 /* write formatted text from a source user to all users on a channel except
498  * for the sender (for privmsg etc) */
499 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
500 {
501         std::string textbuffer;
502         VAFORMAT(textbuffer, text, text);
503         this->WriteAllExceptSender(user, serversource, status, textbuffer);
504 }
505
506 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
507 {
508         std::string textbuffer;
509         VAFORMAT(textbuffer, text, text);
510         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
511         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
512 }
513
514 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
515 {
516         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
517         this->RawWriteAllExcept(user, serversource, status, except_list, message);
518 }
519
520 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
521 {
522         unsigned int minrank = 0;
523         if (status)
524         {
525                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
526                 if (mh)
527                         minrank = mh->GetPrefixRank();
528         }
529         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
530         {
531                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
532                 {
533                         /* User doesn't have the status we're after */
534                         if (minrank && i->second->getRank() < minrank)
535                                 continue;
536
537                         i->first->Write(out);
538                 }
539         }
540 }
541
542 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
543 {
544         CUList except_list;
545         except_list.insert(user);
546         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
547 }
548
549 const char* Channel::ChanModes(bool showkey)
550 {
551         static std::string scratch;
552         std::string sparam;
553
554         scratch.clear();
555
556         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
557         for(int n = 0; n < 64; n++)
558         {
559                 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
560                 if (mh && IsModeSet(mh))
561                 {
562                         scratch.push_back(n + 65);
563
564                         ParamModeBase* pm = mh->IsParameterMode();
565                         if (!pm)
566                                 continue;
567
568                         if (n == 'k' - 65 && !showkey)
569                         {
570                                 sparam += " <key>";
571                         }
572                         else
573                         {
574                                 sparam += ' ';
575                                 pm->GetParameter(this, sparam);
576                         }
577                 }
578         }
579
580         scratch += sparam;
581         return scratch.c_str();
582 }
583
584 /* compile a userlist of a channel into a string, each nick seperated by
585  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
586  */
587 void Channel::UserList(User* user, bool has_user)
588 {
589         bool has_privs = user->HasPrivPermission("channels/auspex");
590         std::string list;
591         list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
592         list.push_back(' ');
593         list.append(this->name).append(" :");
594         std::string::size_type pos = list.size();
595
596         const size_t maxlen = ServerInstance->Config->Limits.MaxLine - 10 - ServerInstance->Config->ServerName.size();
597         std::string prefixlist;
598         std::string nick;
599         for (UserMembIter i = userlist.begin(); i != userlist.end(); ++i)
600         {
601                 if ((!has_user) && (i->first->IsModeSet(invisiblemode)) && (!has_privs))
602                 {
603                         /*
604                          * user is +i, and source not on the channel, does not show
605                          * nick in NAMES list
606                          */
607                         continue;
608                 }
609
610                 Membership* memb = i->second;
611
612                 prefixlist.clear();
613                 char prefix = memb->GetPrefixChar();
614                 if (prefix)
615                         prefixlist.push_back(prefix);
616                 nick = i->first->nick;
617
618                 ModResult res;
619                 FIRST_MOD_RESULT(OnNamesListItem, res, (user, memb, prefixlist, nick));
620
621                 // See if a module wants us to exclude this user from NAMES
622                 if (res == MOD_RES_DENY)
623                         continue;
624
625                 if (list.size() + prefixlist.length() + nick.length() + 1 > maxlen)
626                 {
627                         /* list overflowed into multiple numerics */
628                         user->WriteNumeric(RPL_NAMREPLY, list);
629
630                         // Erase all nicks, keep the constant part
631                         list.erase(pos);
632                 }
633
634                 list.append(prefixlist).append(nick).push_back(' ');
635         }
636
637         // Only send the user list numeric if there is at least one user in it
638         if (list.size() != pos)
639                 user->WriteNumeric(RPL_NAMREPLY, list);
640
641         user->WriteNumeric(RPL_ENDOFNAMES, "%s :End of /NAMES list.", this->name.c_str());
642 }
643
644 /* returns the status character for a given user on a channel, e.g. @ for op,
645  * % for halfop etc. If the user has several modes set, the highest mode
646  * the user has must be returned.
647  */
648 char Membership::GetPrefixChar() const
649 {
650         char pf = 0;
651         unsigned int bestrank = 0;
652
653         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
654         {
655                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
656                 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
657                 {
658                         bestrank = mh->GetPrefixRank();
659                         pf = mh->GetPrefix();
660                 }
661         }
662         return pf;
663 }
664
665 unsigned int Membership::getRank()
666 {
667         char mchar = modes.c_str()[0];
668         unsigned int rv = 0;
669         if (mchar)
670         {
671                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
672                 if (mh)
673                         rv = mh->GetPrefixRank();
674         }
675         return rv;
676 }
677
678 const char* Membership::GetAllPrefixChars() const
679 {
680         static char prefix[64];
681         int ctr = 0;
682
683         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
684         {
685                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
686                 if (mh && mh->GetPrefix())
687                         prefix[ctr++] = mh->GetPrefix();
688         }
689         prefix[ctr] = 0;
690
691         return prefix;
692 }
693
694 unsigned int Channel::GetPrefixValue(User* user)
695 {
696         UserMembIter m = userlist.find(user);
697         if (m == userlist.end())
698                 return 0;
699         return m->second->getRank();
700 }
701
702 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
703 {
704         char prefix = delta_mh->GetModeChar();
705         for (unsigned int i = 0; i < modes.length(); i++)
706         {
707                 char mchar = modes[i];
708                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
709                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
710                 {
711                         modes = modes.substr(0,i) +
712                                 (adding ? std::string(1, prefix) : "") +
713                                 modes.substr(mchar == prefix ? i+1 : i);
714                         return adding != (mchar == prefix);
715                 }
716         }
717         if (adding)
718                 modes.push_back(prefix);
719         return adding;
720 }
721
722 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
723 {
724         if ((timeout != 0) && (ServerInstance->Time() >= timeout))
725                 // Expired, don't bother
726                 return;
727
728         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
729
730         Invitation* inv = Invitation::Find(c, u, false);
731         if (inv)
732         {
733                  if ((inv->expiry == 0) || (inv->expiry > timeout))
734                         return;
735                 inv->expiry = timeout;
736                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
737         }
738         else
739         {
740                 inv = new Invitation(c, u, timeout);
741                 c->invites.push_front(inv);
742                 u->invites.push_front(inv);
743                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
744         }
745 }
746
747 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
748 {
749         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);
750
751         Invitation* result = NULL;
752         for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
753         {
754                 Invitation* inv = *i;
755                 ++i;
756
757                 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
758                 {
759                         /* Expired invite, remove it. */
760                         std::string expiration = InspIRCd::TimeString(inv->expiry);
761                         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
762                         delete inv;
763                 }
764                 else
765                 {
766                         /* Is it what we're searching for? */
767                         if (inv->chan == c)
768                         {
769                                 result = inv;
770                                 break;
771                         }
772                 }
773         }
774
775         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
776         return result;
777 }
778
779 Invitation::~Invitation()
780 {
781         // Remove this entry from both lists
782         chan->invites.erase(this);
783         user->invites.erase(this);
784         ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);
785 }