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