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