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