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