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