]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
9489e57baedc2e0cc93475fbba1952a0724c61a6
[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(InspIRCd* Instance, const std::string &cname, time_t ts) : ServerInstance(Instance)
21 {
22         chan_hash::iterator findchan = ServerInstance->chanlist->find(cname);
23         if (findchan != Instance->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(ServerInstance, 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", ServerInstance->Config->DefaultModes);
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(InspIRCd* Instance, 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() >= Instance->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, Instance->Config->Limits.ChanMax);
228         Ptr = Instance->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                                 Instance->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 = "@";
244                         created_by_local = true;
245                 }
246
247                 if (IS_LOCAL(user) && override == false)
248                 {
249                         ModResult MOD_RESULT;
250                         FIRST_MOD_RESULT(Instance, 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(Instance, 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(Instance, 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 = Instance->Config->InvBypassModes && invited;
280
281                                 if (!ckey.empty())
282                                 {
283                                         FIRST_MOD_RESULT(Instance, 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(Instance, 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(Instance, 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(Instance, Ptr, user, privs, bursting, created_by_local);
338 }
339
340 Channel* Channel::ForceChan(InspIRCd* Instance, 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 = Instance->Modes->FindPrefix(status);
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(Instance->FakeClient, Instance->FakeClient, Ptr, nick, true);
356                 }
357         }
358
359         CUList except_list;
360         FOREACH_MOD_I(Instance,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 = Instance->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(Instance,I_OnPostJoin,OnPostJoin(memb));
380         return Ptr;
381 }
382
383 bool Channel::IsBanned(User* user)
384 {
385         ModResult result;
386         DO_EACH_HOOK(ServerInstance, OnCheckBan, ModResult modresult, (user, this))
387         {
388                 result = result + modresult;
389         }
390         WHILE_EACH_HOOK(ServerInstance, OnCheckBan);
391
392         if (result != MOD_RES_PASSTHRU)
393                 return (result == MOD_RES_DENY);
394
395         char mask[MAXBUF];
396         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), user->GetIPString());
397         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
398         {
399                 if ((InspIRCd::Match(user->GetFullHost(),i->data, NULL)) || // host
400                         (InspIRCd::Match(user->GetFullRealHost(),i->data, NULL)) || // uncloaked host
401                         (InspIRCd::MatchCIDR(mask, i->data, NULL))) // ip
402                 {
403                         return true;
404                 }
405         }
406         return false;
407 }
408
409 ModResult Channel::GetExtBanStatus(const std::string &str, char type)
410 {
411         ModResult result;
412         DO_EACH_HOOK(ServerInstance, OnCheckStringExtBan, ModResult modresult, (str, this, type))
413         {
414                 result = result + modresult;
415         }
416         WHILE_EACH_HOOK(ServerInstance, OnCheckStringExtBan);
417
418         if (result != MOD_RES_PASSTHRU)
419                 return result;
420
421         // nobody decided for us, check the ban list
422         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
423         {
424                 if (i->data[0] != type || i->data[1] != ':')
425                         continue;
426
427                 std::string maskptr = i->data.substr(2);
428                 ServerInstance->Logs->Log("EXTBANS", DEBUG, "Checking %s against %s, type is %c", str.c_str(), maskptr.c_str(), type);
429
430                 if (InspIRCd::Match(str, maskptr, NULL))
431                         return MOD_RES_DENY;
432         }
433
434         return MOD_RES_PASSTHRU;
435 }
436
437 ModResult Channel::GetExtBanStatus(User *user, char type)
438 {
439         ModResult rv;
440         DO_EACH_HOOK(ServerInstance, OnCheckExtBan, ModResult modresult, (user, this, type))
441         {
442                 rv = rv + modresult;
443         }
444         WHILE_EACH_HOOK(ServerInstance, OnCheckExtBan);
445
446         if (rv != MOD_RES_PASSTHRU)
447                 return rv;
448
449         char mask[MAXBUF];
450         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), user->GetIPString());
451
452         rv = rv + this->GetExtBanStatus(mask, type);
453         rv = rv + this->GetExtBanStatus(user->GetFullHost(), type);
454         rv = rv + this->GetExtBanStatus(user->GetFullRealHost(), type);
455         return rv;
456 }
457
458 /* Channel::PartUser
459  * remove a channel from a users record, and return the number of users left.
460  * Therefore, if this function returns 0 the caller should delete the Channel.
461  */
462 long Channel::PartUser(User *user, std::string &reason)
463 {
464         if (!user)
465                 return this->GetUserCounter();
466
467         Membership* memb = GetUser(user);
468
469         if (memb)
470         {
471                 CUList except_list;
472                 FOREACH_MOD(I_OnUserPart,OnUserPart(memb, reason, except_list));
473
474                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
475
476                 user->chans.erase(this);
477                 this->RemoveAllPrefixes(user);
478         }
479
480         if (!this->DelUser(user)) /* if there are no users left on the channel... */
481         {
482                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
483                 /* kill the record */
484                 if (iter != ServerInstance->chanlist->end())
485                 {
486                         ModResult res;
487                         FIRST_MOD_RESULT(ServerInstance, OnChannelPreDelete, res, (this));
488                         if (res == MOD_RES_DENY)
489                                 return 1; // delete halted by module
490                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
491                         ServerInstance->chanlist->erase(iter);
492                 }
493                 return 0;
494         }
495
496         return this->GetUserCounter();
497 }
498
499 long Channel::ServerKickUser(User* user, const char* reason, const char* servername)
500 {
501         if (servername == NULL || *ServerInstance->Config->HideWhoisServer)
502                 servername = ServerInstance->Config->ServerName;
503
504         ServerInstance->FakeClient->server = servername;
505         return this->KickUser(ServerInstance->FakeClient, user, reason);
506 }
507
508 long Channel::KickUser(User *src, User *user, const char* reason)
509 {
510         if (!src || !user || !reason)
511                 return this->GetUserCounter();
512
513         Membership* memb = GetUser(user);
514         if (IS_LOCAL(src))
515         {
516                 if (!memb)
517                 {
518                         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());
519                         return this->GetUserCounter();
520                 }
521                 if ((ServerInstance->ULine(user->server)) && (!ServerInstance->ULine(src->server)))
522                 {
523                         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());
524                         return this->GetUserCounter();
525                 }
526
527                 ModResult res;
528                 if (ServerInstance->ULine(src->server))
529                         res = MOD_RES_ALLOW;
530                 else
531                         FIRST_MOD_RESULT(ServerInstance, OnUserPreKick, res, (src,memb,reason));
532
533                 if (res == MOD_RES_DENY)
534                         return this->GetUserCounter();
535
536                 if (res == MOD_RES_PASSTHRU)
537                 {
538                         int them = this->GetPrefixValue(src);
539                         int us = this->GetPrefixValue(user);
540                         if ((them < HALFOP_VALUE) || (them < us))
541                         {
542                                 src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator",src->nick.c_str(), this->name.c_str(), them >= HALFOP_VALUE ? "" : "half-");
543                                 return this->GetUserCounter();
544                         }
545                 }
546         }
547
548         if (memb)
549         {
550                 CUList except_list;
551                 FOREACH_MOD(I_OnUserKick,OnUserKick(src, memb, reason, except_list));
552
553                 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), user->nick.c_str(), reason);
554
555                 user->chans.erase(this);
556                 this->RemoveAllPrefixes(user);
557         }
558
559         if (!this->DelUser(user))
560         /* if there are no users left on the channel */
561         {
562                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name.c_str());
563
564                 /* kill the record */
565                 if (iter != ServerInstance->chanlist->end())
566                 {
567                         ModResult res;
568                         FIRST_MOD_RESULT(ServerInstance, OnChannelPreDelete, res, (this));
569                         if (res == MOD_RES_DENY)
570                                 return 1; // delete halted by module
571                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
572                         ServerInstance->chanlist->erase(iter);
573                 }
574                 return 0;
575         }
576
577         return this->GetUserCounter();
578 }
579
580 void Channel::WriteChannel(User* user, const char* text, ...)
581 {
582         char textbuffer[MAXBUF];
583         va_list argsPtr;
584
585         if (!user || !text)
586                 return;
587
588         va_start(argsPtr, text);
589         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
590         va_end(argsPtr);
591
592         this->WriteChannel(user, std::string(textbuffer));
593 }
594
595 void Channel::WriteChannel(User* user, const std::string &text)
596 {
597         char tb[MAXBUF];
598
599         if (!user)
600                 return;
601
602         snprintf(tb,MAXBUF,":%s %s", user->GetFullHost().c_str(), text.c_str());
603         std::string out = tb;
604
605         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
606         {
607                 if (IS_LOCAL(i->first))
608                         i->first->Write(out);
609         }
610 }
611
612 void Channel::WriteChannelWithServ(const char* ServName, const char* text, ...)
613 {
614         char textbuffer[MAXBUF];
615         va_list argsPtr;
616
617         if (!text)
618                 return;
619
620         va_start(argsPtr, text);
621         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
622         va_end(argsPtr);
623
624         this->WriteChannelWithServ(ServName, std::string(textbuffer));
625 }
626
627 void Channel::WriteChannelWithServ(const char* ServName, const std::string &text)
628 {
629         char tb[MAXBUF];
630
631         snprintf(tb,MAXBUF,":%s %s", ServName ? ServName : ServerInstance->Config->ServerName, text.c_str());
632         std::string out = tb;
633
634         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
635         {
636                 if (IS_LOCAL(i->first))
637                         i->first->Write(out);
638         }
639 }
640
641 /* write formatted text from a source user to all users on a channel except
642  * for the sender (for privmsg etc) */
643 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
644 {
645         char textbuffer[MAXBUF];
646         va_list argsPtr;
647
648         if (!text)
649                 return;
650
651         va_start(argsPtr, text);
652         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
653         va_end(argsPtr);
654
655         this->WriteAllExceptSender(user, serversource, status, std::string(textbuffer));
656 }
657
658 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
659 {
660         char textbuffer[MAXBUF];
661         va_list argsPtr;
662
663         if (!text)
664                 return;
665
666         int offset = snprintf(textbuffer,MAXBUF,":%s ", user->GetFullHost().c_str());
667
668         va_start(argsPtr, text);
669         vsnprintf(textbuffer + offset, MAXBUF - offset, text, argsPtr);
670         va_end(argsPtr);
671
672         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(textbuffer));
673 }
674
675 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
676 {
677         char tb[MAXBUF];
678
679         snprintf(tb,MAXBUF,":%s %s", serversource ? ServerInstance->Config->ServerName : user->GetFullHost().c_str(), text.c_str());
680         std::string out = tb;
681
682         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(tb));
683 }
684
685 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
686 {
687         char statmode = 0;
688         if (status)
689         {
690                 ModeHandler* mh = ServerInstance->Modes->FindPrefix(status);
691                 if (mh)
692                         statmode = mh->GetModeChar();
693         }
694         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
695         {
696                 if ((IS_LOCAL(i->first)) && (except_list.find(i->first) == except_list.end()))
697                 {
698                         /* User doesnt have the status we're after */
699                         if (statmode && !i->second->hasMode(statmode))
700                                 continue;
701
702                         i->first->Write(out);
703                 }
704         }
705 }
706
707 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
708 {
709         CUList except_list;
710         except_list.insert(user);
711         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
712 }
713
714 /*
715  * return a count of the users on a specific channel accounting for
716  * invisible users who won't increase the count. e.g. for /LIST
717  */
718 int Channel::CountInvisible()
719 {
720         int count = 0;
721         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
722         {
723                 if (!(i->first->IsModeSet('i')))
724                         count++;
725         }
726
727         return count;
728 }
729
730 char* Channel::ChanModes(bool showkey)
731 {
732         static char scratch[MAXBUF];
733         static char sparam[MAXBUF];
734         char* offset = scratch;
735         std::string extparam;
736
737         *scratch = '\0';
738         *sparam = '\0';
739
740         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
741         for(int n = 0; n < 64; n++)
742         {
743                 if(this->modes[n])
744                 {
745                         *offset++ = n + 65;
746                         extparam.clear();
747                         switch (n)
748                         {
749                                 case CM_KEY:
750                                         // Unfortunately this must be special-cased, as we definitely don't want to always display key.
751                                         if (showkey)
752                                         {
753                                                 extparam = this->GetModeParameter('k');
754                                         }
755                                         else
756                                         {
757                                                 extparam = "<key>";
758                                         }
759                                         break;
760                                 case CM_NOEXTERNAL:
761                                 case CM_TOPICLOCK:
762                                 case CM_INVITEONLY:
763                                 case CM_MODERATED:
764                                 case CM_SECRET:
765                                 case CM_PRIVATE:
766                                         /* We know these have no parameters */
767                                 break;
768                                 default:
769                                         extparam = this->GetModeParameter(n + 65);
770                                 break;
771                         }
772                         if (!extparam.empty())
773                         {
774                                 charlcat(sparam,' ',MAXBUF);
775                                 strlcat(sparam,extparam.c_str(),MAXBUF);
776                         }
777                 }
778         }
779
780         /* Null terminate scratch */
781         *offset = '\0';
782         strlcat(scratch,sparam,MAXBUF);
783         return scratch;
784 }
785
786 /* compile a userlist of a channel into a string, each nick seperated by
787  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
788  */
789 void Channel::UserList(User *user)
790 {
791         char list[MAXBUF];
792         size_t dlen, curlen;
793         ModResult call_modules;
794
795         if (!IS_LOCAL(user))
796                 return;
797
798         FIRST_MOD_RESULT(ServerInstance, OnUserList, call_modules, (user, this));
799
800         if (call_modules != MOD_RES_ALLOW)
801         {
802                 if ((this->IsModeSet('s')) && (!this->HasUser(user)))
803                 {
804                         user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
805                         return;
806                 }
807         }
808
809         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name.c_str());
810
811         int numusers = 0;
812         char* ptr = list + dlen;
813
814         /* Improvement by Brain - this doesnt change in value, so why was it inside
815          * the loop?
816          */
817         bool has_user = this->HasUser(user);
818
819         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
820         {
821                 if ((!has_user) && (i->first->IsModeSet('i')))
822                 {
823                         /*
824                          * user is +i, and source not on the channel, does not show
825                          * nick in NAMES list
826                          */
827                         continue;
828                 }
829
830                 std::string prefixlist = this->GetPrefixChar(i->first);
831                 std::string nick = i->first->nick;
832
833                 if (call_modules != MOD_RES_DENY)
834                 {
835                         FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->second, prefixlist, nick));
836
837                         /* Nick was nuked, a module wants us to skip it */
838                         if (nick.empty())
839                                 continue;
840                 }
841
842                 size_t ptrlen = 0;
843
844                 if (curlen + prefixlist.length() + nick.length() + 1 > 480)
845                 {
846                         /* list overflowed into multiple numerics */
847                         user->WriteNumeric(RPL_NAMREPLY, std::string(list));
848
849                         /* reset our lengths */
850                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name.c_str());
851                         ptr = list + dlen;
852
853                         ptrlen = 0;
854                         numusers = 0;
855                 }
856
857                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
858
859                 curlen += ptrlen;
860                 ptr += ptrlen;
861
862                 numusers++;
863         }
864
865         /* if whats left in the list isnt empty, send it */
866         if (numusers)
867         {
868                 user->WriteNumeric(RPL_NAMREPLY, std::string(list));
869         }
870
871         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
872 }
873
874 long Channel::GetMaxBans()
875 {
876         /* Return the cached value if there is one */
877         if (this->maxbans)
878                 return this->maxbans;
879
880         /* If there isnt one, we have to do some O(n) hax to find it the first time. (ick) */
881         for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
882         {
883                 if (InspIRCd::Match(this->name, n->first, NULL))
884                 {
885                         this->maxbans = n->second;
886                         return n->second;
887                 }
888         }
889
890         /* Screw it, just return the default of 64 */
891         this->maxbans = 64;
892         return this->maxbans;
893 }
894
895 void Channel::ResetMaxBans()
896 {
897         this->maxbans = 0;
898 }
899
900 /* returns the status character for a given user on a channel, e.g. @ for op,
901  * % for halfop etc. If the user has several modes set, the highest mode
902  * the user has must be returned.
903  */
904 const char* Channel::GetPrefixChar(User *user)
905 {
906         static char pf[2] = {0, 0};
907         *pf = 0;
908         unsigned int bestrank = 0;
909
910         UserMembIter m = userlist.find(user);
911         if (m != userlist.end())
912         {
913                 for(unsigned int i=0; i < m->second->modes.length(); i++)
914                 {
915                         char mchar = m->second->modes[i];
916                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
917                         if (mh && mh->GetPrefixRank() > bestrank)
918                         {
919                                 bestrank = mh->GetPrefixRank();
920                                 pf[0] = mh->GetPrefix();
921                         }
922                 }
923         }
924         return pf;
925 }
926
927 unsigned int Membership::getRank()
928 {
929         char mchar = modes.c_str()[0];
930         unsigned int rv = 0;
931         if (mchar)
932         {
933                 ModeHandler* mh = chan->ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
934                 if (mh)
935                         rv = mh->GetPrefixRank();
936         }
937         return rv;
938 }
939
940 const char* Channel::GetAllPrefixChars(User* user)
941 {
942         static char prefix[64];
943         int ctr = 0;
944
945         UserMembIter m = userlist.find(user);
946         if (m != userlist.end())
947         {
948                 for(unsigned int i=0; i < m->second->modes.length(); i++)
949                 {
950                         char mchar = m->second->modes[i];
951                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
952                         if (mh && mh->GetPrefix())
953                                 prefix[ctr++] = mh->GetPrefix();
954                 }
955         }
956         prefix[ctr] = 0;
957
958         return prefix;
959 }
960
961 unsigned int Channel::GetPrefixValue(User* user)
962 {
963         unsigned int bestrank = 0;
964
965         UserMembIter m = userlist.find(user);
966         if (m != userlist.end())
967         {
968                 for(unsigned int i=0; i < m->second->modes.length(); i++)
969                 {
970                         char mchar = m->second->modes[i];
971                         ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
972                         if (mh && mh->GetPrefixRank() > bestrank)
973                                 bestrank = mh->GetPrefixRank();
974                 }
975         }
976         return bestrank;
977 }
978
979 void Channel::SetPrefix(User* user, char prefix, bool adding)
980 {
981         ModeHandler* delta_mh = ServerInstance->Modes->FindMode(prefix, MODETYPE_CHANNEL);
982         if (!delta_mh)
983                 return;
984         UserMembIter m = userlist.find(user);
985         if (m == userlist.end())
986                 return;
987         for(unsigned int i=0; i < m->second->modes.length(); i++)
988         {
989                 char mchar = m->second->modes[i];
990                 ModeHandler* mh = ServerInstance->Modes->FindMode(mchar, MODETYPE_CHANNEL);
991                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
992                 {
993                         m->second->modes =
994                                 m->second->modes.substr(0,i) +
995                                 (adding ? std::string(1, prefix) : "") +
996                                 m->second->modes.substr(mchar == prefix ? i+1 : i);
997                         return;
998                 }
999         }
1000         if (adding)
1001                 m->second->modes += std::string(1, prefix);
1002 }
1003
1004 void Channel::RemoveAllPrefixes(User* user)
1005 {
1006         UserMembIter m = userlist.find(user);
1007         if (m != userlist.end())
1008         {
1009                 m->second->modes.clear();
1010         }
1011 }