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