]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Fix global clone count not being decremented on remote user quit
[user/henk/code/inspircd.git] / src / users.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 #include "inspircd.h"
15 #include <stdarg.h>
16 #include "socketengine.h"
17 #include "xline.h"
18 #include "bancache.h"
19 #include "commands/cmd_whowas.h"
20
21 typedef unsigned int uniq_id_t;
22 class sent
23 {
24         uniq_id_t uniq_id;
25         uniq_id_t* array;
26         void init()
27         {
28                 if (!array)
29                         array = new uniq_id_t[ServerInstance->SE->GetMaxFds()];
30                 memset(array, 0, ServerInstance->SE->GetMaxFds() * sizeof(uniq_id_t));
31                 uniq_id++;
32         }
33  public:
34         sent() : uniq_id(static_cast<uniq_id_t>(-1)), array(NULL) {}
35         inline uniq_id_t operator++()
36         {
37                 if (++uniq_id == 0)
38                         init();
39                 return uniq_id;
40         }
41         inline uniq_id_t& operator[](int i)
42         {
43                 return array[i];
44         }
45         ~sent()
46         {
47                 delete[] array;
48         }
49 };
50
51 static sent already_sent;
52
53 std::string User::ProcessNoticeMasks(const char *sm)
54 {
55         bool adding = true, oldadding = false;
56         const char *c = sm;
57         std::string output;
58
59         while (c && *c)
60         {
61                 switch (*c)
62                 {
63                         case '+':
64                                 adding = true;
65                         break;
66                         case '-':
67                                 adding = false;
68                         break;
69                         case '*':
70                                 for (unsigned char d = 'A'; d <= 'z'; d++)
71                                 {
72                                         if (ServerInstance->SNO->IsEnabled(d))
73                                         {
74                                                 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
75                                                 {
76                                                         if ((oldadding != adding) || (!output.length()))
77                                                                 output += (adding ? '+' : '-');
78
79                                                         this->SetNoticeMask(d, adding);
80
81                                                         output += d;
82                                                 }
83                                         }
84                                         oldadding = adding;
85                                 }
86                         break;
87                         default:
88                                 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
89                                 {
90                                         if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
91                                         {
92                                                 if ((oldadding != adding) || (!output.length()))
93                                                         output += (adding ? '+' : '-');
94
95                                                 this->SetNoticeMask(*c, adding);
96
97                                                 output += *c;
98                                         }
99                                 }
100                                 else
101                                         this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
102
103                                 oldadding = adding;
104                         break;
105                 }
106
107                 *c++;
108         }
109
110         std::string s = this->FormatNoticeMasks();
111         if (s.length() == 0)
112         {
113                 this->modes[UM_SNOMASK] = false;
114         }
115
116         return output;
117 }
118
119 void LocalUser::StartDNSLookup()
120 {
121         try
122         {
123                 bool cached = false;
124                 const char* sip = this->GetIPString();
125                 UserResolver *res_reverse;
126
127                 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
128                 res_reverse = new UserResolver(this, sip, resolvtype, cached);
129
130                 ServerInstance->AddResolver(res_reverse, cached);
131         }
132         catch (CoreException& e)
133         {
134                 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
135         }
136 }
137
138 bool User::IsNoticeMaskSet(unsigned char sm)
139 {
140         if (!isalpha(sm))
141                 return false;
142         return (snomasks[sm-65]);
143 }
144
145 void User::SetNoticeMask(unsigned char sm, bool value)
146 {
147         if (!isalpha(sm))
148                 return;
149         snomasks[sm-65] = value;
150 }
151
152 const char* User::FormatNoticeMasks()
153 {
154         static char data[MAXBUF];
155         int offset = 0;
156
157         for (int n = 0; n < 64; n++)
158         {
159                 if (snomasks[n])
160                         data[offset++] = n+65;
161         }
162
163         data[offset] = 0;
164         return data;
165 }
166
167 bool User::IsModeSet(unsigned char m)
168 {
169         if (!isalpha(m))
170                 return false;
171         return (modes[m-65]);
172 }
173
174 void User::SetMode(unsigned char m, bool value)
175 {
176         if (!isalpha(m))
177                 return;
178         modes[m-65] = value;
179 }
180
181 const char* User::FormatModes(bool showparameters)
182 {
183         static char data[MAXBUF];
184         std::string params;
185         int offset = 0;
186
187         for (unsigned char n = 0; n < 64; n++)
188         {
189                 if (modes[n])
190                 {
191                         data[offset++] = n + 65;
192                         ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
193                         if (showparameters && mh && mh->GetNumParams(true))
194                         {
195                                 std::string p = mh->GetUserParameter(this);
196                                 if (p.length())
197                                         params.append(" ").append(p);
198                         }
199                 }
200         }
201         data[offset] = 0;
202         strlcat(data, params.c_str(), MAXBUF);
203         return data;
204 }
205
206 void User::DecrementModes()
207 {
208         ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
209         for (unsigned char n = 'A'; n <= 'z'; n++)
210         {
211                 if (modes[n-65])
212                 {
213                         ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
214                         ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
215                         if (mh)
216                         {
217                                 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
218                                 mh->ChangeCount(-1);
219                         }
220                 }
221         }
222 }
223
224 User::User(const std::string &uid, const std::string& sid, int type)
225         : uuid(uid), server(sid), usertype(type)
226 {
227         age = ServerInstance->Time();
228         signon = idle_lastmsg = 0;
229         registered = 0;
230         quietquit = quitting = exempt = dns_done = false;
231         client_sa.sa.sa_family = AF_UNSPEC;
232
233         ServerInstance->Logs->Log("USERS", DEBUG, "New UUID for user: %s", uuid.c_str());
234
235         user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
236         if (finduuid == ServerInstance->Users->uuidlist->end())
237                 (*ServerInstance->Users->uuidlist)[uuid] = this;
238         else
239                 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
240 }
241
242 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
243         : User(ServerInstance->GetUID(), ServerInstance->Config->ServerName, USERTYPE_LOCAL)
244 {
245         bytes_in = bytes_out = cmds_in = cmds_out = 0;
246         server_sa.sa.sa_family = AF_UNSPEC;
247         Penalty = 0;
248         lastping = nping = 0;
249         SetFd(myfd);
250         memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
251         memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
252 }
253
254 User::~User()
255 {
256         if (ServerInstance->Users->uuidlist->find(uuid) != ServerInstance->Users->uuidlist->end())
257                 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
258 }
259
260 const std::string& User::MakeHost()
261 {
262         if (!this->cached_makehost.empty())
263                 return this->cached_makehost;
264
265         char nhost[MAXBUF];
266         /* This is much faster than snprintf */
267         char* t = nhost;
268         for(const char* n = ident.c_str(); *n; n++)
269                 *t++ = *n;
270         *t++ = '@';
271         for(const char* n = host.c_str(); *n; n++)
272                 *t++ = *n;
273         *t = 0;
274
275         this->cached_makehost.assign(nhost);
276
277         return this->cached_makehost;
278 }
279
280 const std::string& User::MakeHostIP()
281 {
282         if (!this->cached_hostip.empty())
283                 return this->cached_hostip;
284
285         char ihost[MAXBUF];
286         /* This is much faster than snprintf */
287         char* t = ihost;
288         for(const char* n = ident.c_str(); *n; n++)
289                 *t++ = *n;
290         *t++ = '@';
291         for(const char* n = this->GetIPString(); *n; n++)
292                 *t++ = *n;
293         *t = 0;
294
295         this->cached_hostip = ihost;
296
297         return this->cached_hostip;
298 }
299
300 const std::string& User::GetFullHost()
301 {
302         if (!this->cached_fullhost.empty())
303                 return this->cached_fullhost;
304
305         char result[MAXBUF];
306         char* t = result;
307         for(const char* n = nick.c_str(); *n; n++)
308                 *t++ = *n;
309         *t++ = '!';
310         for(const char* n = ident.c_str(); *n; n++)
311                 *t++ = *n;
312         *t++ = '@';
313         for(const char* n = dhost.c_str(); *n; n++)
314                 *t++ = *n;
315         *t = 0;
316
317         this->cached_fullhost = result;
318
319         return this->cached_fullhost;
320 }
321
322 char* User::MakeWildHost()
323 {
324         static char nresult[MAXBUF];
325         char* t = nresult;
326         *t++ = '*';     *t++ = '!';
327         *t++ = '*';     *t++ = '@';
328         for(const char* n = dhost.c_str(); *n; n++)
329                 *t++ = *n;
330         *t = 0;
331         return nresult;
332 }
333
334 const std::string& User::GetFullRealHost()
335 {
336         if (!this->cached_fullrealhost.empty())
337                 return this->cached_fullrealhost;
338
339         char fresult[MAXBUF];
340         char* t = fresult;
341         for(const char* n = nick.c_str(); *n; n++)
342                 *t++ = *n;
343         *t++ = '!';
344         for(const char* n = ident.c_str(); *n; n++)
345                 *t++ = *n;
346         *t++ = '@';
347         for(const char* n = host.c_str(); *n; n++)
348                 *t++ = *n;
349         *t = 0;
350
351         this->cached_fullrealhost = fresult;
352
353         return this->cached_fullrealhost;
354 }
355
356 bool LocalUser::IsInvited(const irc::string &channel)
357 {
358         time_t now = ServerInstance->Time();
359         InvitedList::iterator safei;
360         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
361         {
362                 if (channel == i->first)
363                 {
364                         if (i->second != 0 && now > i->second)
365                         {
366                                 /* Expired invite, remove it. */
367                                 safei = i;
368                                 --i;
369                                 invites.erase(safei);
370                                 continue;
371                         }
372                         return true;
373                 }
374         }
375         return false;
376 }
377
378 InvitedList* LocalUser::GetInviteList()
379 {
380         time_t now = ServerInstance->Time();
381         /* Weed out expired invites here. */
382         InvitedList::iterator safei;
383         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
384         {
385                 if (i->second != 0 && now > i->second)
386                 {
387                         /* Expired invite, remove it. */
388                         safei = i;
389                         --i;
390                         invites.erase(safei);
391                 }
392         }
393         return &invites;
394 }
395
396 void LocalUser::InviteTo(const irc::string &channel, time_t invtimeout)
397 {
398         time_t now = ServerInstance->Time();
399         if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
400         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
401         {
402                 if (channel == i->first)
403                 {
404                         if (i->second != 0 && invtimeout > i->second)
405                         {
406                                 i->second = invtimeout;
407                         }
408
409                         return;
410                 }
411         }
412         invites.push_back(std::make_pair(channel, invtimeout));
413 }
414
415 void LocalUser::RemoveInvite(const irc::string &channel)
416 {
417         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
418         {
419                 if (channel == i->first)
420                 {
421                         invites.erase(i);
422                         return;
423                 }
424         }
425 }
426
427 bool User::HasModePermission(unsigned char, ModeType)
428 {
429         return true;
430 }
431
432 bool LocalUser::HasModePermission(unsigned char mode, ModeType type)
433 {
434         if (!IS_OPER(this))
435                 return false;
436
437         if (mode < 'A' || mode > ('A' + 64)) return false;
438
439         return ((type == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
440
441 }
442 /*
443  * users on remote servers can completely bypass all permissions based checks.
444  * This prevents desyncs when one server has different type/class tags to another.
445  * That having been said, this does open things up to the possibility of source changes
446  * allowing remote kills, etc - but if they have access to the src, they most likely have
447  * access to the conf - so it's an end to a means either way.
448  */
449 bool User::HasPermission(const std::string&)
450 {
451         return true;
452 }
453
454 bool LocalUser::HasPermission(const std::string &command)
455 {
456         // are they even an oper at all?
457         if (!IS_OPER(this))
458         {
459                 return false;
460         }
461
462         if (oper->AllowedOperCommands.find(command) != oper->AllowedOperCommands.end())
463                 return true;
464         else if (oper->AllowedOperCommands.find("*") != oper->AllowedOperCommands.end())
465                 return true;
466
467         return false;
468 }
469
470 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
471 {
472         return true;
473 }
474
475 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
476 {
477         if (!IS_OPER(this))
478         {
479                 if (noisy)
480                         this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
481                 return false;
482         }
483
484         if (oper->AllowedPrivs.find(privstr) != oper->AllowedPrivs.end())
485         {
486                 return true;
487         }
488         else if (oper->AllowedPrivs.find("*") != oper->AllowedPrivs.end())
489         {
490                 return true;
491         }
492
493         if (noisy)
494                 this->WriteServ("NOTICE %s :Oper type %s does not have access to priv %s", this->nick.c_str(), oper->NameStr(), privstr.c_str());
495         return false;
496 }
497
498 void User::OnDataReady()
499 {
500 }
501
502 void LocalUser::OnDataReady()
503 {
504         if (quitting)
505                 return;
506
507         if (recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
508         {
509                 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
510                 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
511                         nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
512         }
513         unsigned long sendqmax = ULONG_MAX;
514         if (!HasPrivPermission("users/flood/increased-buffers"))
515                 sendqmax = MyClass->GetSendqSoftMax();
516         int penaltymax = MyClass->GetPenaltyThreshold();
517         if (penaltymax == 0 || HasPrivPermission("users/flood/no-fakelag"))
518                 penaltymax = INT_MAX;
519
520         while (Penalty < penaltymax && getSendQSize() < sendqmax)
521         {
522                 std::string line;
523                 line.reserve(MAXBUF);
524                 std::string::size_type qpos = 0;
525                 while (qpos < recvq.length())
526                 {
527                         char c = recvq[qpos++];
528                         switch (c)
529                         {
530                         case '\0':
531                                 c = ' ';
532                                 break;
533                         case '\r':
534                                 continue;
535                         case '\n':
536                                 goto eol_found;
537                         }
538                         if (line.length() < MAXBUF - 2)
539                                 line.push_back(c);
540                 }
541                 // if we got here, the recvq ran out before we found a newline
542                 return;
543 eol_found:
544                 // just found a newline. Terminate the string, and pull it out of recvq
545                 recvq = recvq.substr(qpos);
546
547                 // TODO should this be moved to when it was inserted in recvq?
548                 ServerInstance->stats->statsRecv += qpos;
549                 this->bytes_in += qpos;
550                 this->cmds_in++;
551
552                 ServerInstance->Parser->ProcessBuffer(line, this);
553                 if (quitting)
554                         return;
555         }
556         // Add pseudo-penalty so that we continue processing after sendq recedes
557         if (Penalty == 0 && getSendQSize() >= sendqmax)
558                 Penalty++;
559 }
560
561 void LocalUser::AddWriteBuf(const std::string &data)
562 {
563         if (!quitting && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
564         {
565                 /*
566                  * Quit the user FIRST, because otherwise we could recurse
567                  * here and hit the same limit.
568                  */
569                 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
570                 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
571                         nick.c_str(), MyClass->GetSendqHardMax());
572                 return;
573         }
574
575         // We still want to append data to the sendq of a quitting user,
576         // e.g. their ERROR message that says 'closing link'
577
578         WriteData(data);
579 }
580
581 void User::OnError(BufferedSocketError)
582 {
583         ServerInstance->Users->QuitUser(this, getError());
584 }
585
586 CullResult User::cull()
587 {
588         if (!quitting)
589                 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
590         PurgeEmptyChannels();
591
592         this->InvalidateCache();
593         this->DecrementModes();
594
595         if (client_sa.sa.sa_family != AF_UNSPEC)
596                 ServerInstance->Users->RemoveCloneCounts(this);
597
598         ServerInstance->Users->uuidlist->erase(uuid);
599         return Extensible::cull();
600 }
601
602 CullResult LocalUser::cull()
603 {
604         std::vector<LocalUser*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
605         if (x != ServerInstance->Users->local_users.end())
606                 ServerInstance->Users->local_users.erase(x);
607         else
608                 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
609
610         Close();
611         return User::cull();
612 }
613
614 CullResult FakeUser::cull()
615 {
616         // Fake users don't quit, they just get culled.
617         quitting = true;
618         return User::cull();
619 }
620
621 void User::Oper(OperInfo* info)
622 {
623         if (this->IsModeSet('o'))
624                 this->UnOper();
625
626         this->modes[UM_OPERATOR] = 1;
627         this->oper = info;
628         this->WriteServ("MODE %s :+o", this->nick.c_str());
629         FOREACH_MOD(I_OnOper, OnOper(this, info->name));
630
631         std::string opername;
632         if (info->oper_block)
633                 opername = info->oper_block->getString("name");
634
635         if (IS_LOCAL(this))
636         {
637                 LocalUser* l = IS_LOCAL(this);
638                 std::string vhost = oper->getConfig("vhost");
639                 if (!vhost.empty())
640                         l->ChangeDisplayedHost(vhost.c_str());
641                 std::string opClass = oper->getConfig("class");
642                 if (!opClass.empty())
643                 {
644                         l->SetClass(opClass);
645                         l->CheckClass();
646                 }
647         }
648
649         ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
650                 nick.c_str(), ident.c_str(), host.c_str(), oper->NameStr(), opername.c_str());
651         this->WriteNumeric(381, "%s :You are now %s %s", nick.c_str(), strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->NameStr());
652
653         ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick.c_str(), this->ident.c_str(), this->host.c_str(), oper->NameStr());
654         ServerInstance->Users->all_opers.push_back(this);
655
656         // Expand permissions from config for faster lookup
657         if (IS_LOCAL(this))
658                 oper->init();
659
660         FOREACH_MOD(I_OnPostOper,OnPostOper(this, oper->name, opername));
661 }
662
663 void OperInfo::init()
664 {
665         AllowedOperCommands.clear();
666         AllowedPrivs.clear();
667         AllowedUserModes.reset();
668         AllowedChanModes.reset();
669         AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
670
671         for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
672         {
673                 ConfigTag* tag = *iter;
674                 std::string mycmd, mypriv;
675                 /* Process commands */
676                 irc::spacesepstream CommandList(tag->getString("commands"));
677                 while (CommandList.GetToken(mycmd))
678                 {
679                         AllowedOperCommands.insert(mycmd);
680                 }
681
682                 irc::spacesepstream PrivList(tag->getString("privs"));
683                 while (PrivList.GetToken(mypriv))
684                 {
685                         AllowedPrivs.insert(mypriv);
686                 }
687
688                 for (unsigned char* c = (unsigned char*)tag->getString("usermodes").c_str(); *c; ++c)
689                 {
690                         if (*c == '*')
691                         {
692                                 this->AllowedUserModes.set();
693                         }
694                         else
695                         {
696                                 this->AllowedUserModes[*c - 'A'] = true;
697                         }
698                 }
699
700                 for (unsigned char* c = (unsigned char*)tag->getString("chanmodes").c_str(); *c; ++c)
701                 {
702                         if (*c == '*')
703                         {
704                                 this->AllowedChanModes.set();
705                         }
706                         else
707                         {
708                                 this->AllowedChanModes[*c - 'A'] = true;
709                         }
710                 }
711         }
712 }
713
714 void User::UnOper()
715 {
716         if (!IS_OPER(this))
717                 return;
718
719         /*
720          * unset their oper type (what IS_OPER checks).
721          * note, order is important - this must come before modes as -o attempts
722          * to call UnOper. -- w00t
723          */
724         oper = NULL;
725
726
727         /* Remove all oper only modes from the user when the deoper - Bug #466*/
728         std::string moderemove("-");
729
730         for (unsigned char letter = 'A'; letter <= 'z'; letter++)
731         {
732                 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
733                 if (mh && mh->NeedsOper())
734                         moderemove += letter;
735         }
736
737
738         std::vector<std::string> parameters;
739         parameters.push_back(this->nick);
740         parameters.push_back(moderemove);
741
742         ServerInstance->Parser->CallHandler("MODE", parameters, this);
743
744         /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
745         ServerInstance->Users->all_opers.remove(this);
746
747         this->modes[UM_OPERATOR] = 0;
748 }
749
750 /* adds or updates an entry in the whowas list */
751 void User::AddToWhoWas()
752 {
753         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
754         if (whowas)
755         {
756                 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
757                 req.user = this;
758                 req.Send();
759         }
760 }
761
762 /*
763  * Check class restrictions
764  */
765 void LocalUser::CheckClass()
766 {
767         ConnectClass* a = this->MyClass;
768
769         if (!a)
770         {
771                 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
772         }
773         else if (a->type == CC_DENY)
774         {
775                 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
776                 return;
777         }
778         else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
779         {
780                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
781                 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
782                 return;
783         }
784         else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
785         {
786                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
787                 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
788                 return;
789         }
790
791         this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
792 }
793
794 bool User::CheckLines(bool doZline)
795 {
796         const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
797
798         if (!this->exempt)
799         {
800                 for (int n = 0; check[n]; ++n)
801                 {
802                         XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
803
804                         if (r)
805                         {
806                                 r->Apply(this);
807                                 return true;
808                         }
809                 }
810         }
811
812         return false;
813 }
814
815 void LocalUser::FullConnect()
816 {
817         ServerInstance->stats->statsConnects++;
818         this->idle_lastmsg = ServerInstance->Time();
819
820         /*
821          * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
822          * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
823          * may put the user into a totally seperate class with different restrictions! so we *must* check again.
824          * Don't remove this! -- w00t
825          */
826         this->SetClass();
827
828         /* Check the password, if one is required by the user's connect class.
829          * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
830          */
831         if (!MyClass->pass.empty())
832         {
833                 if (ServerInstance->PassCompare(this, MyClass->pass.c_str(), password.c_str(), MyClass->hash.c_str()))
834                 {
835                         ServerInstance->Users->QuitUser(this, "Invalid password");
836                         return;
837                 }
838         }
839
840         if (this->CheckLines())
841                 return;
842
843         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
844         this->WriteNumeric(RPL_WELCOME, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick.c_str(), ServerInstance->Config->Network.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str());
845         this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
846         this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
847         this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-2.0 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
848
849         ServerInstance->Config->Send005(this);
850         this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
851
852
853         this->ShowMOTD();
854
855         /* Now registered */
856         if (ServerInstance->Users->unregistered_count)
857                 ServerInstance->Users->unregistered_count--;
858
859         /* Trigger LUSERS output, give modules a chance too */
860         ModResult MOD_RESULT;
861         std::string command("LUSERS");
862         std::vector<std::string> parameters;
863         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
864         if (!MOD_RESULT)
865                 ServerInstance->CallCommandHandler(command, parameters, this);
866
867         /*
868          * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
869          * for a user that doesn't exist yet.
870          */
871         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
872
873         this->registered = REG_ALL;
874
875         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
876
877         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
878                 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
879         ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
880         ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
881 }
882
883 /** User::UpdateNick()
884  * re-allocates a nick in the user_hash after they change nicknames,
885  * returns a pointer to the new user as it may have moved
886  */
887 User* User::UpdateNickHash(const char* New)
888 {
889         //user_hash::iterator newnick;
890         user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
891
892         if (!irc::string(this->nick.c_str()).compare(New))
893                 return oldnick->second;
894
895         if (oldnick == ServerInstance->Users->clientlist->end())
896                 return NULL; /* doesnt exist */
897
898         User* olduser = oldnick->second;
899         ServerInstance->Users->clientlist->erase(oldnick);
900         (*(ServerInstance->Users->clientlist))[New] = olduser;
901         return olduser;
902 }
903
904 void User::InvalidateCache()
905 {
906         /* Invalidate cache */
907         cached_fullhost.clear();
908         cached_hostip.clear();
909         cached_makehost.clear();
910         cached_fullrealhost.clear();
911 }
912
913 bool User::ForceNickChange(const char* newnick)
914 {
915         ModResult MOD_RESULT;
916
917         this->InvalidateCache();
918
919         ServerInstance->NICKForced.set(this, 1);
920         FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
921         ServerInstance->NICKForced.set(this, 0);
922
923         if (MOD_RESULT == MOD_RES_DENY)
924         {
925                 ServerInstance->stats->statsCollisions++;
926                 return false;
927         }
928
929         std::deque<classbase*> dummy;
930         Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
931         if (nickhandler) // wtfbbq, when would this not be here
932         {
933                 std::vector<std::string> parameters;
934                 parameters.push_back(newnick);
935                 ServerInstance->NICKForced.set(this, 1);
936                 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
937                 ServerInstance->NICKForced.set(this, 0);
938                 return result;
939         }
940
941         // Unreachable, we hope
942         return false;
943 }
944
945 int LocalUser::GetServerPort()
946 {
947         switch (this->server_sa.sa.sa_family)
948         {
949                 case AF_INET6:
950                         return htons(this->server_sa.in6.sin6_port);
951                 case AF_INET:
952                         return htons(this->server_sa.in4.sin_port);
953         }
954         return 0;
955 }
956
957 const char* User::GetIPString()
958 {
959         int port;
960         if (cachedip.empty())
961         {
962                 irc::sockets::satoap(client_sa, cachedip, port);
963                 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
964                 if (cachedip.c_str()[0] == ':')
965                         cachedip.insert(0,1,'0');
966         }
967
968         return cachedip.c_str();
969 }
970
971 irc::sockets::cidr_mask User::GetCIDRMask()
972 {
973         int range = 0;
974         switch (client_sa.sa.sa_family)
975         {
976                 case AF_INET6:
977                         range = ServerInstance->Config->c_ipv6_range;
978                         break;
979                 case AF_INET:
980                         range = ServerInstance->Config->c_ipv4_range;
981                         break;
982         }
983         return irc::sockets::cidr_mask(client_sa, range);
984 }
985
986 bool User::SetClientIP(const char* sip)
987 {
988         this->cachedip = "";
989         return irc::sockets::aptosa(sip, 0, client_sa);
990 }
991
992 static std::string wide_newline("\r\n");
993
994 void User::Write(const std::string& text)
995 {
996 }
997
998 void User::Write(const char *text, ...)
999 {
1000 }
1001
1002 void LocalUser::Write(const std::string& text)
1003 {
1004         if (!ServerInstance->SE->BoundsCheckFd(this))
1005                 return;
1006
1007         if (text.length() > MAXBUF - 2)
1008         {
1009                 // this should happen rarely or never. Crop the string at 512 and try again.
1010                 std::string try_again = text.substr(0, MAXBUF - 2);
1011                 Write(try_again);
1012                 return;
1013         }
1014
1015         ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1016
1017         this->AddWriteBuf(text);
1018         this->AddWriteBuf(wide_newline);
1019
1020         ServerInstance->stats->statsSent += text.length() + 2;
1021         this->bytes_out += text.length() + 2;
1022         this->cmds_out++;
1023 }
1024
1025 /** Write()
1026  */
1027 void LocalUser::Write(const char *text, ...)
1028 {
1029         va_list argsPtr;
1030         char textbuffer[MAXBUF];
1031
1032         va_start(argsPtr, text);
1033         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1034         va_end(argsPtr);
1035
1036         this->Write(std::string(textbuffer));
1037 }
1038
1039 void User::WriteServ(const std::string& text)
1040 {
1041         this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1042 }
1043
1044 /** WriteServ()
1045  *  Same as Write(), except `text' is prefixed with `:server.name '.
1046  */
1047 void User::WriteServ(const char* text, ...)
1048 {
1049         va_list argsPtr;
1050         char textbuffer[MAXBUF];
1051
1052         va_start(argsPtr, text);
1053         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1054         va_end(argsPtr);
1055
1056         this->WriteServ(std::string(textbuffer));
1057 }
1058
1059
1060 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1061 {
1062         va_list argsPtr;
1063         char textbuffer[MAXBUF];
1064
1065         va_start(argsPtr, text);
1066         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1067         va_end(argsPtr);
1068
1069         this->WriteNumeric(numeric, std::string(textbuffer));
1070 }
1071
1072 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1073 {
1074         char textbuffer[MAXBUF];
1075         ModResult MOD_RESULT;
1076
1077         FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1078
1079         if (MOD_RESULT == MOD_RES_DENY)
1080                 return;
1081
1082         snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1083         this->Write(std::string(textbuffer));
1084 }
1085
1086 void User::WriteFrom(User *user, const std::string &text)
1087 {
1088         char tb[MAXBUF];
1089
1090         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1091
1092         this->Write(std::string(tb));
1093 }
1094
1095
1096 /* write text from an originating user to originating user */
1097
1098 void User::WriteFrom(User *user, const char* text, ...)
1099 {
1100         va_list argsPtr;
1101         char textbuffer[MAXBUF];
1102
1103         va_start(argsPtr, text);
1104         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1105         va_end(argsPtr);
1106
1107         this->WriteFrom(user, std::string(textbuffer));
1108 }
1109
1110
1111 /* write text to an destination user from a source user (e.g. user privmsg) */
1112
1113 void User::WriteTo(User *dest, const char *data, ...)
1114 {
1115         char textbuffer[MAXBUF];
1116         va_list argsPtr;
1117
1118         va_start(argsPtr, data);
1119         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1120         va_end(argsPtr);
1121
1122         this->WriteTo(dest, std::string(textbuffer));
1123 }
1124
1125 void User::WriteTo(User *dest, const std::string &data)
1126 {
1127         dest->WriteFrom(this, data);
1128 }
1129
1130 void User::WriteCommon(const char* text, ...)
1131 {
1132         char textbuffer[MAXBUF];
1133         va_list argsPtr;
1134
1135         if (this->registered != REG_ALL || quitting)
1136                 return;
1137
1138         int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1139
1140         va_start(argsPtr, text);
1141         vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1142         va_end(argsPtr);
1143
1144         this->WriteCommonRaw(std::string(textbuffer), true);
1145 }
1146
1147 void User::WriteCommonExcept(const char* text, ...)
1148 {
1149         char textbuffer[MAXBUF];
1150         va_list argsPtr;
1151
1152         if (this->registered != REG_ALL || quitting)
1153                 return;
1154
1155         int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1156
1157         va_start(argsPtr, text);
1158         vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1159         va_end(argsPtr);
1160
1161         this->WriteCommonRaw(std::string(textbuffer), false);
1162 }
1163
1164 void User::WriteCommonRaw(const std::string &line, bool include_self)
1165 {
1166         if (this->registered != REG_ALL || quitting)
1167                 return;
1168
1169         uniq_id_t uniq_id = ++already_sent;
1170
1171         UserChanList include_c(chans);
1172         std::map<User*,bool> exceptions;
1173
1174         exceptions[this] = include_self;
1175
1176         FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1177
1178         for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1179         {
1180                 LocalUser* u = IS_LOCAL(i->first);
1181                 if (u && !u->quitting)
1182                 {
1183                         already_sent[u->GetFd()] = uniq_id;
1184                         if (i->second)
1185                                 u->Write(line);
1186                 }
1187         }
1188         for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1189         {
1190                 Channel* c = *v;
1191                 const UserMembList* ulist = c->GetUsers();
1192                 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1193                 {
1194                         LocalUser* u = IS_LOCAL(i->first);
1195                         if (u && !u->quitting && already_sent[u->GetFd()] != uniq_id)
1196                         {
1197                                 already_sent[u->GetFd()] = uniq_id;
1198                                 u->Write(line);
1199                         }
1200                 }
1201         }
1202 }
1203
1204 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1205 {
1206         char tb1[MAXBUF];
1207         char tb2[MAXBUF];
1208
1209         if (this->registered != REG_ALL)
1210                 return;
1211
1212         uniq_id_t uniq_id = ++already_sent;
1213
1214         snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1215         snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1216         std::string out1 = tb1;
1217         std::string out2 = tb2;
1218
1219         UserChanList include_c(chans);
1220         std::map<User*,bool> exceptions;
1221
1222         FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1223
1224         for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1225         {
1226                 LocalUser* u = IS_LOCAL(i->first);
1227                 if (u && !u->quitting)
1228                 {
1229                         already_sent[u->GetFd()] = uniq_id;
1230                         if (i->second)
1231                                 u->Write(IS_OPER(u) ? out2 : out1);
1232                 }
1233         }
1234         for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1235         {
1236                 const UserMembList* ulist = (*v)->GetUsers();
1237                 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1238                 {
1239                         LocalUser* u = IS_LOCAL(i->first);
1240                         if (u && !u->quitting && (already_sent[u->GetFd()] != uniq_id))
1241                         {
1242                                 already_sent[u->GetFd()] = uniq_id;
1243                                 u->Write(IS_OPER(u) ? out2 : out1);
1244                         }
1245                 }
1246         }
1247 }
1248
1249 void LocalUser::SendText(const std::string& line)
1250 {
1251         Write(line);
1252 }
1253
1254 void RemoteUser::SendText(const std::string& line)
1255 {
1256         ServerInstance->PI->PushToClient(this, line);
1257 }
1258
1259 void FakeUser::SendText(const std::string& line)
1260 {
1261 }
1262
1263 void User::SendText(const char *text, ...)
1264 {
1265         va_list argsPtr;
1266         char line[MAXBUF];
1267
1268         va_start(argsPtr, text);
1269         vsnprintf(line, MAXBUF, text, argsPtr);
1270         va_end(argsPtr);
1271
1272         SendText(std::string(line));
1273 }
1274
1275 void User::SendText(const std::string &LinePrefix, std::stringstream &TextStream)
1276 {
1277         char line[MAXBUF];
1278         int start_pos = LinePrefix.length();
1279         int pos = start_pos;
1280         memcpy(line, LinePrefix.data(), pos);
1281         std::string Word;
1282         while (TextStream >> Word)
1283         {
1284                 int len = Word.length();
1285                 if (pos + len + 12 > MAXBUF)
1286                 {
1287                         line[pos] = '\0';
1288                         SendText(std::string(line));
1289                         pos = start_pos;
1290                 }
1291                 line[pos] = ' ';
1292                 memcpy(line + pos + 1, Word.data(), len);
1293                 pos += len + 1;
1294         }
1295         line[pos] = '\0';
1296         SendText(std::string(line));
1297 }
1298
1299 /* return 0 or 1 depending if users u and u2 share one or more common channels
1300  * (used by QUIT, NICK etc which arent channel specific notices)
1301  *
1302  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1303  * the first users channels then the second users channels within the outer loop,
1304  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1305  * all possible iterations). However this new function instead checks against the
1306  * channel's userlist in the inner loop which is a std::map<User*,User*>
1307  * and saves us time as we already know what pointer value we are after.
1308  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1309  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1310  */
1311 bool User::SharesChannelWith(User *other)
1312 {
1313         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1314                 return false;
1315
1316         /* Outer loop */
1317         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1318         {
1319                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1320                  * by replacing it with a map::find which *should* be more efficient
1321                  */
1322                 if ((*i)->HasUser(other))
1323                         return true;
1324         }
1325         return false;
1326 }
1327
1328 bool User::ChangeName(const char* gecos)
1329 {
1330         if (!this->fullname.compare(gecos))
1331                 return true;
1332
1333         if (IS_LOCAL(this))
1334         {
1335                 ModResult MOD_RESULT;
1336                 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (IS_LOCAL(this),gecos));
1337                 if (MOD_RESULT == MOD_RES_DENY)
1338                         return false;
1339                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1340         }
1341         this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1342
1343         return true;
1344 }
1345
1346 void User::DoHostCycle(const std::string &quitline)
1347 {
1348         char buffer[MAXBUF];
1349
1350         if (!ServerInstance->Config->CycleHosts)
1351                 return;
1352
1353         uniq_id_t silent_id = ++already_sent;
1354         uniq_id_t seen_id = ++already_sent;
1355
1356         UserChanList include_c(chans);
1357         std::map<User*,bool> exceptions;
1358
1359         FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1360
1361         for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1362         {
1363                 LocalUser* u = IS_LOCAL(i->first);
1364                 if (u && !u->quitting)
1365                 {
1366                         if (i->second)
1367                         {
1368                                 already_sent[u->GetFd()] = seen_id;
1369                                 u->Write(quitline);
1370                         }
1371                         else
1372                         {
1373                                 already_sent[u->GetFd()] = silent_id;
1374                         }
1375                 }
1376         }
1377         for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1378         {
1379                 Channel* c = *v;
1380                 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1381                 std::string joinline(buffer);
1382                 Membership* memb = c->GetUser(this);
1383                 std::string modeline = memb->modes;
1384                 if (modeline.length() > 0)
1385                 {
1386                         for(unsigned int i=0; i < memb->modes.length(); i++)
1387                                 modeline.append(" ").append(nick);
1388                         snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1389                         modeline = buffer;
1390                 }
1391
1392                 const UserMembList *ulist = c->GetUsers();
1393                 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1394                 {
1395                         LocalUser* u = IS_LOCAL(i->first);
1396                         if (u == NULL || u == this)
1397                                 continue;
1398                         if (already_sent[u->GetFd()] == silent_id)
1399                                 continue;
1400
1401                         if (already_sent[u->GetFd()] != seen_id)
1402                         {
1403                                 u->Write(quitline);
1404                                 already_sent[u->GetFd()] = seen_id;
1405                         }
1406                         u->Write(joinline);
1407                         if (modeline.length() > 0)
1408                                 u->Write(modeline);
1409                 }
1410         }
1411 }
1412
1413 bool User::ChangeDisplayedHost(const char* shost)
1414 {
1415         if (dhost == shost)
1416                 return true;
1417
1418         if (IS_LOCAL(this))
1419         {
1420                 ModResult MOD_RESULT;
1421                 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (IS_LOCAL(this),shost));
1422                 if (MOD_RESULT == MOD_RES_DENY)
1423                         return false;
1424         }
1425
1426         FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1427
1428         std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1429
1430         /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1431         this->dhost.assign(shost, 0, 64);
1432
1433         this->InvalidateCache();
1434
1435         this->DoHostCycle(quitstr);
1436
1437         if (IS_LOCAL(this))
1438                 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1439
1440         return true;
1441 }
1442
1443 bool User::ChangeIdent(const char* newident)
1444 {
1445         if (this->ident == newident)
1446                 return true;
1447
1448         FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1449
1450         std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1451
1452         this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1453
1454         this->InvalidateCache();
1455
1456         this->DoHostCycle(quitstr);
1457
1458         return true;
1459 }
1460
1461 void User::SendAll(const char* command, const char* text, ...)
1462 {
1463         char textbuffer[MAXBUF];
1464         char formatbuffer[MAXBUF];
1465         va_list argsPtr;
1466
1467         va_start(argsPtr, text);
1468         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1469         va_end(argsPtr);
1470
1471         snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1472         std::string fmt = formatbuffer;
1473
1474         for (std::vector<LocalUser*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1475         {
1476                 (*i)->Write(fmt);
1477         }
1478 }
1479
1480
1481 std::string User::ChannelList(User* source, bool spy)
1482 {
1483         std::string list;
1484
1485         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1486         {
1487                 Channel* c = *i;
1488                 /* If the target is the sender, neither +p nor +s is set, or
1489                  * the channel contains the user, it is not a spy channel
1490                  */
1491                 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1492                         list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1493         }
1494
1495         return list;
1496 }
1497
1498 void User::SplitChanList(User* dest, const std::string &cl)
1499 {
1500         std::string line;
1501         std::ostringstream prefix;
1502         std::string::size_type start, pos, length;
1503
1504         prefix << this->nick << " " << dest->nick << " :";
1505         line = prefix.str();
1506         int namelen = ServerInstance->Config->ServerName.length() + 6;
1507
1508         for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1509         {
1510                 length = (pos == std::string::npos) ? cl.length() : pos;
1511
1512                 if (line.length() + namelen + length - start > 510)
1513                 {
1514                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1515                         line = prefix.str();
1516                 }
1517
1518                 if(pos == std::string::npos)
1519                 {
1520                         line.append(cl.substr(start, length - start));
1521                         break;
1522                 }
1523                 else
1524                 {
1525                         line.append(cl.substr(start, length - start + 1));
1526                 }
1527         }
1528
1529         if (line.length())
1530         {
1531                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1532         }
1533 }
1534
1535 /*
1536  * Sets a user's connection class.
1537  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1538  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1539  * then their ip will be taken as 'priority' anyway, so for example,
1540  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1541  */
1542 void LocalUser::SetClass(const std::string &explicit_name)
1543 {
1544         ConnectClass *found = NULL;
1545
1546         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1547
1548         if (!explicit_name.empty())
1549         {
1550                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1551                 {
1552                         ConnectClass* c = *i;
1553
1554                         if (explicit_name == c->name)
1555                         {
1556                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1557                                 found = c;
1558                         }
1559                 }
1560         }
1561         else
1562         {
1563                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1564                 {
1565                         ConnectClass* c = *i;
1566
1567                         if (c->type == CC_ALLOW)
1568                         {
1569                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1570                         }
1571                         else
1572                         {
1573                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1574                         }
1575
1576                         /* check if host matches.. */
1577                         if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1578                             !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1579                         {
1580                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1581                                 continue;
1582                         }
1583
1584                         /*
1585                          * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1586                          * because we should attempt to find another class if this one doesn't match us. -- w00t
1587                          */
1588                         if (c->limit && (c->GetReferenceCount() >= c->limit))
1589                         {
1590                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1591                                 continue;
1592                         }
1593
1594                         /* if it requires a port ... */
1595                         if (c->GetPort())
1596                         {
1597                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1598
1599                                 /* and our port doesn't match, fail. */
1600                                 if (this->GetServerPort() != c->GetPort())
1601                                 {
1602                                         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1603                                         continue;
1604                                 }
1605                         }
1606
1607                         /* we stop at the first class that meets ALL critera. */
1608                         found = c;
1609                         break;
1610                 }
1611         }
1612
1613         /*
1614          * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1615          */
1616         if (found)
1617         {
1618                 MyClass = found;
1619         }
1620 }
1621
1622 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1623  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1624  * then their ip will be taken as 'priority' anyway, so for example,
1625  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1626  */
1627 ConnectClass* LocalUser::GetClass()
1628 {
1629         return MyClass;
1630 }
1631
1632 ConnectClass* User::GetClass()
1633 {
1634         return NULL;
1635 }
1636
1637 void User::PurgeEmptyChannels()
1638 {
1639         // firstly decrement the count on each channel
1640         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1641         {
1642                 Channel* c = *f;
1643                 c->DelUser(this);
1644         }
1645
1646         this->UnOper();
1647 }
1648
1649 void User::ShowMOTD()
1650 {
1651         if (!ServerInstance->Config->MOTD.size())
1652         {
1653                 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1654                 return;
1655         }
1656         this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1657
1658         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1659                 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1660
1661         this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1662 }
1663
1664 void User::ShowRULES()
1665 {
1666         if (!ServerInstance->Config->RULES.size())
1667         {
1668                 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1669                 return;
1670         }
1671
1672         this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1673
1674         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1675                 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1676
1677         this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1678 }
1679
1680 const std::string& FakeUser::GetFullHost()
1681 {
1682         if (!ServerInstance->Config->HideWhoisServer.empty())
1683                 return ServerInstance->Config->HideWhoisServer;
1684         return server;
1685 }
1686
1687 const std::string& FakeUser::GetFullRealHost()
1688 {
1689         if (!ServerInstance->Config->HideWhoisServer.empty())
1690                 return ServerInstance->Config->HideWhoisServer;
1691         return server;
1692 }
1693
1694 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1695         : config(tag), type(t), name("unnamed"), registration_timeout(0), host(mask),
1696         pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1697         recvqmax(0), penaltythreshold(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1698 {
1699 }
1700
1701 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1702         : config(tag), type(t), name("unnamed"),
1703         registration_timeout(parent.registration_timeout), host(mask),
1704         pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1705         softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1706         recvqmax(parent.recvqmax), penaltythreshold(parent.penaltythreshold), maxlocal(parent.maxlocal),
1707         maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1708         port(parent.port), limit(parent.limit)
1709 {
1710 }
1711
1712 void ConnectClass::Update(const ConnectClass* src)
1713 {
1714         name = src->name;
1715         registration_timeout = src->registration_timeout;
1716         host = src->host;
1717         pingtime = src->pingtime;
1718         pass = src->pass;
1719         hash = src->hash;
1720         softsendqmax = src->softsendqmax;
1721         hardsendqmax = src->hardsendqmax;
1722         recvqmax = src->recvqmax;
1723         penaltythreshold = src->penaltythreshold;
1724         maxlocal = src->maxlocal;
1725         maxglobal = src->maxglobal;
1726         limit = src->limit;
1727 }