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