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