]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
b53f780e66e452874e0e6d658387e606871b55b3
[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 && IS_LOCAL(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, OnLocalTopicChange, 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->GetStatus(u) < STATUS_HOP))
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         if (u && IS_LOCAL(u))
108         {
109                 FOREACH_MOD(I_OnPostLocalTopicChange,OnPostLocalTopicChange(u, this, this->topic));
110         }
111
112         return CMD_SUCCESS;
113 }
114
115 long Channel::GetUserCounter()
116 {
117         return (this->internal_userlist.size());
118 }
119
120 void Channel::AddUser(User* user)
121 {
122         internal_userlist[user] = user->nick;
123 }
124
125 unsigned long Channel::DelUser(User* user)
126 {
127         CUListIter a = internal_userlist.find(user);
128
129         if (a != internal_userlist.end())
130         {
131                 internal_userlist.erase(a);
132                 /* And tidy any others... */
133                 DelOppedUser(user);
134                 DelHalfoppedUser(user);
135                 DelVoicedUser(user);
136         }
137
138         return internal_userlist.size();
139 }
140
141 bool Channel::HasUser(User* user)
142 {
143         return (internal_userlist.find(user) != internal_userlist.end());
144 }
145
146 void Channel::AddOppedUser(User* user)
147 {
148         internal_op_userlist[user] = user->nick;
149 }
150
151 void Channel::DelOppedUser(User* user)
152 {
153         CUListIter a = internal_op_userlist.find(user);
154         if (a != internal_op_userlist.end())
155         {
156                 internal_op_userlist.erase(a);
157                 return;
158         }
159 }
160
161 void Channel::AddHalfoppedUser(User* user)
162 {
163         internal_halfop_userlist[user] = user->nick;
164 }
165
166 void Channel::DelHalfoppedUser(User* user)
167 {
168         CUListIter a = internal_halfop_userlist.find(user);
169
170         if (a != internal_halfop_userlist.end())
171         {
172                 internal_halfop_userlist.erase(a);
173         }
174 }
175
176 void Channel::AddVoicedUser(User* user)
177 {
178         internal_voice_userlist[user] = user->nick;
179 }
180
181 void Channel::DelVoicedUser(User* user)
182 {
183         CUListIter a = internal_voice_userlist.find(user);
184
185         if (a != internal_voice_userlist.end())
186         {
187                 internal_voice_userlist.erase(a);
188         }
189 }
190
191 CUList* Channel::GetUsers()
192 {
193         return &internal_userlist;
194 }
195
196 CUList* Channel::GetOppedUsers()
197 {
198         return &internal_op_userlist;
199 }
200
201 CUList* Channel::GetHalfoppedUsers()
202 {
203         return &internal_halfop_userlist;
204 }
205
206 CUList* Channel::GetVoicedUsers()
207 {
208         return &internal_voice_userlist;
209 }
210
211 void Channel::SetDefaultModes()
212 {
213         ServerInstance->Logs->Log("CHANNELS", DEBUG, "SetDefaultModes %s", ServerInstance->Config->DefaultModes);
214         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
215         std::string modeseq;
216         std::string parameter;
217
218         list.GetToken(modeseq);
219
220         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
221         {
222                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
223                 if (mode)
224                 {
225                         if (mode->GetNumParams(true))
226                                 list.GetToken(parameter);
227                         else
228                                 parameter.clear();
229
230                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
231                 }
232         }
233 }
234
235 /*
236  * add a channel to a user, creating the record for it if needed and linking
237  * it to the user record
238  */
239 Channel* Channel::JoinUser(InspIRCd* Instance, User *user, const char* cn, bool override, const char* key, bool bursting, time_t TS)
240 {
241         // Fix: unregistered users could be joined using /SAJOIN
242         if (!user || !cn || user->registered != REG_ALL)
243                 return NULL;
244
245         char cname[MAXBUF];
246         std::string privs;
247         Channel *Ptr;
248
249         /*
250          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
251          * We restrict local users to MaxChans channels.
252          * We restrict local operators to OperMaxChans channels.
253          * This is a lot more logical than how it was formerly. -- w00t
254          */
255         if (IS_LOCAL(user) && !override)
256         {
257                 // Checking MyClass exists because we *may* get here with NULL, not 100% sure.
258                 if (user->MyClass && user->MyClass->maxchans)
259                 {
260                         if (user->HasPrivPermission("channels/high-join-limit"))
261                         {
262                                 if (user->chans.size() >= Instance->Config->OperMaxChans)
263                                 {
264                                         user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cn);
265                                         return NULL;
266                                 }
267                         }
268                         else
269                         {
270                                 if (user->chans.size() >= user->MyClass->maxchans)
271                                 {
272                                         user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s %s :You are on too many channels",user->nick.c_str(), cn);
273                                         return NULL;
274                                 }
275                         }
276                 }
277         }
278
279         strlcpy(cname, cn, Instance->Config->Limits.ChanMax);
280         Ptr = Instance->FindChan(cname);
281         bool created_by_local = false;
282
283         if (!Ptr)
284         {
285                 /*
286                  * Fix: desync bug was here, don't set @ on remote users - spanningtree handles their permissions. bug #358. -- w00t
287                  */
288                 if (!IS_LOCAL(user))
289                 {
290                         if (!TS)
291                                 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);
292                 }
293                 else
294                 {
295                         privs = "@";
296                         created_by_local = true;
297                 }
298
299                 if (IS_LOCAL(user) && override == false)
300                 {
301                         ModResult MOD_RESULT;
302                         FIRST_MOD_RESULT(Instance, OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key ? key : ""));
303                         if (MOD_RESULT == MOD_RES_DENY)
304                                 return NULL;
305                 }
306
307                 Ptr = new Channel(Instance, cname, TS);
308         }
309         else
310         {
311                 /* Already on the channel */
312                 if (Ptr->HasUser(user))
313                         return NULL;
314
315                 /*
316                  * remote users are allowed us to bypass channel modes
317                  * and bans (used by servers)
318                  */
319                 if (IS_LOCAL(user) && override == false)
320                 {
321                         ModResult MOD_RESULT;
322                         FIRST_MOD_RESULT(Instance, OnUserPreJoin, MOD_RESULT, (user, Ptr, cname, privs, key ? key : ""));
323                         if (MOD_RESULT == MOD_RES_DENY)
324                         {
325                                 return NULL;
326                         }
327                         else if (MOD_RESULT == MOD_RES_PASSTHRU)
328                         {
329                                 std::string ckey = Ptr->GetModeParameter('k');
330                                 bool invited = user->IsInvited(Ptr->name.c_str());
331                                 bool can_bypass = Instance->Config->InvBypassModes && invited;
332
333                                 if (!ckey.empty())
334                                 {
335                                         FIRST_MOD_RESULT(Instance, OnCheckKey, MOD_RESULT, (user, Ptr, key ? key : ""));
336                                         if (!MOD_RESULT.check((key && ckey == key) || can_bypass))
337                                         {
338                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
339                                                 user->WriteNumeric(ERR_BADCHANNELKEY, "%s %s :Cannot join channel (Incorrect channel key)",user->nick.c_str(), Ptr->name.c_str());
340                                                 return NULL;
341                                         }
342                                 }
343
344                                 if (Ptr->IsModeSet('i'))
345                                 {
346                                         FIRST_MOD_RESULT(Instance, OnCheckInvite, MOD_RESULT, (user, Ptr));
347                                         if (!MOD_RESULT.check(invited))
348                                         {
349                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s %s :Cannot join channel (Invite only)",user->nick.c_str(), Ptr->name.c_str());
350                                                 return NULL;
351                                         }
352                                 }
353
354                                 std::string limit = Ptr->GetModeParameter('l');
355                                 if (!limit.empty())
356                                 {
357                                         FIRST_MOD_RESULT(Instance, OnCheckLimit, MOD_RESULT, (user, Ptr));
358                                         if (!MOD_RESULT.check((Ptr->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
359                                         {
360                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s %s :Cannot join channel (Channel is full)",user->nick.c_str(), Ptr->name.c_str());
361                                                 return NULL;
362                                         }
363                                 }
364
365                                 if (Ptr->IsBanned(user) && !can_bypass)
366                                 {
367                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s %s :Cannot join channel (You're banned)",user->nick.c_str(), Ptr->name.c_str());
368                                         return NULL;
369                                 }
370
371                                 /*
372                                  * If the user has invites for this channel, remove them now
373                                  * after a successful join so they don't build up.
374                                  */
375                                 if (invited)
376                                 {
377                                         user->RemoveInvite(Ptr->name.c_str());
378                                 }
379                         }
380                 }
381         }
382
383         if (created_by_local)
384         {
385                 /* As spotted by jilles, dont bother to set this on remote users */
386                 Ptr->SetDefaultModes();
387         }
388
389         return Channel::ForceChan(Instance, Ptr, user, privs, bursting, created_by_local);
390 }
391
392 Channel* Channel::ForceChan(InspIRCd* Instance, Channel* Ptr, User* user, const std::string &privs, bool bursting, bool created)
393 {
394         std::string nick = user->nick;
395         bool silent = false;
396
397         Ptr->AddUser(user);
398
399         /* Just in case they have no permissions */
400         user->chans[Ptr] = 0;
401
402         for (std::string::const_iterator x = privs.begin(); x != privs.end(); x++)
403         {
404                 const char status = *x;
405                 ModeHandler* mh = Instance->Modes->FindPrefix(status);
406                 if (mh)
407                 {
408                         /* Set, and make sure that the mode handler knows this mode was now set */
409                         Ptr->SetPrefix(user, status, mh->GetPrefixRank(), true);
410                         mh->OnModeChange(Instance->FakeClient, Instance->FakeClient, Ptr, nick, true);
411
412                         switch (mh->GetPrefix())
413                         {
414                                 /* These logic ops are SAFE IN THIS CASE because if the entry doesnt exist,
415                                  * addressing operator[] creates it. If they do exist, it points to it.
416                                  * At all other times where we dont want to create an item if it doesnt exist, we
417                                  * must stick to ::find().
418                                  */
419                                 case '@':
420                                         user->chans[Ptr] |= UCMODE_OP;
421                                 break;
422                                 case '%':
423                                         user->chans[Ptr] |= UCMODE_HOP;
424                                 break;
425                                 case '+':
426                                         user->chans[Ptr] |= UCMODE_VOICE;
427                                 break;
428                         }
429                 }
430         }
431
432         FOREACH_MOD_I(Instance,I_OnUserJoin,OnUserJoin(user, Ptr, bursting, silent, created));
433
434         if (!silent)
435                 Ptr->WriteChannel(user,"JOIN :%s",Ptr->name.c_str());
436
437         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
438         std::string ms = Instance->Modes->ModeString(user, Ptr);
439         if ((Ptr->GetUserCounter() > 1) && (ms.length()))
440                 Ptr->WriteAllExceptSender(user, true, 0, "MODE %s +%s", Ptr->name.c_str(), ms.c_str());
441
442         /* Major improvement by Brain - we dont need to be calculating all this pointlessly for remote users */
443         if (IS_LOCAL(user))
444         {
445                 if (Ptr->topicset)
446                 {
447                         user->WriteNumeric(RPL_TOPIC, "%s %s :%s", user->nick.c_str(), Ptr->name.c_str(), Ptr->topic.c_str());
448                         user->WriteNumeric(RPL_TOPICTIME, "%s %s %s %lu", user->nick.c_str(), Ptr->name.c_str(), Ptr->setby.c_str(), (unsigned long)Ptr->topicset);
449                 }
450                 Ptr->UserList(user);
451         }
452         FOREACH_MOD_I(Instance,I_OnPostJoin,OnPostJoin(user, Ptr));
453         return Ptr;
454 }
455
456 bool Channel::IsBanned(User* user)
457 {
458         ModResult result;
459         DO_EACH_HOOK(ServerInstance, OnCheckBan, ModResult modresult, (user, this))
460         {
461                 result = result + modresult;
462         }
463         WHILE_EACH_HOOK(ServerInstance, OnCheckBan);
464
465         if (result != MOD_RES_PASSTHRU)
466                 return (result == MOD_RES_DENY);
467
468         char mask[MAXBUF];
469         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), user->GetIPString());
470         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
471         {
472                 if ((InspIRCd::Match(user->GetFullHost(),i->data, NULL)) || // host
473                         (InspIRCd::Match(user->GetFullRealHost(),i->data, NULL)) || // uncloaked host
474                         (InspIRCd::MatchCIDR(mask, i->data, NULL))) // ip
475                 {
476                         return true;
477                 }
478         }
479         return false;
480 }
481
482 ModResult Channel::GetExtBanStatus(const std::string &str, char type)
483 {
484         ModResult result;
485         DO_EACH_HOOK(ServerInstance, OnCheckStringExtBan, ModResult modresult, (str, this, type))
486         {
487                 result = result + modresult;
488         }
489         WHILE_EACH_HOOK(ServerInstance, OnCheckStringExtBan);
490
491         if (result != MOD_RES_PASSTHRU)
492                 return result;
493
494         // nobody decided for us, check the ban list
495         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
496         {
497                 if (i->data[0] != type || i->data[1] != ':')
498                         continue;
499
500                 std::string maskptr = i->data.substr(2);
501                 ServerInstance->Logs->Log("EXTBANS", DEBUG, "Checking %s against %s, type is %c", str.c_str(), maskptr.c_str(), type);
502
503                 if (InspIRCd::Match(str, maskptr, NULL))
504                         return MOD_RES_DENY;
505         }
506
507         return MOD_RES_PASSTHRU;
508 }
509
510 ModResult Channel::GetExtBanStatus(User *user, char type)
511 {
512         ModResult rv;
513         DO_EACH_HOOK(ServerInstance, OnCheckExtBan, ModResult modresult, (user, this, type))
514         {
515                 rv = rv + modresult;
516         }
517         WHILE_EACH_HOOK(ServerInstance, OnCheckExtBan);
518
519         if (rv != MOD_RES_PASSTHRU)
520                 return rv;
521
522         char mask[MAXBUF];
523         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), user->GetIPString());
524
525         rv = rv + this->GetExtBanStatus(mask, type);
526         rv = rv + this->GetExtBanStatus(user->GetFullHost(), type);
527         rv = rv + this->GetExtBanStatus(user->GetFullRealHost(), type);
528         return rv;
529 }
530
531 /* Channel::PartUser
532  * remove a channel from a users record, and return the number of users left.
533  * Therefore, if this function returns 0 the caller should delete the Channel.
534  */
535 long Channel::PartUser(User *user, std::string &reason)
536 {
537         bool silent = false;
538
539         if (!user)
540                 return this->GetUserCounter();
541
542         UCListIter i = user->chans.find(this);
543         if (i != user->chans.end())
544         {
545                 FOREACH_MOD(I_OnUserPart,OnUserPart(user, this, reason, silent));
546
547                 if (!silent)
548                         this->WriteChannel(user, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
549
550                 user->chans.erase(i);
551                 this->RemoveAllPrefixes(user);
552         }
553
554         if (!this->DelUser(user)) /* if there are no users left on the channel... */
555         {
556                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
557                 /* kill the record */
558                 if (iter != ServerInstance->chanlist->end())
559                 {
560                         ModResult res;
561                         FIRST_MOD_RESULT(ServerInstance, OnChannelPreDelete, res, (this));
562                         if (res == MOD_RES_DENY)
563                                 return 1; // delete halted by module
564                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
565                         ServerInstance->chanlist->erase(iter);
566                 }
567                 return 0;
568         }
569
570         return this->GetUserCounter();
571 }
572
573 long Channel::ServerKickUser(User* user, const char* reason, const char* servername)
574 {
575         if (servername == NULL || *ServerInstance->Config->HideWhoisServer)
576                 servername = ServerInstance->Config->ServerName;
577
578         ServerInstance->FakeClient->server = servername;
579         return this->KickUser(ServerInstance->FakeClient, user, reason);
580 }
581
582 long Channel::KickUser(User *src, User *user, const char* reason)
583 {
584         bool silent = false;
585
586         if (!src || !user || !reason)
587                 return this->GetUserCounter();
588
589         if (IS_LOCAL(src))
590         {
591                 if (!this->HasUser(user))
592                 {
593                         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());
594                         return this->GetUserCounter();
595                 }
596                 if ((ServerInstance->ULine(user->server)) && (!ServerInstance->ULine(src->server)))
597                 {
598                         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());
599                         return this->GetUserCounter();
600                 }
601
602                 ModResult res;
603                 if (ServerInstance->ULine(src->server))
604                         res = MOD_RES_ALLOW;
605                 if (res == MOD_RES_PASSTHRU)
606                         FIRST_MOD_RESULT(ServerInstance, OnUserPreKick, res, (src,user,this,reason));
607                 if (res == MOD_RES_PASSTHRU)
608                         FIRST_MOD_RESULT(ServerInstance, OnAccessCheck, res, (src,user,this,AC_KICK));
609
610                 if (res == MOD_RES_DENY)
611                         return this->GetUserCounter();
612
613                 if (res == MOD_RES_PASSTHRU)
614                 {
615                         int them = this->GetStatus(src);
616                         int us = this->GetStatus(user);
617                         if ((them < STATUS_HOP) || (them < us))
618                         {
619                                 src->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator",src->nick.c_str(), this->name.c_str(), them == STATUS_HOP ? "" : "half-");
620                                 return this->GetUserCounter();
621                         }
622                 }
623         }
624
625         FOREACH_MOD(I_OnUserKick,OnUserKick(src, user, this, reason, silent));
626
627         UCListIter i = user->chans.find(this);
628         if (i != user->chans.end())
629         {
630                 /* zap it from the channel list of the user */
631                 if (!silent)
632                         this->WriteChannel(src, "KICK %s %s :%s", this->name.c_str(), user->nick.c_str(), reason);
633
634                 user->chans.erase(i);
635                 this->RemoveAllPrefixes(user);
636         }
637
638         if (!this->DelUser(user))
639         /* if there are no users left on the channel */
640         {
641                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name.c_str());
642
643                 /* kill the record */
644                 if (iter != ServerInstance->chanlist->end())
645                 {
646                         ModResult res;
647                         FIRST_MOD_RESULT(ServerInstance, OnChannelPreDelete, res, (this));
648                         if (res == MOD_RES_DENY)
649                                 return 1; // delete halted by module
650                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
651                         ServerInstance->chanlist->erase(iter);
652                 }
653                 return 0;
654         }
655
656         return this->GetUserCounter();
657 }
658
659 void Channel::WriteChannel(User* user, const char* text, ...)
660 {
661         char textbuffer[MAXBUF];
662         va_list argsPtr;
663
664         if (!user || !text)
665                 return;
666
667         va_start(argsPtr, text);
668         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
669         va_end(argsPtr);
670
671         this->WriteChannel(user, std::string(textbuffer));
672 }
673
674 void Channel::WriteChannel(User* user, const std::string &text)
675 {
676         CUList *ulist = this->GetUsers();
677         char tb[MAXBUF];
678
679         if (!user)
680                 return;
681
682         snprintf(tb,MAXBUF,":%s %s", user->GetFullHost().c_str(), text.c_str());
683         std::string out = tb;
684
685         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
686         {
687                 if (IS_LOCAL(i->first))
688                         i->first->Write(out);
689         }
690 }
691
692 void Channel::WriteChannelWithServ(const char* ServName, const char* text, ...)
693 {
694         char textbuffer[MAXBUF];
695         va_list argsPtr;
696
697         if (!text)
698                 return;
699
700         va_start(argsPtr, text);
701         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
702         va_end(argsPtr);
703
704         this->WriteChannelWithServ(ServName, std::string(textbuffer));
705 }
706
707 void Channel::WriteChannelWithServ(const char* ServName, const std::string &text)
708 {
709         CUList *ulist = this->GetUsers();
710         char tb[MAXBUF];
711
712         snprintf(tb,MAXBUF,":%s %s", ServName ? ServName : ServerInstance->Config->ServerName, text.c_str());
713         std::string out = tb;
714
715         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
716         {
717                 if (IS_LOCAL(i->first))
718                         i->first->Write(out);
719         }
720 }
721
722 /* write formatted text from a source user to all users on a channel except
723  * for the sender (for privmsg etc) */
724 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
725 {
726         char textbuffer[MAXBUF];
727         va_list argsPtr;
728
729         if (!text)
730                 return;
731
732         va_start(argsPtr, text);
733         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
734         va_end(argsPtr);
735
736         this->WriteAllExceptSender(user, serversource, status, std::string(textbuffer));
737 }
738
739 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
740 {
741         char textbuffer[MAXBUF];
742         va_list argsPtr;
743
744         if (!text)
745                 return;
746
747         int offset = snprintf(textbuffer,MAXBUF,":%s ", user->GetFullHost().c_str());
748
749         va_start(argsPtr, text);
750         vsnprintf(textbuffer + offset, MAXBUF - offset, text, argsPtr);
751         va_end(argsPtr);
752
753         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(textbuffer));
754 }
755
756 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
757 {
758         char tb[MAXBUF];
759
760         snprintf(tb,MAXBUF,":%s %s", serversource ? ServerInstance->Config->ServerName : user->GetFullHost().c_str(), text.c_str());
761         std::string out = tb;
762
763         this->RawWriteAllExcept(user, serversource, status, except_list, std::string(tb));
764 }
765
766 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
767 {
768         CUList *ulist = this->GetUsers();
769         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
770         {
771                 if ((IS_LOCAL(i->first)) && (except_list.find(i->first) == except_list.end()))
772                 {
773                         /* User doesnt have the status we're after */
774                         if (status && !strchr(this->GetAllPrefixChars(i->first), status))
775                                 continue;
776
777                         i->first->Write(out);
778                 }
779         }
780 }
781
782 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
783 {
784         CUList except_list;
785         except_list[user] = user->nick;
786         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
787 }
788
789 /*
790  * return a count of the users on a specific channel accounting for
791  * invisible users who won't increase the count. e.g. for /LIST
792  */
793 int Channel::CountInvisible()
794 {
795         int count = 0;
796         CUList *ulist= this->GetUsers();
797         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
798         {
799                 if (!(i->first->IsModeSet('i')))
800                         count++;
801         }
802
803         return count;
804 }
805
806 char* Channel::ChanModes(bool showkey)
807 {
808         static char scratch[MAXBUF];
809         static char sparam[MAXBUF];
810         char* offset = scratch;
811         std::string extparam;
812
813         *scratch = '\0';
814         *sparam = '\0';
815
816         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
817         for(int n = 0; n < 64; n++)
818         {
819                 if(this->modes[n])
820                 {
821                         *offset++ = n + 65;
822                         extparam.clear();
823                         switch (n)
824                         {
825                                 case CM_KEY:
826                                         // Unfortunately this must be special-cased, as we definitely don't want to always display key.
827                                         if (showkey)
828                                         {
829                                                 extparam = this->GetModeParameter('k');
830                                         }
831                                         else
832                                         {
833                                                 extparam = "<key>";
834                                         }
835                                         break;
836                                 case CM_NOEXTERNAL:
837                                 case CM_TOPICLOCK:
838                                 case CM_INVITEONLY:
839                                 case CM_MODERATED:
840                                 case CM_SECRET:
841                                 case CM_PRIVATE:
842                                         /* We know these have no parameters */
843                                 break;
844                                 default:
845                                         extparam = this->GetModeParameter(n + 65);
846                                 break;
847                         }
848                         if (!extparam.empty())
849                         {
850                                 charlcat(sparam,' ',MAXBUF);
851                                 strlcat(sparam,extparam.c_str(),MAXBUF);
852                         }
853                 }
854         }
855
856         /* Null terminate scratch */
857         *offset = '\0';
858         strlcat(scratch,sparam,MAXBUF);
859         return scratch;
860 }
861
862 /* compile a userlist of a channel into a string, each nick seperated by
863  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
864  */
865 void Channel::UserList(User *user, CUList *ulist)
866 {
867         char list[MAXBUF];
868         size_t dlen, curlen;
869         ModResult call_modules;
870
871         if (!IS_LOCAL(user))
872                 return;
873
874         FIRST_MOD_RESULT(ServerInstance, OnUserList, call_modules, (user, this, ulist));
875
876         if (call_modules != MOD_RES_ALLOW)
877         {
878                 if ((this->IsModeSet('s')) && (!this->HasUser(user)))
879                 {
880                         user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel",user->nick.c_str(), this->name.c_str());
881                         return;
882                 }
883         }
884
885         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name.c_str());
886
887         int numusers = 0;
888         char* ptr = list + dlen;
889
890         if (!ulist)
891                 ulist = this->GetUsers();
892
893         /* Improvement by Brain - this doesnt change in value, so why was it inside
894          * the loop?
895          */
896         bool has_user = this->HasUser(user);
897
898         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
899         {
900                 if ((!has_user) && (i->first->IsModeSet('i')))
901                 {
902                         /*
903                          * user is +i, and source not on the channel, does not show
904                          * nick in NAMES list
905                          */
906                         continue;
907                 }
908
909                 std::string prefixlist = this->GetPrefixChar(i->first);
910                 std::string nick = i->first->nick;
911
912                 if (call_modules != MOD_RES_DENY)
913                 {
914                         FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->first, this, prefixlist, nick));
915
916                         /* Nick was nuked, a module wants us to skip it */
917                         if (nick.empty())
918                                 continue;
919                 }
920
921                 size_t ptrlen = 0;
922
923                 if (curlen + prefixlist.length() + nick.length() + 1 > 480)
924                 {
925                         /* list overflowed into multiple numerics */
926                         user->WriteNumeric(RPL_NAMREPLY, std::string(list));
927
928                         /* reset our lengths */
929                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick.c_str(), this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name.c_str());
930                         ptr = list + dlen;
931
932                         ptrlen = 0;
933                         numusers = 0;
934                 }
935
936                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
937
938                 curlen += ptrlen;
939                 ptr += ptrlen;
940
941                 numusers++;
942         }
943
944         /* if whats left in the list isnt empty, send it */
945         if (numusers)
946         {
947                 user->WriteNumeric(RPL_NAMREPLY, std::string(list));
948         }
949
950         user->WriteNumeric(RPL_ENDOFNAMES, "%s %s :End of /NAMES list.", user->nick.c_str(), this->name.c_str());
951 }
952
953 long Channel::GetMaxBans()
954 {
955         /* Return the cached value if there is one */
956         if (this->maxbans)
957                 return this->maxbans;
958
959         /* If there isnt one, we have to do some O(n) hax to find it the first time. (ick) */
960         for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
961         {
962                 if (InspIRCd::Match(this->name, n->first, NULL))
963                 {
964                         this->maxbans = n->second;
965                         return n->second;
966                 }
967         }
968
969         /* Screw it, just return the default of 64 */
970         this->maxbans = 64;
971         return this->maxbans;
972 }
973
974 void Channel::ResetMaxBans()
975 {
976         this->maxbans = 0;
977 }
978
979 /* returns the status character for a given user on a channel, e.g. @ for op,
980  * % for halfop etc. If the user has several modes set, the highest mode
981  * the user has must be returned.
982  */
983 const char* Channel::GetPrefixChar(User *user)
984 {
985         static char pf[2] = {0, 0};
986
987         prefixlist::iterator n = prefixes.find(user);
988         if (n != prefixes.end())
989         {
990                 if (n->second.size())
991                 {
992                         /* If the user has any prefixes, their highest prefix
993                          * will always be at the head of the list, as the list is
994                          * sorted in rank order highest first (see SetPrefix()
995                          * for reasons why)
996                          */
997                         *pf = n->second.begin()->first;
998                         return pf;
999                 }
1000         }
1001
1002         *pf = 0;
1003         return pf;
1004 }
1005
1006
1007 const char* Channel::GetAllPrefixChars(User* user)
1008 {
1009         static char prefix[MAXBUF];
1010         int ctr = 0;
1011         *prefix = 0;
1012
1013         prefixlist::iterator n = prefixes.find(user);
1014         if (n != prefixes.end())
1015         {
1016                 for (std::vector<prefixtype>::iterator x = n->second.begin(); x != n->second.end(); x++)
1017                 {
1018                         prefix[ctr++] = x->first;
1019                 }
1020         }
1021
1022         prefix[ctr] = 0;
1023
1024         return prefix;
1025 }
1026
1027 unsigned int Channel::GetPrefixValue(User* user)
1028 {
1029         prefixlist::iterator n = prefixes.find(user);
1030         if (n != prefixes.end())
1031         {
1032                 if (n->second.size())
1033                         return n->second.begin()->second;
1034         }
1035         return 0;
1036 }
1037
1038 int Channel::GetStatusFlags(User *user)
1039 {
1040         UCListIter i = user->chans.find(this);
1041         if (i != user->chans.end())
1042         {
1043                 return i->second;
1044         }
1045         return 0;
1046 }
1047
1048 int Channel::GetStatus(User *user)
1049 {
1050         if (ServerInstance->ULine(user->server))
1051                 return STATUS_OP;
1052
1053         UCListIter i = user->chans.find(this);
1054         if (i != user->chans.end())
1055         {
1056                 if ((i->second & UCMODE_OP) > 0)
1057                 {
1058                         return STATUS_OP;
1059                 }
1060                 if ((i->second & UCMODE_HOP) > 0)
1061                 {
1062                         return STATUS_HOP;
1063                 }
1064                 if ((i->second & UCMODE_VOICE) > 0)
1065                 {
1066                         return STATUS_VOICE;
1067                 }
1068                 return STATUS_NORMAL;
1069         }
1070         return STATUS_NORMAL;
1071 }
1072
1073 void Channel::SetPrefix(User* user, char prefix, unsigned int prefix_value, bool adding)
1074 {
1075         prefixlist::iterator n = prefixes.find(user);
1076         prefixtype pfx = std::make_pair(prefix,prefix_value);
1077         if (adding)
1078         {
1079                 if (n != prefixes.end())
1080                 {
1081                         if (std::find(n->second.begin(), n->second.end(), pfx) == n->second.end())
1082                         {
1083                                 n->second.push_back(pfx);
1084                                 /* We must keep prefixes in rank order, largest first.
1085                                  * This is for two reasons, firstly because x-chat *ass-u-me's* this
1086                                  * state, and secondly it turns out to be a benefit to us later.
1087                                  * See above in GetPrefix().
1088                                  */
1089                                 std::sort(n->second.begin(), n->second.end(), ModeParser::PrefixComparison);
1090                         }
1091                 }
1092                 else
1093                 {
1094                         pfxcontainer one;
1095                         one.push_back(pfx);
1096                         prefixes.insert(std::make_pair<User*,pfxcontainer>(user, one));
1097                 }
1098         }
1099         else
1100         {
1101                 if (n != prefixes.end())
1102                 {
1103                         pfxcontainer::iterator x = std::find(n->second.begin(), n->second.end(), pfx);
1104                         if (x != n->second.end())
1105                                 n->second.erase(x);
1106                 }
1107         }
1108 }
1109
1110 void Channel::RemoveAllPrefixes(User* user)
1111 {
1112         prefixlist::iterator n = prefixes.find(user);
1113         if (n != prefixes.end())
1114         {
1115                 prefixes.erase(n);
1116         }
1117 }