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