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