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