]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
32ae873890d0cb6b594fdfd13432997497f37d66
[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
32 already_sent_t LocalUser::already_sent_id = 0;
33
34 bool User::IsNoticeMaskSet(unsigned char sm)
35 {
36         if (!isalpha(sm))
37                 return false;
38         return (snomasks[sm-65]);
39 }
40
41 bool User::IsModeSet(unsigned char m)
42 {
43         if (!isalpha(m))
44                 return false;
45         return (modes[m-65]);
46 }
47
48 const char* User::FormatModes(bool showparameters)
49 {
50         static std::string data;
51         std::string params;
52         data.clear();
53
54         for (unsigned char n = 0; n < 64; n++)
55         {
56                 if (modes[n])
57                 {
58                         data.push_back(n + 65);
59                         ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
60                         if (showparameters && mh && mh->GetNumParams(true))
61                         {
62                                 std::string p = mh->GetUserParameter(this);
63                                 if (p.length())
64                                         params.append(" ").append(p);
65                         }
66                 }
67         }
68         data += params;
69         return data.c_str();
70 }
71
72 User::User(const std::string& uid, Server* srv, int type)
73         : uuid(uid), server(srv), usertype(type)
74 {
75         age = ServerInstance->Time();
76         signon = 0;
77         registered = 0;
78         quitting = false;
79         client_sa.sa.sa_family = AF_UNSPEC;
80
81         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
82
83         if (!ServerInstance->Users->uuidlist->insert(std::make_pair(uuid, this)).second)
84                 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
85 }
86
87 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
88         : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL), eh(this),
89         bytes_in(0), bytes_out(0), cmds_in(0), cmds_out(0), nping(0), CommandFloodPenalty(0),
90         already_sent(0)
91 {
92         exempt = quitting_sendq = false;
93         idle_lastmsg = 0;
94         ident = "unknown";
95         lastping = 0;
96         eh.SetFd(myfd);
97         memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
98         memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
99         dhost = host = GetIPString();
100 }
101
102 User::~User()
103 {
104         if (ServerInstance->Users->uuidlist->find(uuid) != ServerInstance->Users->uuidlist->end())
105                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "User destructor for %s called without cull", uuid.c_str());
106 }
107
108 const std::string& User::MakeHost()
109 {
110         if (!this->cached_makehost.empty())
111                 return this->cached_makehost;
112
113         // XXX: Is there really a need to cache this?
114         this->cached_makehost = ident + "@" + host;
115         return this->cached_makehost;
116 }
117
118 const std::string& User::MakeHostIP()
119 {
120         if (!this->cached_hostip.empty())
121                 return this->cached_hostip;
122
123         // XXX: Is there really a need to cache this?
124         this->cached_hostip = ident + "@" + this->GetIPString();
125         return this->cached_hostip;
126 }
127
128 const std::string& User::GetFullHost()
129 {
130         if (!this->cached_fullhost.empty())
131                 return this->cached_fullhost;
132
133         // XXX: Is there really a need to cache this?
134         this->cached_fullhost = nick + "!" + ident + "@" + dhost;
135         return this->cached_fullhost;
136 }
137
138 const std::string& User::GetFullRealHost()
139 {
140         if (!this->cached_fullrealhost.empty())
141                 return this->cached_fullrealhost;
142
143         // XXX: Is there really a need to cache this?
144         this->cached_fullrealhost = nick + "!" + ident + "@" + host;
145         return this->cached_fullrealhost;
146 }
147
148 InviteList& LocalUser::GetInviteList()
149 {
150         RemoveExpiredInvites();
151         return invites;
152 }
153
154 bool LocalUser::RemoveInvite(Channel* chan)
155 {
156         Invitation* inv = Invitation::Find(chan, this);
157         if (inv)
158         {
159                 delete inv;
160                 return true;
161         }
162         return false;
163 }
164
165 void LocalUser::RemoveExpiredInvites()
166 {
167         Invitation::Find(NULL, this);
168 }
169
170 bool User::HasModePermission(unsigned char, ModeType)
171 {
172         return true;
173 }
174
175 bool LocalUser::HasModePermission(unsigned char mode, ModeType type)
176 {
177         if (!this->IsOper())
178                 return false;
179
180         if (mode < 'A' || mode > ('A' + 64)) return false;
181
182         return ((type == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
183
184 }
185 /*
186  * users on remote servers can completely bypass all permissions based checks.
187  * This prevents desyncs when one server has different type/class tags to another.
188  * That having been said, this does open things up to the possibility of source changes
189  * allowing remote kills, etc - but if they have access to the src, they most likely have
190  * access to the conf - so it's an end to a means either way.
191  */
192 bool User::HasPermission(const std::string&)
193 {
194         return true;
195 }
196
197 bool LocalUser::HasPermission(const std::string &command)
198 {
199         // are they even an oper at all?
200         if (!this->IsOper())
201         {
202                 return false;
203         }
204
205         if (oper->AllowedOperCommands.find(command) != oper->AllowedOperCommands.end())
206                 return true;
207         else if (oper->AllowedOperCommands.find("*") != oper->AllowedOperCommands.end())
208                 return true;
209
210         return false;
211 }
212
213 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
214 {
215         return true;
216 }
217
218 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
219 {
220         if (!this->IsOper())
221         {
222                 if (noisy)
223                         this->WriteNotice("You are not an oper");
224                 return false;
225         }
226
227         if (oper->AllowedPrivs.find(privstr) != oper->AllowedPrivs.end())
228         {
229                 return true;
230         }
231         else if (oper->AllowedPrivs.find("*") != oper->AllowedPrivs.end())
232         {
233                 return true;
234         }
235
236         if (noisy)
237                 this->WriteNotice("Oper type " + oper->name + " does not have access to priv " + privstr);
238
239         return false;
240 }
241
242 void UserIOHandler::OnDataReady()
243 {
244         if (user->quitting)
245                 return;
246
247         if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
248         {
249                 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
250                 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
251                         user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
252                 return;
253         }
254         unsigned long sendqmax = ULONG_MAX;
255         if (!user->HasPrivPermission("users/flood/increased-buffers"))
256                 sendqmax = user->MyClass->GetSendqSoftMax();
257         unsigned long penaltymax = ULONG_MAX;
258         if (!user->HasPrivPermission("users/flood/no-fakelag"))
259                 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
260
261         while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
262         {
263                 std::string line;
264                 line.reserve(ServerInstance->Config->Limits.MaxLine);
265                 std::string::size_type qpos = 0;
266                 while (qpos < recvq.length())
267                 {
268                         char c = recvq[qpos++];
269                         switch (c)
270                         {
271                         case '\0':
272                                 c = ' ';
273                                 break;
274                         case '\r':
275                                 continue;
276                         case '\n':
277                                 goto eol_found;
278                         }
279                         if (line.length() < ServerInstance->Config->Limits.MaxLine - 2)
280                                 line.push_back(c);
281                 }
282                 // if we got here, the recvq ran out before we found a newline
283                 return;
284 eol_found:
285                 // just found a newline. Terminate the string, and pull it out of recvq
286                 recvq = recvq.substr(qpos);
287
288                 // TODO should this be moved to when it was inserted in recvq?
289                 ServerInstance->stats->statsRecv += qpos;
290                 user->bytes_in += qpos;
291                 user->cmds_in++;
292
293                 ServerInstance->Parser->ProcessBuffer(line, user);
294                 if (user->quitting)
295                         return;
296         }
297         if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
298                 ServerInstance->Users->QuitUser(user, "Excess Flood");
299 }
300
301 void UserIOHandler::AddWriteBuf(const std::string &data)
302 {
303         if (user->quitting_sendq)
304                 return;
305         if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
306                 !user->HasPrivPermission("users/flood/increased-buffers"))
307         {
308                 user->quitting_sendq = true;
309                 ServerInstance->GlobalCulls.AddSQItem(user);
310                 return;
311         }
312
313         // We still want to append data to the sendq of a quitting user,
314         // e.g. their ERROR message that says 'closing link'
315
316         WriteData(data);
317 }
318
319 void UserIOHandler::OnError(BufferedSocketError)
320 {
321         ServerInstance->Users->QuitUser(user, getError());
322 }
323
324 CullResult User::cull()
325 {
326         if (!quitting)
327                 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
328         PurgeEmptyChannels();
329
330         if (client_sa.sa.sa_family != AF_UNSPEC)
331                 ServerInstance->Users->RemoveCloneCounts(this);
332
333         return Extensible::cull();
334 }
335
336 CullResult LocalUser::cull()
337 {
338         ServerInstance->Users->local_users.erase(this);
339         ClearInvites();
340         eh.cull();
341         return User::cull();
342 }
343
344 CullResult FakeUser::cull()
345 {
346         // Fake users don't quit, they just get culled.
347         quitting = true;
348         // Fake users are not inserted into UserManager::clientlist, they're only in the uuidlist
349         ServerInstance->Users->uuidlist->erase(uuid);
350         return User::cull();
351 }
352
353 void User::Oper(OperInfo* info)
354 {
355         ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
356         if (this->IsModeSet(opermh))
357                 this->UnOper();
358
359         this->SetMode(opermh, true);
360         this->oper = info;
361         this->WriteServ("MODE %s :+o", this->nick.c_str());
362         FOREACH_MOD(OnOper, (this, info->name));
363
364         std::string opername;
365         if (info->oper_block)
366                 opername = info->oper_block->getString("name");
367
368         if (IS_LOCAL(this))
369         {
370                 LocalUser* l = IS_LOCAL(this);
371                 std::string vhost = oper->getConfig("vhost");
372                 if (!vhost.empty())
373                         l->ChangeDisplayedHost(vhost.c_str());
374                 std::string opClass = oper->getConfig("class");
375                 if (!opClass.empty())
376                         l->SetClass(opClass);
377         }
378
379         ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
380                 nick.c_str(), ident.c_str(), host.c_str(), oper->name.c_str(), opername.c_str());
381         this->WriteNumeric(RPL_YOUAREOPER, ":You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str());
382
383         ServerInstance->Logs->Log("OPER", LOG_DEFAULT, "%s opered as type: %s", GetFullRealHost().c_str(), oper->name.c_str());
384         ServerInstance->Users->all_opers.push_back(this);
385
386         // Expand permissions from config for faster lookup
387         if (IS_LOCAL(this))
388                 oper->init();
389
390         FOREACH_MOD(OnPostOper, (this, oper->name, opername));
391 }
392
393 void OperInfo::init()
394 {
395         AllowedOperCommands.clear();
396         AllowedPrivs.clear();
397         AllowedUserModes.reset();
398         AllowedChanModes.reset();
399         AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
400
401         for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
402         {
403                 ConfigTag* tag = *iter;
404                 std::string mycmd, mypriv;
405                 /* Process commands */
406                 irc::spacesepstream CommandList(tag->getString("commands"));
407                 while (CommandList.GetToken(mycmd))
408                 {
409                         AllowedOperCommands.insert(mycmd);
410                 }
411
412                 irc::spacesepstream PrivList(tag->getString("privs"));
413                 while (PrivList.GetToken(mypriv))
414                 {
415                         AllowedPrivs.insert(mypriv);
416                 }
417
418                 std::string modes = tag->getString("usermodes");
419                 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
420                 {
421                         if (*c == '*')
422                         {
423                                 this->AllowedUserModes.set();
424                         }
425                         else if (*c >= 'A' && *c < 'z')
426                         {
427                                 this->AllowedUserModes[*c - 'A'] = true;
428                         }
429                 }
430
431                 modes = tag->getString("chanmodes");
432                 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
433                 {
434                         if (*c == '*')
435                         {
436                                 this->AllowedChanModes.set();
437                         }
438                         else if (*c >= 'A' && *c < 'z')
439                         {
440                                 this->AllowedChanModes[*c - 'A'] = true;
441                         }
442                 }
443         }
444 }
445
446 void User::UnOper()
447 {
448         if (!this->IsOper())
449                 return;
450
451         /*
452          * unset their oper type (what IS_OPER checks).
453          * note, order is important - this must come before modes as -o attempts
454          * to call UnOper. -- w00t
455          */
456         oper = NULL;
457
458
459         /* Remove all oper only modes from the user when the deoper - Bug #466*/
460         std::string moderemove("-");
461
462         for (unsigned char letter = 'A'; letter <= 'z'; letter++)
463         {
464                 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
465                 if (mh && mh->NeedsOper())
466                         moderemove += letter;
467         }
468
469
470         std::vector<std::string> parameters;
471         parameters.push_back(this->nick);
472         parameters.push_back(moderemove);
473
474         ServerInstance->Modes->Process(parameters, this);
475
476         /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
477         ServerInstance->Users->all_opers.remove(this);
478
479         ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
480         this->SetMode(opermh, false);
481 }
482
483 /*
484  * Check class restrictions
485  */
486 void LocalUser::CheckClass(bool clone_count)
487 {
488         ConnectClass* a = this->MyClass;
489
490         if (!a)
491         {
492                 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
493                 return;
494         }
495         else if (a->type == CC_DENY)
496         {
497                 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection"));
498                 return;
499         }
500         else if (clone_count)
501         {
502                 if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
503                 {
504                         ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
505                         if (a->maxconnwarn)
506                                 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString().c_str());
507                         return;
508                 }
509                 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
510                 {
511                         ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
512                         if (a->maxconnwarn)
513                                 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString().c_str());
514                         return;
515                 }
516         }
517
518         this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
519 }
520
521 bool LocalUser::CheckLines(bool doZline)
522 {
523         const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
524
525         if (!this->exempt)
526         {
527                 for (int n = 0; check[n]; ++n)
528                 {
529                         XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
530
531                         if (r)
532                         {
533                                 r->Apply(this);
534                                 return true;
535                         }
536                 }
537         }
538
539         return false;
540 }
541
542 void LocalUser::FullConnect()
543 {
544         ServerInstance->stats->statsConnects++;
545         this->idle_lastmsg = ServerInstance->Time();
546
547         /*
548          * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
549          * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
550          * may put the user into a totally seperate class with different restrictions! so we *must* check again.
551          * Don't remove this! -- w00t
552          */
553         MyClass = NULL;
554         SetClass();
555         CheckClass();
556         CheckLines();
557
558         if (quitting)
559                 return;
560
561         this->WriteNumeric(RPL_WELCOME, ":Welcome to the %s IRC Network %s", ServerInstance->Config->Network.c_str(), GetFullRealHost().c_str());
562         this->WriteNumeric(RPL_YOURHOSTIS, ":Your host is %s, running version %s", ServerInstance->Config->ServerName.c_str(), BRANCH);
563         this->WriteNumeric(RPL_SERVERCREATED, ":This server was created %s %s", __TIME__, __DATE__);
564
565         const std::string& modelist = ServerInstance->Modes->GetModeListFor004Numeric();
566         this->WriteNumeric(RPL_SERVERVERSION, "%s %s %s", ServerInstance->Config->ServerName.c_str(), BRANCH, modelist.c_str());
567
568         ServerInstance->ISupport.SendTo(this);
569
570         /* Now registered */
571         if (ServerInstance->Users->unregistered_count)
572                 ServerInstance->Users->unregistered_count--;
573
574         /* Trigger MOTD and LUSERS output, give modules a chance too */
575         ModResult MOD_RESULT;
576         std::string command("LUSERS");
577         std::vector<std::string> parameters;
578         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, command));
579         if (!MOD_RESULT)
580                 ServerInstance->Parser->CallHandler(command, parameters, this);
581
582         MOD_RESULT = MOD_RES_PASSTHRU;
583         command = "MOTD";
584         FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, command));
585         if (!MOD_RESULT)
586                 ServerInstance->Parser->CallHandler(command, parameters, this);
587
588         if (ServerInstance->Config->RawLog)
589                 WriteServ("PRIVMSG %s :*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.", nick.c_str());
590
591         /*
592          * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
593          * for a user that doesn't exist yet.
594          */
595         FOREACH_MOD(OnUserConnect, (this));
596
597         this->registered = REG_ALL;
598
599         FOREACH_MOD(OnPostConnect, (this));
600
601         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
602                 this->GetServerPort(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->fullname.c_str());
603         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
604         ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
605         // reset the flood penalty (which could have been raised due to things like auto +x)
606         CommandFloodPenalty = 0;
607 }
608
609 void User::InvalidateCache()
610 {
611         /* Invalidate cache */
612         cached_fullhost.clear();
613         cached_hostip.clear();
614         cached_makehost.clear();
615         cached_fullrealhost.clear();
616 }
617
618 bool User::ChangeNick(const std::string& newnick, bool force)
619 {
620         if (quitting)
621         {
622                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
623                 return false;
624         }
625
626         if (!force)
627         {
628                 ModResult MOD_RESULT;
629                 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
630
631                 if (MOD_RESULT == MOD_RES_DENY)
632                 {
633                         ServerInstance->stats->statsCollisions++;
634                         return false;
635                 }
636         }
637
638         if (assign(newnick) == assign(nick))
639         {
640                 // case change, don't need to check Q:lines and such
641                 // and, if it's identical including case, we can leave right now
642                 if (newnick == nick)
643                         return true;
644         }
645         else
646         {
647                 /*
648                  * Don't check Q:Lines if it's a server-enforced change, just on the off-chance some fucking *moron*
649                  * tries to Q:Line SIDs, also, this means we just get our way period, as it really should be.
650                  * Thanks Kein for finding this. -- w00t
651                  *
652                  * Also don't check Q:Lines for remote nickchanges, they should have our Q:Lines anyway to enforce themselves.
653                  *              -- w00t
654                  */
655                 if (IS_LOCAL(this) && !force)
656                 {
657                         XLine* mq = ServerInstance->XLines->MatchesLine("Q",newnick);
658                         if (mq)
659                         {
660                                 if (this->registered == REG_ALL)
661                                 {
662                                         ServerInstance->SNO->WriteGlobalSno('a', "Q-Lined nickname %s from %s: %s",
663                                                 newnick.c_str(), GetFullRealHost().c_str(), mq->reason.c_str());
664                                 }
665                                 this->WriteNumeric(ERR_ERRONEUSNICKNAME, "%s :Invalid nickname: %s", newnick.c_str(), mq->reason.c_str());
666                                 return false;
667                         }
668
669                         if (ServerInstance->Config->RestrictBannedUsers)
670                         {
671                                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
672                                 {
673                                         Channel* chan = (*i)->chan;
674                                         if (chan->GetPrefixValue(this) < VOICE_VALUE && chan->IsBanned(this))
675                                         {
676                                                 this->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Cannot send to channel (you're banned)", chan->name.c_str());
677                                                 return false;
678                                         }
679                                 }
680                         }
681                 }
682
683                 /*
684                  * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
685                  * then we have a potential collide. Check whether someone else is camping on the nick
686                  * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
687                  * camper to their UID, and allow the incoming nick change.
688                  *
689                  * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
690                  * because the nick is already (rightfully) in use. -- w00t
691                  */
692                 User* InUse = ServerInstance->FindNickOnly(newnick);
693                 if (InUse && (InUse != this))
694                 {
695                         if (InUse->registered != REG_ALL)
696                         {
697                                 /* force the camper to their UUID, and ask them to re-send a NICK. */
698                                 InUse->WriteTo(InUse, "NICK %s", InUse->uuid.c_str());
699                                 InUse->WriteNumeric(ERR_NICKNAMEINUSE, "%s :Nickname overruled.", InUse->nick.c_str());
700
701                                 ServerInstance->Users->clientlist->erase(InUse->nick);
702                                 (*(ServerInstance->Users->clientlist))[InUse->uuid] = InUse;
703
704                                 InUse->nick = InUse->uuid;
705                                 InUse->InvalidateCache();
706                                 InUse->registered &= ~REG_NICK;
707                         }
708                         else
709                         {
710                                 /* No camping, tell the incoming user  to stop trying to change nick ;p */
711                                 this->WriteNumeric(ERR_NICKNAMEINUSE, "%s :Nickname is already in use.", newnick.c_str());
712                                 return false;
713                         }
714                 }
715         }
716
717         if (this->registered == REG_ALL)
718                 this->WriteCommon("NICK %s",newnick.c_str());
719         std::string oldnick = nick;
720         nick = newnick;
721
722         InvalidateCache();
723         ServerInstance->Users->clientlist->erase(oldnick);
724         (*(ServerInstance->Users->clientlist))[newnick] = this;
725
726         if (registered == REG_ALL)
727                 FOREACH_MOD(OnUserPostNick, (this,oldnick));
728
729         return true;
730 }
731
732 int LocalUser::GetServerPort()
733 {
734         switch (this->server_sa.sa.sa_family)
735         {
736                 case AF_INET6:
737                         return htons(this->server_sa.in6.sin6_port);
738                 case AF_INET:
739                         return htons(this->server_sa.in4.sin_port);
740         }
741         return 0;
742 }
743
744 const std::string& User::GetIPString()
745 {
746         int port;
747         if (cachedip.empty())
748         {
749                 irc::sockets::satoap(client_sa, cachedip, port);
750                 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
751                 if (cachedip[0] == ':')
752                         cachedip.insert(cachedip.begin(),1,'0');
753         }
754
755         return cachedip;
756 }
757
758 irc::sockets::cidr_mask User::GetCIDRMask()
759 {
760         int range = 0;
761         switch (client_sa.sa.sa_family)
762         {
763                 case AF_INET6:
764                         range = ServerInstance->Config->c_ipv6_range;
765                         break;
766                 case AF_INET:
767                         range = ServerInstance->Config->c_ipv4_range;
768                         break;
769         }
770         return irc::sockets::cidr_mask(client_sa, range);
771 }
772
773 bool User::SetClientIP(const char* sip, bool recheck_eline)
774 {
775         cachedip.clear();
776         cached_hostip.clear();
777         return irc::sockets::aptosa(sip, 0, client_sa);
778 }
779
780 void User::SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline)
781 {
782         cachedip.clear();
783         cached_hostip.clear();
784         memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
785 }
786
787 bool LocalUser::SetClientIP(const char* sip, bool recheck_eline)
788 {
789         irc::sockets::sockaddrs sa;
790         if (!irc::sockets::aptosa(sip, 0, sa))
791                 // Invalid
792                 return false;
793
794         LocalUser::SetClientIP(sa, recheck_eline);
795         return true;
796 }
797
798 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline)
799 {
800         if (sa != client_sa)
801         {
802                 User::SetClientIP(sa);
803                 if (recheck_eline)
804                         this->exempt = (ServerInstance->XLines->MatchesLine("E", this) != NULL);
805
806                 FOREACH_MOD(OnSetUserIP, (this));
807         }
808 }
809
810 static std::string wide_newline("\r\n");
811
812 void User::Write(const std::string& text)
813 {
814 }
815
816 void User::Write(const char *text, ...)
817 {
818 }
819
820 void LocalUser::Write(const std::string& text)
821 {
822         if (!ServerInstance->SE->BoundsCheckFd(&eh))
823                 return;
824
825         if (text.length() > ServerInstance->Config->Limits.MaxLine - 2)
826         {
827                 // this should happen rarely or never. Crop the string at 512 and try again.
828                 std::string try_again = text.substr(0, ServerInstance->Config->Limits.MaxLine - 2);
829                 Write(try_again);
830                 return;
831         }
832
833         ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %s", uuid.c_str(), text.c_str());
834
835         eh.AddWriteBuf(text);
836         eh.AddWriteBuf(wide_newline);
837
838         ServerInstance->stats->statsSent += text.length() + 2;
839         this->bytes_out += text.length() + 2;
840         this->cmds_out++;
841 }
842
843 /** Write()
844  */
845 void LocalUser::Write(const char *text, ...)
846 {
847         std::string textbuffer;
848         VAFORMAT(textbuffer, text, text);
849         this->Write(textbuffer);
850 }
851
852 void User::WriteServ(const std::string& text)
853 {
854         this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
855 }
856
857 /** WriteServ()
858  *  Same as Write(), except `text' is prefixed with `:server.name '.
859  */
860 void User::WriteServ(const char* text, ...)
861 {
862         std::string textbuffer;
863         VAFORMAT(textbuffer, text, text);
864         this->WriteServ(textbuffer);
865 }
866
867 void User::WriteNotice(const std::string& text)
868 {
869         this->WriteServ("NOTICE " + (this->registered == REG_ALL ? this->nick : "*") + " :" + text);
870 }
871
872 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
873 {
874         std::string textbuffer;
875         VAFORMAT(textbuffer, text, text);
876         this->WriteNumeric(numeric, textbuffer);
877 }
878
879 void User::WriteNumeric(unsigned int numeric, const std::string &text)
880 {
881         ModResult MOD_RESULT;
882
883         FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
884
885         if (MOD_RESULT == MOD_RES_DENY)
886                 return;
887
888         const std::string message = InspIRCd::Format(":%s %03u %s %s", ServerInstance->Config->ServerName.c_str(),
889                 numeric, !this->nick.empty() ? this->nick.c_str() : "*", text.c_str());
890         this->Write(message);
891 }
892
893 void User::WriteFrom(User *user, const std::string &text)
894 {
895         const std::string message = ":" + user->GetFullHost() + " " + text;
896         this->Write(message);
897 }
898
899
900 /* write text from an originating user to originating user */
901
902 void User::WriteFrom(User *user, const char* text, ...)
903 {
904         std::string textbuffer;
905         VAFORMAT(textbuffer, text, text);
906         this->WriteFrom(user, textbuffer);
907 }
908
909
910 /* write text to an destination user from a source user (e.g. user privmsg) */
911
912 void User::WriteTo(User *dest, const char *data, ...)
913 {
914         std::string textbuffer;
915         VAFORMAT(textbuffer, data, data);
916         this->WriteTo(dest, textbuffer);
917 }
918
919 void User::WriteTo(User *dest, const std::string &data)
920 {
921         dest->WriteFrom(this, data);
922 }
923
924 void User::WriteCommon(const char* text, ...)
925 {
926         if (this->registered != REG_ALL || quitting)
927                 return;
928
929         std::string textbuffer;
930         VAFORMAT(textbuffer, text, text);
931         textbuffer = ":" + this->GetFullHost() + " " + textbuffer;
932         this->WriteCommonRaw(textbuffer, true);
933 }
934
935 void User::WriteCommonExcept(const char* text, ...)
936 {
937         if (this->registered != REG_ALL || quitting)
938                 return;
939
940         std::string textbuffer;
941         VAFORMAT(textbuffer, text, text);
942         textbuffer = ":" + this->GetFullHost() + " " + textbuffer;
943         this->WriteCommonRaw(textbuffer, false);
944 }
945
946 void User::WriteCommonRaw(const std::string &line, bool include_self)
947 {
948         if (this->registered != REG_ALL || quitting)
949                 return;
950
951         LocalUser::already_sent_id++;
952
953         IncludeChanList include_c(chans.begin(), chans.end());
954         std::map<User*,bool> exceptions;
955
956         exceptions[this] = include_self;
957
958         FOREACH_MOD(OnBuildNeighborList, (this, include_c, exceptions));
959
960         for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
961         {
962                 LocalUser* u = IS_LOCAL(i->first);
963                 if (u && !u->quitting)
964                 {
965                         u->already_sent = LocalUser::already_sent_id;
966                         if (i->second)
967                                 u->Write(line);
968                 }
969         }
970         for (IncludeChanList::const_iterator v = include_c.begin(); v != include_c.end(); ++v)
971         {
972                 Channel* c = (*v)->chan;
973                 const UserMembList* ulist = c->GetUsers();
974                 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
975                 {
976                         LocalUser* u = IS_LOCAL(i->first);
977                         if (u && !u->quitting && u->already_sent != LocalUser::already_sent_id)
978                         {
979                                 u->already_sent = LocalUser::already_sent_id;
980                                 u->Write(line);
981                         }
982                 }
983         }
984 }
985
986 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
987 {
988         if (this->registered != REG_ALL)
989                 return;
990
991         already_sent_t uniq_id = ++LocalUser::already_sent_id;
992
993         const std::string normalMessage = ":" + this->GetFullHost() + " QUIT :" + normal_text;
994         const std::string operMessage = ":" + this->GetFullHost() + " QUIT :" + oper_text;
995
996         IncludeChanList include_c(chans.begin(), chans.end());
997         std::map<User*,bool> exceptions;
998
999         FOREACH_MOD(OnBuildNeighborList, (this, include_c, exceptions));
1000
1001         for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1002         {
1003                 LocalUser* u = IS_LOCAL(i->first);
1004                 if (u && !u->quitting)
1005                 {
1006                         u->already_sent = uniq_id;
1007                         if (i->second)
1008                                 u->Write(u->IsOper() ? operMessage : normalMessage);
1009                 }
1010         }
1011         for (IncludeChanList::const_iterator v = include_c.begin(); v != include_c.end(); ++v)
1012         {
1013                 const UserMembList* ulist = (*v)->chan->GetUsers();
1014                 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1015                 {
1016                         LocalUser* u = IS_LOCAL(i->first);
1017                         if (u && !u->quitting && (u->already_sent != uniq_id))
1018                         {
1019                                 u->already_sent = uniq_id;
1020                                 u->Write(u->IsOper() ? operMessage : normalMessage);
1021                         }
1022                 }
1023         }
1024 }
1025
1026 void LocalUser::SendText(const std::string& line)
1027 {
1028         Write(line);
1029 }
1030
1031 void RemoteUser::SendText(const std::string& line)
1032 {
1033         ServerInstance->PI->PushToClient(this, line);
1034 }
1035
1036 void FakeUser::SendText(const std::string& line)
1037 {
1038 }
1039
1040 void User::SendText(const char *text, ...)
1041 {
1042         std::string line;
1043         VAFORMAT(line, text, text);
1044         SendText(line);
1045 }
1046
1047 void User::SendText(const std::string& linePrefix, std::stringstream& textStream)
1048 {
1049         std::string line;
1050         std::string word;
1051         while (textStream >> word)
1052         {
1053                 size_t lineLength = linePrefix.length() + line.length() + word.length() + 3; // "\s\n\r"
1054                 if (lineLength > ServerInstance->Config->Limits.MaxLine)
1055                 {
1056                         SendText(linePrefix + line);
1057                         line.clear();
1058                 }
1059                 line += " " + word;
1060         }
1061         SendText(linePrefix + line);
1062 }
1063
1064 /* return 0 or 1 depending if users u and u2 share one or more common channels
1065  * (used by QUIT, NICK etc which arent channel specific notices)
1066  *
1067  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1068  * the first users channels then the second users channels within the outer loop,
1069  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1070  * all possible iterations). However this new function instead checks against the
1071  * channel's userlist in the inner loop which is a std::map<User*,User*>
1072  * and saves us time as we already know what pointer value we are after.
1073  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1074  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1075  */
1076 bool User::SharesChannelWith(User *other)
1077 {
1078         if ((this->registered != REG_ALL) || (other->registered != REG_ALL))
1079                 return false;
1080
1081         /* Outer loop */
1082         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1083         {
1084                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1085                  * by replacing it with a map::find which *should* be more efficient
1086                  */
1087                 if ((*i)->chan->HasUser(other))
1088                         return true;
1089         }
1090         return false;
1091 }
1092
1093 bool User::ChangeName(const std::string& gecos)
1094 {
1095         if (!this->fullname.compare(gecos))
1096                 return true;
1097
1098         if (IS_LOCAL(this))
1099         {
1100                 ModResult MOD_RESULT;
1101                 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (IS_LOCAL(this),gecos));
1102                 if (MOD_RESULT == MOD_RES_DENY)
1103                         return false;
1104                 FOREACH_MOD(OnChangeName, (this,gecos));
1105         }
1106         this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1107
1108         return true;
1109 }
1110
1111 bool User::ChangeDisplayedHost(const std::string& shost)
1112 {
1113         if (dhost == shost)
1114                 return true;
1115
1116         if (IS_LOCAL(this))
1117         {
1118                 ModResult MOD_RESULT;
1119                 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (IS_LOCAL(this),shost));
1120                 if (MOD_RESULT == MOD_RES_DENY)
1121                         return false;
1122         }
1123
1124         FOREACH_MOD(OnChangeHost, (this,shost));
1125
1126         this->dhost.assign(shost, 0, 64);
1127         this->InvalidateCache();
1128
1129         if (IS_LOCAL(this))
1130                 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s :is now your displayed host", this->dhost.c_str());
1131
1132         return true;
1133 }
1134
1135 bool User::ChangeIdent(const std::string& newident)
1136 {
1137         if (this->ident == newident)
1138                 return true;
1139
1140         FOREACH_MOD(OnChangeIdent, (this,newident));
1141
1142         this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1143         this->InvalidateCache();
1144
1145         return true;
1146 }
1147
1148 void User::SendAll(const char* command, const char* text, ...)
1149 {
1150         std::string textbuffer;
1151         VAFORMAT(textbuffer, text, text);
1152         const std::string message = ":" + this->GetFullHost() + " " + command + " $* :" + textbuffer;
1153
1154         for (LocalUserList::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1155         {
1156                 if ((*i)->registered == REG_ALL)
1157                         (*i)->Write(message);
1158         }
1159 }
1160
1161 /*
1162  * Sets a user's connection class.
1163  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1164  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1165  * then their ip will be taken as 'priority' anyway, so for example,
1166  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1167  */
1168 void LocalUser::SetClass(const std::string &explicit_name)
1169 {
1170         ConnectClass *found = NULL;
1171
1172         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1173
1174         if (!explicit_name.empty())
1175         {
1176                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1177                 {
1178                         ConnectClass* c = *i;
1179
1180                         if (explicit_name == c->name)
1181                         {
1182                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Explicitly set to %s", explicit_name.c_str());
1183                                 found = c;
1184                         }
1185                 }
1186         }
1187         else
1188         {
1189                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1190                 {
1191                         ConnectClass* c = *i;
1192                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking %s", c->GetName().c_str());
1193
1194                         ModResult MOD_RESULT;
1195                         FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1196                         if (MOD_RESULT == MOD_RES_DENY)
1197                                 continue;
1198                         if (MOD_RESULT == MOD_RES_ALLOW)
1199                         {
1200                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class forced by module to %s", c->GetName().c_str());
1201                                 found = c;
1202                                 break;
1203                         }
1204
1205                         if (c->type == CC_NAMED)
1206                                 continue;
1207
1208                         bool regdone = (registered != REG_NONE);
1209                         if (c->config->getBool("registered", regdone) != regdone)
1210                                 continue;
1211
1212                         /* check if host matches.. */
1213                         if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1214                             !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1215                         {
1216                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "No host match (for %s)", c->GetHost().c_str());
1217                                 continue;
1218                         }
1219
1220                         /*
1221                          * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1222                          * because we should attempt to find another class if this one doesn't match us. -- w00t
1223                          */
1224                         if (c->limit && (c->GetReferenceCount() >= c->limit))
1225                         {
1226                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1227                                 continue;
1228                         }
1229
1230                         /* if it requires a port ... */
1231                         int port = c->config->getInt("port");
1232                         if (port)
1233                         {
1234                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Requires port (%d)", port);
1235
1236                                 /* and our port doesn't match, fail. */
1237                                 if (this->GetServerPort() != port)
1238                                         continue;
1239                         }
1240
1241                         if (regdone && !c->config->getString("password").empty())
1242                         {
1243                                 if (ServerInstance->PassCompare(this, c->config->getString("password"), password, c->config->getString("hash")))
1244                                 {
1245                                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Bad password, skipping");
1246                                         continue;
1247                                 }
1248                         }
1249
1250                         /* we stop at the first class that meets ALL critera. */
1251                         found = c;
1252                         break;
1253                 }
1254         }
1255
1256         /*
1257          * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1258          */
1259         if (found)
1260         {
1261                 MyClass = found;
1262         }
1263 }
1264
1265 void User::PurgeEmptyChannels()
1266 {
1267         // firstly decrement the count on each channel
1268         for (UCListIter i = this->chans.begin(); i != this->chans.end(); )
1269         {
1270                 Channel* c = (*i)->chan;
1271                 ++i;
1272                 c->DelUser(this);
1273         }
1274
1275         this->UnOper();
1276 }
1277
1278 const std::string& FakeUser::GetFullHost()
1279 {
1280         if (!ServerInstance->Config->HideWhoisServer.empty())
1281                 return ServerInstance->Config->HideWhoisServer;
1282         return server->GetName();
1283 }
1284
1285 const std::string& FakeUser::GetFullRealHost()
1286 {
1287         if (!ServerInstance->Config->HideWhoisServer.empty())
1288                 return ServerInstance->Config->HideWhoisServer;
1289         return server->GetName();
1290 }
1291
1292 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1293         : config(tag), type(t), fakelag(true), name("unnamed"), registration_timeout(0), host(mask),
1294         pingtime(0), softsendqmax(0), hardsendqmax(0), recvqmax(0),
1295         penaltythreshold(0), commandrate(0), maxlocal(0), maxglobal(0), maxconnwarn(true), maxchans(0),
1296         limit(0), resolvehostnames(true)
1297 {
1298 }
1299
1300 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1301         : config(tag), type(t), fakelag(parent.fakelag), name("unnamed"),
1302         registration_timeout(parent.registration_timeout), host(mask), pingtime(parent.pingtime),
1303         softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax), recvqmax(parent.recvqmax),
1304         penaltythreshold(parent.penaltythreshold), commandrate(parent.commandrate),
1305         maxlocal(parent.maxlocal), maxglobal(parent.maxglobal), maxconnwarn(parent.maxconnwarn), maxchans(parent.maxchans),
1306         limit(parent.limit), resolvehostnames(parent.resolvehostnames)
1307 {
1308 }
1309
1310 void ConnectClass::Update(const ConnectClass* src)
1311 {
1312         config = src->config;
1313         type = src->type;
1314         fakelag = src->fakelag;
1315         name = src->name;
1316         registration_timeout = src->registration_timeout;
1317         host = src->host;
1318         pingtime = src->pingtime;
1319         softsendqmax = src->softsendqmax;
1320         hardsendqmax = src->hardsendqmax;
1321         recvqmax = src->recvqmax;
1322         penaltythreshold = src->penaltythreshold;
1323         commandrate = src->commandrate;
1324         maxlocal = src->maxlocal;
1325         maxglobal = src->maxglobal;
1326         maxconnwarn = src->maxconnwarn;
1327         maxchans = src->maxchans;
1328         limit = src->limit;
1329         resolvehostnames = src->resolvehostnames;
1330 }