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