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