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