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