]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
First UserManager overhaul: Move clone counts out of InspIRCd & User.
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDusers */
15
16 #include "inspircd.h"
17 #include <stdarg.h>
18 #include "socketengine.h"
19 #include "wildcard.h"
20 #include "xline.h"
21 #include "bancache.h"
22 #include "commands/cmd_whowas.h"
23
24 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
25
26 /* XXX: Used for speeding up WriteCommon operations */
27 unsigned long uniq_id = 0;
28
29 std::string User::ProcessNoticeMasks(const char *sm)
30 {
31         bool adding = true, oldadding = false;
32         const char *c = sm;
33         std::string output;
34
35         while (c && *c)
36         {
37                 switch (*c)
38                 {
39                         case '+':
40                                 adding = true;
41                         break;
42                         case '-':
43                                 adding = false;
44                         break;
45                         case '*':
46                                 for (unsigned char d = 'A'; d <= 'z'; d++)
47                                 {
48                                         if (ServerInstance->SNO->IsEnabled(d))
49                                         {
50                                                 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
51                                                 {
52                                                         if ((oldadding != adding) || (!output.length()))
53                                                                 output += (adding ? '+' : '-');
54
55                                                         this->SetNoticeMask(d, adding);
56
57                                                         output += d;
58                                                 }
59                                         }
60                                         oldadding = adding;
61                                 }
62                         break;
63                         default:
64                                 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
65                                 {
66                                         if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
67                                         {
68                                                 if ((oldadding != adding) || (!output.length()))
69                                                         output += (adding ? '+' : '-');
70
71                                                 this->SetNoticeMask(*c, adding);
72
73                                                 output += *c;
74                                         }
75                                 }
76                                 oldadding = adding;
77                         break;
78                 }
79
80                 *c++;
81         }
82
83         return output;
84 }
85
86 void User::StartDNSLookup()
87 {
88         try
89         {
90                 bool cached;
91                 const char* ip = this->GetIPString();
92
93                 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
94                 if (!strncmp(ip, "0::ffff:", 8))
95                         res_reverse = new UserResolver(this->ServerInstance, this, ip + 8, DNS_QUERY_PTR4, cached);
96                 else
97                         res_reverse = new UserResolver(this->ServerInstance, this, ip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
98
99                 this->ServerInstance->AddResolver(res_reverse, cached);
100         }
101         catch (CoreException& e)
102         {
103                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
104         }
105 }
106
107 bool User::IsNoticeMaskSet(unsigned char sm)
108 {
109         return (snomasks[sm-65]);
110 }
111
112 void User::SetNoticeMask(unsigned char sm, bool value)
113 {
114         snomasks[sm-65] = value;
115 }
116
117 const char* User::FormatNoticeMasks()
118 {
119         static char data[MAXBUF];
120         int offset = 0;
121
122         for (int n = 0; n < 64; n++)
123         {
124                 if (snomasks[n])
125                         data[offset++] = n+65;
126         }
127
128         data[offset] = 0;
129         return data;
130 }
131
132
133
134 bool User::IsModeSet(unsigned char m)
135 {
136         return (modes[m-65]);
137 }
138
139 void User::SetMode(unsigned char m, bool value)
140 {
141         modes[m-65] = value;
142 }
143
144 const char* User::FormatModes()
145 {
146         static char data[MAXBUF];
147         int offset = 0;
148         for (int n = 0; n < 64; n++)
149         {
150                 if (modes[n])
151                         data[offset++] = n+65;
152         }
153         data[offset] = 0;
154         return data;
155 }
156
157 void User::DecrementModes()
158 {
159         ServerInstance->Log(DEBUG,"DecrementModes()");
160         for (unsigned char n = 'A'; n <= 'z'; n++)
161         {
162                 if (modes[n-65])
163                 {
164                         ServerInstance->Log(DEBUG,"DecrementModes() found mode %c", n);
165                         ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
166                         if (mh)
167                         {
168                                 ServerInstance->Log(DEBUG,"Found handler %c and call ChangeCount", n);
169                                 mh->ChangeCount(-1);
170                         }
171                 }
172         }
173 }
174
175 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
176 {
177         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
178         server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
179         reset_due = ServerInstance->Time();
180         age = ServerInstance->Time(true);
181         Penalty = 0;
182         lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
183         ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
184         OverPenalty = ExemptFromPenalty = muted = exempt = haspassed = dns_done = false;
185         fd = -1;
186         recvq.clear();
187         sendq.clear();
188         WriteError.clear();
189         res_forward = res_reverse = NULL;
190         Visibility = NULL;
191         ip = NULL;
192         MyClass = NULL;
193         AllowedOperCommands = NULL;
194         chans.clear();
195         invites.clear();
196         memset(modes,0,sizeof(modes));
197         memset(snomasks,0,sizeof(snomasks));
198         /* Invalidate cache */
199         operquit = cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
200
201         if (uid.empty())
202                 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
203         else
204                 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
205
206         ServerInstance->Log(DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
207
208         user_hash::iterator finduuid = Instance->uuidlist->find(uuid);
209         if (finduuid == Instance->uuidlist->end())
210                 (*Instance->uuidlist)[uuid] = this;
211         else
212                 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
213 }
214
215 User::~User()
216 {
217         /* NULL for remote users :) */
218         if (this->MyClass)
219         {
220                 this->MyClass->RefCount--;
221                 ServerInstance->Log(DEBUG, "User destructor -- connect refcount now: %u", this->MyClass->RefCount);
222         }
223         if (this->AllowedOperCommands)
224         {
225                 delete AllowedOperCommands;
226                 AllowedOperCommands = NULL;
227         }
228
229         this->InvalidateCache();
230         this->DecrementModes();
231         if (operquit)
232                 free(operquit);
233         if (ip)
234         {
235                 ServerInstance->Users->RemoveCloneCounts(this);
236
237                 if (this->GetProtocolFamily() == AF_INET)
238                 {
239                         delete (sockaddr_in*)ip;
240                 }
241 #ifdef SUPPORT_IP6LINKS
242                 else
243                 {
244                         delete (sockaddr_in6*)ip;
245                 }
246 #endif
247         }
248
249         ServerInstance->uuidlist->erase(uuid);
250 }
251
252 char* User::MakeHost()
253 {
254         if (this->cached_makehost)
255                 return this->cached_makehost;
256
257         char nhost[MAXBUF];
258         /* This is much faster than snprintf */
259         char* t = nhost;
260         for(char* n = ident; *n; n++)
261                 *t++ = *n;
262         *t++ = '@';
263         for(char* n = host; *n; n++)
264                 *t++ = *n;
265         *t = 0;
266
267         this->cached_makehost = strdup(nhost);
268
269         return this->cached_makehost;
270 }
271
272 char* User::MakeHostIP()
273 {
274         if (this->cached_hostip)
275                 return this->cached_hostip;
276
277         char ihost[MAXBUF];
278         /* This is much faster than snprintf */
279         char* t = ihost;
280         for(char* n = ident; *n; n++)
281                 *t++ = *n;
282         *t++ = '@';
283         for(const char* n = this->GetIPString(); *n; n++)
284                 *t++ = *n;
285         *t = 0;
286
287         this->cached_hostip = strdup(ihost);
288
289         return this->cached_hostip;
290 }
291
292 void User::CloseSocket()
293 {
294         ServerInstance->SE->Shutdown(this, 2);
295         ServerInstance->SE->Close(this);
296 }
297
298 char* User::GetFullHost()
299 {
300         if (this->cached_fullhost)
301                 return this->cached_fullhost;
302
303         char result[MAXBUF];
304         char* t = result;
305         for(char* n = nick; *n; n++)
306                 *t++ = *n;
307         *t++ = '!';
308         for(char* n = ident; *n; n++)
309                 *t++ = *n;
310         *t++ = '@';
311         for(char* n = dhost; *n; n++)
312                 *t++ = *n;
313         *t = 0;
314
315         this->cached_fullhost = strdup(result);
316
317         return this->cached_fullhost;
318 }
319
320 char* User::MakeWildHost()
321 {
322         static char nresult[MAXBUF];
323         char* t = nresult;
324         *t++ = '*';     *t++ = '!';
325         *t++ = '*';     *t++ = '@';
326         for(char* n = dhost; *n; n++)
327                 *t++ = *n;
328         *t = 0;
329         return nresult;
330 }
331
332 int User::ReadData(void* buffer, size_t size)
333 {
334         if (IS_LOCAL(this))
335         {
336 #ifndef WIN32
337                 return read(this->fd, buffer, size);
338 #else
339                 return recv(this->fd, (char*)buffer, size, 0);
340 #endif
341         }
342         else
343                 return 0;
344 }
345
346
347 char* User::GetFullRealHost()
348 {
349         if (this->cached_fullrealhost)
350                 return this->cached_fullrealhost;
351
352         char fresult[MAXBUF];
353         char* t = fresult;
354         for(char* n = nick; *n; n++)
355                 *t++ = *n;
356         *t++ = '!';
357         for(char* n = ident; *n; n++)
358                 *t++ = *n;
359         *t++ = '@';
360         for(char* n = host; *n; n++)
361                 *t++ = *n;
362         *t = 0;
363
364         this->cached_fullrealhost = strdup(fresult);
365
366         return this->cached_fullrealhost;
367 }
368
369 bool User::IsInvited(const irc::string &channel)
370 {
371         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
372         {
373                 if (channel == *i)
374                 {
375                         return true;
376                 }
377         }
378         return false;
379 }
380
381 InvitedList* User::GetInviteList()
382 {
383         return &invites;
384 }
385
386 void User::InviteTo(const irc::string &channel)
387 {
388         invites.push_back(channel);
389 }
390
391 void User::RemoveInvite(const irc::string &channel)
392 {
393         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
394         {
395                 if (channel == *i)
396                 {
397                         invites.erase(i);
398                         return;
399                 }
400         }
401 }
402
403 bool User::HasPermission(const std::string &command)
404 {
405         /*
406          * users on remote servers can completely bypass all permissions based checks.
407          * This prevents desyncs when one server has different type/class tags to another.
408          * That having been said, this does open things up to the possibility of source changes
409          * allowing remote kills, etc - but if they have access to the src, they most likely have
410          * access to the conf - so it's an end to a means either way.
411          */
412         if (!IS_LOCAL(this))
413                 return true;
414
415         // are they even an oper at all?
416         if (!IS_OPER(this))
417         {
418                 return false;
419         }
420
421         if (!AllowedOperCommands)
422                 return false;
423
424         if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
425                 return true;
426         else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
427                 return true;
428
429         return false;
430 }
431
432 /** NOTE: We cannot pass a const reference to this method.
433  * The string is changed by the workings of the method,
434  * so that if we pass const ref, we end up copying it to
435  * something we can change anyway. Makes sense to just let
436  * the compiler do that copy for us.
437  */
438 bool User::AddBuffer(std::string a)
439 {
440         try
441         {
442                 std::string::size_type i = a.rfind('\r');
443
444                 while (i != std::string::npos)
445                 {
446                         a.erase(i, 1);
447                         i = a.rfind('\r');
448                 }
449
450                 if (a.length())
451                         recvq.append(a);
452
453                 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
454                 {
455                         this->SetWriteError("RecvQ exceeded");
456                         ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->MyClass->GetRecvqMax());
457                         return false;
458                 }
459
460                 return true;
461         }
462
463         catch (...)
464         {
465                 ServerInstance->Log(DEBUG,"Exception in User::AddBuffer()");
466                 return false;
467         }
468 }
469
470 bool User::BufferIsReady()
471 {
472         return (recvq.find('\n') != std::string::npos);
473 }
474
475 void User::ClearBuffer()
476 {
477         recvq.clear();
478 }
479
480 std::string User::GetBuffer()
481 {
482         try
483         {
484                 if (recvq.empty())
485                         return "";
486
487                 /* Strip any leading \r or \n off the string.
488                  * Usually there are only one or two of these,
489                  * so its is computationally cheap to do.
490                  */
491                 std::string::iterator t = recvq.begin();
492                 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
493                 {
494                         recvq.erase(t);
495                         t = recvq.begin();
496                 }
497
498                 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
499                 {
500                         /* Find the first complete line, return it as the
501                          * result, and leave the recvq as whats left
502                          */
503                         if (*x == '\n')
504                         {
505                                 std::string ret = std::string(recvq.begin(), x);
506                                 recvq.erase(recvq.begin(), x + 1);
507                                 return ret;
508                         }
509                 }
510                 return "";
511         }
512
513         catch (...)
514         {
515                 ServerInstance->Log(DEBUG,"Exception in User::GetBuffer()");
516                 return "";
517         }
518 }
519
520 void User::AddWriteBuf(const std::string &data)
521 {
522         if (*this->GetWriteError())
523                 return;
524
525         if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
526         {
527                 /*
528                  * Fix by brain - Set the error text BEFORE calling writeopers, because
529                  * if we dont it'll recursively  call here over and over again trying
530                  * to repeatedly add the text to the sendq!
531                  */
532                 this->SetWriteError("SendQ exceeded");
533                 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->MyClass->GetSendqMax());
534                 return;
535         }
536
537         try
538         {
539                 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
540                         sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
541                 else
542                         sendq.append(data);
543         }
544         catch (...)
545         {
546                 this->SetWriteError("SendQ exceeded");
547                 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
548         }
549 }
550
551 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
552 void User::FlushWriteBuf()
553 {
554         try
555         {
556                 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
557                 {
558                         sendq.clear();
559                 }
560                 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
561                 {
562                         int old_sendq_length = sendq.length();
563                         int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
564
565                         if (n_sent == -1)
566                         {
567                                 if (errno == EAGAIN)
568                                 {
569                                         /* The socket buffer is full. This isnt fatal,
570                                          * try again later.
571                                          */
572                                         this->ServerInstance->SE->WantWrite(this);
573                                 }
574                                 else
575                                 {
576                                         /* Fatal error, set write error and bail
577                                          */
578                                         this->SetWriteError(errno ? strerror(errno) : "EOF from client");
579                                         return;
580                                 }
581                         }
582                         else
583                         {
584                                 /* advance the queue */
585                                 if (n_sent)
586                                         this->sendq = this->sendq.substr(n_sent);
587                                 /* update the user's stats counters */
588                                 this->bytes_out += n_sent;
589                                 this->cmds_out++;
590                                 if (n_sent != old_sendq_length)
591                                         this->ServerInstance->SE->WantWrite(this);
592                         }
593                 }
594         }
595
596         catch (...)
597         {
598                 ServerInstance->Log(DEBUG,"Exception in User::FlushWriteBuf()");
599         }
600
601         if (this->sendq.empty())
602         {
603                 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
604         }
605 }
606
607 void User::SetWriteError(const std::string &error)
608 {
609         try
610         {
611                 // don't try to set the error twice, its already set take the first string.
612                 if (this->WriteError.empty())
613                         this->WriteError = error;
614         }
615
616         catch (...)
617         {
618                 ServerInstance->Log(DEBUG,"Exception in User::SetWriteError()");
619         }
620 }
621
622 const char* User::GetWriteError()
623 {
624         return this->WriteError.c_str();
625 }
626
627 void User::Oper(const std::string &opertype, const std::string &opername)
628 {
629         char* mycmd;
630         char* savept;
631         char* savept2;
632
633         try
634         {
635                 this->modes[UM_OPERATOR] = 1;
636                 this->WriteServ("MODE %s :+o", this->nick);
637                 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
638                 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
639                 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
640                 ServerInstance->all_opers.push_back(this);
641
642                 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
643                 if (iter_opertype != ServerInstance->Config->opertypes.end())
644                 {
645
646                         if (AllowedOperCommands)
647                                 AllowedOperCommands->clear();
648                         else
649                                 AllowedOperCommands = new std::map<std::string, bool>;
650
651                         char* Classes = strdup(iter_opertype->second);
652                         char* myclass = strtok_r(Classes," ",&savept);
653                         while (myclass)
654                         {
655                                 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
656                                 if (iter_operclass != ServerInstance->Config->operclass.end())
657                                 {
658                                         char* CommandList = strdup(iter_operclass->second);
659                                         mycmd = strtok_r(CommandList," ",&savept2);
660                                         while (mycmd)
661                                         {
662                                                 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
663                                                 mycmd = strtok_r(NULL," ",&savept2);
664                                         }
665                                         free(CommandList);
666                                 }
667                                 myclass = strtok_r(NULL," ",&savept);
668                         }
669                         free(Classes);
670                 }
671
672                 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
673         }
674
675         catch (...)
676         {
677                 ServerInstance->Log(DEBUG,"Exception in User::Oper()");
678         }
679 }
680
681 void User::UnOper()
682 {
683         try
684         {
685                 if (IS_OPER(this))
686                 {
687                         // unset their oper type (what IS_OPER checks), and remove +o
688                         *this->oper = 0;
689                         this->modes[UM_OPERATOR] = 0;
690                         
691                         // remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404
692                         ServerInstance->all_opers.remove(this);
693
694                         if (AllowedOperCommands)
695                         {
696                                 delete AllowedOperCommands;
697                                 AllowedOperCommands = NULL;
698                         }
699                 }
700         }
701
702         catch (...)
703         {
704                 ServerInstance->Log(DEBUG,"Exception in User::UnOper()");
705         }
706 }
707
708 void User::QuitUser(InspIRCd* Instance, User *user, const std::string &quitreason, const char* operreason)
709 {
710         Instance->Log(DEBUG,"QuitUser: %s '%s'", user->nick, quitreason.c_str());
711         user->Write("ERROR :Closing link (%s@%s) [%s]", user->ident, user->host, *operreason ? operreason : quitreason.c_str());
712         user->muted = true;
713         Instance->GlobalCulls.AddItem(user, quitreason.c_str(), operreason);
714 }
715
716 /* adds or updates an entry in the whowas list */
717 void User::AddToWhoWas()
718 {
719         Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
720         if (whowas_command)
721         {
722                 std::deque<classbase*> params;
723                 params.push_back(this);
724                 whowas_command->HandleInternal(WHOWAS_ADD, params);
725         }
726 }
727
728 /* add a client connection to the sockets list */
729 void User::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, int socketfamily, sockaddr* ip)
730 {
731         /* NOTE: Calling this one parameter constructor for User automatically
732          * allocates a new UUID and places it in the hash_map.
733          */
734         User* New = NULL;
735         try
736         {
737                 New = new User(Instance);
738         }
739         catch (...)
740         {
741                 Instance->Log(DEFAULT,"*** WTF *** Duplicated UUID! -- Crack smoking monkies have been unleashed.");
742                 Instance->WriteOpers("*** WARNING *** Duplicate UUID allocated!");
743                 return;
744         }
745
746         Instance->Log(DEBUG,"New user fd: %d", socket);
747
748         int j = 0;
749
750         Instance->unregistered_count++;
751
752         char ipaddr[MAXBUF];
753 #ifdef IPV6
754         if (socketfamily == AF_INET6)
755                 inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, ipaddr, sizeof(ipaddr));
756         else
757 #endif
758         inet_ntop(AF_INET, &((const sockaddr_in*)ip)->sin_addr, ipaddr, sizeof(ipaddr));
759
760         (*(Instance->clientlist))[New->uuid] = New;
761         New->SetFd(socket);
762
763         /* The users default nick is their UUID */
764         strlcpy(New->nick, New->uuid, NICKMAX - 1);
765
766         New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
767         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
768         strcpy(New->ident, "unknown");
769
770         New->registered = REG_NONE;
771         New->signon = Instance->Time() + Instance->Config->dns_timeout;
772         New->lastping = 1;
773
774         New->SetSockAddr(socketfamily, ipaddr, port);
775
776         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
777         for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
778                 New->dhost[j] = New->host[j] = *temp;
779         New->dhost[j] = New->host[j] = 0;
780
781         Instance->Users->AddLocalClone(New);
782         Instance->Users->AddGlobalClone(New);
783
784         /*
785          * First class check. We do this again in FullConnect after DNS is done, and NICK/USER is recieved.
786          * See my note down there for why this is required. DO NOT REMOVE. :) -- w00t
787          */
788         ConnectClass* i = New->SetClass();
789
790         if (!i)
791         {
792                 User::QuitUser(Instance, New, "Access denied by configuration");
793                 return;
794         }
795
796         /*
797          * Check connect class settings and initialise settings into User.
798          * This will be done again after DNS resolution. -- w00t
799          */
800         New->CheckClass();
801
802         Instance->local_users.push_back(New);
803
804         if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
805         {
806                 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
807                 User::QuitUser(Instance, New,"No more connections allowed");
808                 return;
809         }
810
811         /*
812          * XXX -
813          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
814          * its a pretty big but for the moment valid assumption:
815          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
816          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
817          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
818          * which for the time being is a physical impossibility (even the largest networks dont have more
819          * than about 10,000 users on ONE server!)
820          */
821 #ifndef WINDOWS
822         if ((unsigned int)socket >= MAX_DESCRIPTORS)
823         {
824                 User::QuitUser(Instance, New, "Server is full");
825                 return;
826         }
827 #endif
828         /*
829          * even with bancache, we still have to keep User::exempt current.
830          * besides that, if we get a positive bancache hit, we still won't fuck
831          * them over if they are exempt. -- w00t
832          */
833         New->exempt = (Instance->XLines->MatchesLine("E",New) != NULL);
834
835         if (BanCacheHit *b = Instance->BanCache->GetHit(New->GetIPString()))
836         {
837                 if (!b->Type.empty() && !New->exempt)
838                 {
839                         /* user banned */
840                         Instance->Log(DEBUG, std::string("BanCache: Positive hit for ") + New->GetIPString());
841                         if (*Instance->Config->MoronBanner)
842                                 New->WriteServ("NOTICE %s :*** %s", New->nick, Instance->Config->MoronBanner);
843                         User::QuitUser(Instance, New, b->Reason);
844                         return;
845                 }
846                 else
847                 {
848                         Instance->Log(DEBUG, std::string("BanCache: Negative hit for ") + New->GetIPString());
849                 }
850         }
851         else
852         {
853                 if (!New->exempt)
854                 {
855                         XLine* r = Instance->XLines->MatchesLine("Z",New);
856
857                         if (r)
858                         {
859                                 r->Apply(New);
860                                 return;
861                         }
862                 }
863         }
864
865         if (socket > -1)
866         {
867                 if (!Instance->SE->AddFd(New))
868                 {
869                         Instance->Log(DEBUG,"Internal error on new connection");
870                         User::QuitUser(Instance, New, "Internal error handling connection");
871                 }
872         }
873
874         /* NOTE: even if dns lookups are *off*, we still need to display this.
875          * BOPM and other stuff requires it.
876          */
877         New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
878
879         if (Instance->Config->NoUserDns)
880         {
881                 New->dns_done = true;
882         }
883         else
884         {
885                 New->StartDNSLookup();
886         }
887 }
888
889 /*
890  * Check class restrictions
891  */
892 void User::CheckClass()
893 {
894         ConnectClass* a = this->MyClass;
895
896         if ((!a) || (a->GetType() == CC_DENY))
897         {
898                 User::QuitUser(ServerInstance, this, "Unauthorised connection");
899                 return;
900         }
901         else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
902         {
903                 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (local)");
904                 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
905                 return;
906         }
907         else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
908         {
909                 User::QuitUser(ServerInstance, this, "No more connections allowed from your host via this connect class (global)");
910                 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
911                 return;
912         }
913
914         this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
915         this->timeout = ServerInstance->Time() + a->GetRegTimeout();
916         this->MaxChans = a->GetMaxChans();
917 }
918
919 void User::FullConnect()
920 {
921         ServerInstance->stats->statsConnects++;
922         this->idle_lastmsg = ServerInstance->Time();
923
924         /*
925          * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
926          * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
927          * may put the user into a totally seperate class with different restrictions! so we *must* check again.
928          * Don't remove this! -- w00t
929          */
930         this->SetClass();
931         
932         /* Check the password, if one is required by the user's connect class.
933          * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
934          */
935         if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
936         {
937                 User::QuitUser(ServerInstance, this, "Invalid password");
938                 return;
939         }
940
941         if (!this->exempt)
942         {
943                 GLine *r = (GLine *)ServerInstance->XLines->MatchesLine("G", this);
944
945                 if (r)
946                 {
947                         this->muted = true;
948                         r->Apply(this);
949                         return;
950                 }
951
952                 KLine *n = (KLine *)ServerInstance->XLines->MatchesLine("K", this);
953
954                 if (n)
955                 {
956                         this->muted = true;
957                         n->Apply(this);
958                         return;
959                 }
960         }
961
962         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
963         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
964         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
965         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
966         this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
967
968         ServerInstance->Config->Send005(this);
969
970         this->WriteServ("042 %s %s :your unique ID", this->nick, this->uuid);
971
972
973         this->ShowMOTD();
974
975         /* Now registered */
976         if (ServerInstance->unregistered_count)
977                 ServerInstance->unregistered_count--;
978
979         /* Trigger LUSERS output, give modules a chance too */
980         int MOD_RESULT = 0;
981         FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", NULL, 0, this, true, "LUSERS"));
982         if (!MOD_RESULT)
983                 ServerInstance->CallCommandHandler("LUSERS", NULL, 0, this);
984
985         /*
986          * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
987          * for a user that doesn't exist yet.
988          */
989         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
990
991         this->registered = REG_ALL;
992
993         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
994
995         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString(), this->fullname);
996
997         ServerInstance->Log(DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
998         ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
999 }
1000
1001 /** User::UpdateNick()
1002  * re-allocates a nick in the user_hash after they change nicknames,
1003  * returns a pointer to the new user as it may have moved
1004  */
1005 User* User::UpdateNickHash(const char* New)
1006 {
1007         try
1008         {
1009                 //user_hash::iterator newnick;
1010                 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1011
1012                 if (!strcasecmp(this->nick,New))
1013                         return oldnick->second;
1014
1015                 if (oldnick == ServerInstance->clientlist->end())
1016                         return NULL; /* doesnt exist */
1017
1018                 User* olduser = oldnick->second;
1019                 (*(ServerInstance->clientlist))[New] = olduser;
1020                 ServerInstance->clientlist->erase(oldnick);
1021                 return olduser;
1022         }
1023
1024         catch (...)
1025         {
1026                 ServerInstance->Log(DEBUG,"Exception in User::UpdateNickHash()");
1027                 return NULL;
1028         }
1029 }
1030
1031 void User::InvalidateCache()
1032 {
1033         /* Invalidate cache */
1034         if (cached_fullhost)
1035                 free(cached_fullhost);
1036         if (cached_hostip)
1037                 free(cached_hostip);
1038         if (cached_makehost)
1039                 free(cached_makehost);
1040         if (cached_fullrealhost)
1041                 free(cached_fullrealhost);
1042         cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1043 }
1044
1045 bool User::ForceNickChange(const char* newnick)
1046 {
1047         try
1048         {
1049                 int MOD_RESULT = 0;
1050
1051                 this->InvalidateCache();
1052
1053                 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1054
1055                 if (MOD_RESULT)
1056                 {
1057                         ServerInstance->stats->statsCollisions++;
1058                         return false;
1059                 }
1060
1061                 if (ServerInstance->XLines->MatchesLine("Q",newnick))
1062                 {
1063                         ServerInstance->stats->statsCollisions++;
1064                         return false;
1065                 }
1066
1067                 if (this->registered == REG_ALL)
1068                 {
1069                         std::deque<classbase*> dummy;
1070                         Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1071                         if (nickhandler)
1072                         {
1073                                 nickhandler->HandleInternal(1, dummy);
1074                                 bool result = (ServerInstance->Parser->CallHandler("NICK", &newnick, 1, this) == CMD_SUCCESS);
1075                                 nickhandler->HandleInternal(0, dummy);
1076                                 return result;
1077                         }
1078                 }
1079                 return false;
1080         }
1081
1082         catch (...)
1083         {
1084                 ServerInstance->Log(DEBUG,"Exception in User::ForceNickChange()");
1085                 return false;
1086         }
1087 }
1088
1089 void User::SetSockAddr(int protocol_family, const char* ip, int port)
1090 {
1091         switch (protocol_family)
1092         {
1093 #ifdef SUPPORT_IP6LINKS
1094                 case AF_INET6:
1095                 {
1096                         sockaddr_in6* sin = new sockaddr_in6;
1097                         sin->sin6_family = AF_INET6;
1098                         sin->sin6_port = port;
1099                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1100                         this->ip = (sockaddr*)sin;
1101                 }
1102                 break;
1103 #endif
1104                 case AF_INET:
1105                 {
1106                         sockaddr_in* sin = new sockaddr_in;
1107                         sin->sin_family = AF_INET;
1108                         sin->sin_port = port;
1109                         inet_pton(AF_INET, ip, &sin->sin_addr);
1110                         this->ip = (sockaddr*)sin;
1111                 }
1112                 break;
1113                 default:
1114                         ServerInstance->Log(DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1115                 break;
1116         }
1117 }
1118
1119 int User::GetPort()
1120 {
1121         if (this->ip == NULL)
1122                 return 0;
1123
1124         switch (this->GetProtocolFamily())
1125         {
1126 #ifdef SUPPORT_IP6LINKS
1127                 case AF_INET6:
1128                 {
1129                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1130                         return sin->sin6_port;
1131                 }
1132                 break;
1133 #endif
1134                 case AF_INET:
1135                 {
1136                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1137                         return sin->sin_port;
1138                 }
1139                 break;
1140                 default:
1141                 break;
1142         }
1143         return 0;
1144 }
1145
1146 int User::GetProtocolFamily()
1147 {
1148         if (this->ip == NULL)
1149                 return 0;
1150
1151         sockaddr_in* sin = (sockaddr_in*)this->ip;
1152         return sin->sin_family;
1153 }
1154
1155 /*
1156  * XXX the duplication here is horrid..
1157  * do we really need two methods doing essentially the same thing?
1158  */
1159 const char* User::GetIPString()
1160 {
1161         static char buf[1024];
1162
1163         if (this->ip == NULL)
1164                 return "";
1165
1166         switch (this->GetProtocolFamily())
1167         {
1168 #ifdef SUPPORT_IP6LINKS
1169                 case AF_INET6:
1170                 {
1171                         static char temp[1024];
1172
1173                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1174                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1175                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1176                         if (*buf == ':')
1177                         {
1178                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1179                                 *temp = '0';
1180                                 return temp;
1181                         }
1182                         return buf;
1183                 }
1184                 break;
1185 #endif
1186                 case AF_INET:
1187                 {
1188                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1189                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1190                         return buf;
1191                 }
1192                 break;
1193                 default:
1194                 break;
1195         }
1196         return "";
1197 }
1198
1199 /** NOTE: We cannot pass a const reference to this method.
1200  * The string is changed by the workings of the method,
1201  * so that if we pass const ref, we end up copying it to
1202  * something we can change anyway. Makes sense to just let
1203  * the compiler do that copy for us.
1204  */
1205 void User::Write(std::string text)
1206 {
1207         if (!ServerInstance->SE->BoundsCheckFd(this))
1208                 return;
1209
1210         try
1211         {
1212                 /* ServerInstance->Log(DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1213                  * WARNING: The above debug line is VERY loud, do NOT
1214                  * enable it till we have a good way of filtering it
1215                  * out of the logs (e.g. 1.2 would be good).
1216                  */
1217                 text.append("\r\n");
1218         }
1219         catch (...)
1220         {
1221                 ServerInstance->Log(DEBUG,"Exception in User::Write() std::string::append");
1222                 return;
1223         }
1224
1225         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1226         {
1227                 try
1228                 {
1229                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1230                          * implement their own buffering mechanisms
1231                          */
1232                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1233                 }
1234                 catch (CoreException& modexcept)
1235                 {
1236                         ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1237                 }
1238         }
1239         else
1240         {
1241                 this->AddWriteBuf(text);
1242         }
1243         ServerInstance->stats->statsSent += text.length();
1244         this->ServerInstance->SE->WantWrite(this);
1245 }
1246
1247 /** Write()
1248  */
1249 void User::Write(const char *text, ...)
1250 {
1251         va_list argsPtr;
1252         char textbuffer[MAXBUF];
1253
1254         va_start(argsPtr, text);
1255         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1256         va_end(argsPtr);
1257
1258         this->Write(std::string(textbuffer));
1259 }
1260
1261 void User::WriteServ(const std::string& text)
1262 {
1263         char textbuffer[MAXBUF];
1264
1265         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1266         this->Write(std::string(textbuffer));
1267 }
1268
1269 /** WriteServ()
1270  *  Same as Write(), except `text' is prefixed with `:server.name '.
1271  */
1272 void User::WriteServ(const char* text, ...)
1273 {
1274         va_list argsPtr;
1275         char textbuffer[MAXBUF];
1276
1277         va_start(argsPtr, text);
1278         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1279         va_end(argsPtr);
1280
1281         this->WriteServ(std::string(textbuffer));
1282 }
1283
1284
1285 void User::WriteFrom(User *user, const std::string &text)
1286 {
1287         char tb[MAXBUF];
1288
1289         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1290
1291         this->Write(std::string(tb));
1292 }
1293
1294
1295 /* write text from an originating user to originating user */
1296
1297 void User::WriteFrom(User *user, const char* text, ...)
1298 {
1299         va_list argsPtr;
1300         char textbuffer[MAXBUF];
1301
1302         va_start(argsPtr, text);
1303         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1304         va_end(argsPtr);
1305
1306         this->WriteFrom(user, std::string(textbuffer));
1307 }
1308
1309
1310 /* write text to an destination user from a source user (e.g. user privmsg) */
1311
1312 void User::WriteTo(User *dest, const char *data, ...)
1313 {
1314         char textbuffer[MAXBUF];
1315         va_list argsPtr;
1316
1317         va_start(argsPtr, data);
1318         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1319         va_end(argsPtr);
1320
1321         this->WriteTo(dest, std::string(textbuffer));
1322 }
1323
1324 void User::WriteTo(User *dest, const std::string &data)
1325 {
1326         dest->WriteFrom(this, data);
1327 }
1328
1329
1330 void User::WriteCommon(const char* text, ...)
1331 {
1332         char textbuffer[MAXBUF];
1333         va_list argsPtr;
1334
1335         if (this->registered != REG_ALL)
1336                 return;
1337
1338         va_start(argsPtr, text);
1339         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1340         va_end(argsPtr);
1341
1342         this->WriteCommon(std::string(textbuffer));
1343 }
1344
1345 void User::WriteCommon(const std::string &text)
1346 {
1347         try
1348         {
1349                 bool sent_to_at_least_one = false;
1350                 char tb[MAXBUF];
1351
1352                 if (this->registered != REG_ALL)
1353                         return;
1354
1355                 uniq_id++;
1356
1357                 /* We dont want to be doing this n times, just once */
1358                 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1359                 std::string out = tb;
1360
1361                 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1362                 {
1363                         CUList* ulist = v->first->GetUsers();
1364                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1365                         {
1366                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1367                                 {
1368                                         already_sent[i->first->fd] = uniq_id;
1369                                         i->first->Write(out);
1370                                         sent_to_at_least_one = true;
1371                                 }
1372                         }
1373                 }
1374
1375                 /*
1376                  * if the user was not in any channels, no users will receive the text. Make sure the user
1377                  * receives their OWN message for WriteCommon
1378                  */
1379                 if (!sent_to_at_least_one)
1380                 {
1381                         this->Write(std::string(tb));
1382                 }
1383         }
1384
1385         catch (...)
1386         {
1387                 ServerInstance->Log(DEBUG,"Exception in User::WriteCommon()");
1388         }
1389 }
1390
1391
1392 /* write a formatted string to all users who share at least one common
1393  * channel, NOT including the source user e.g. for use in QUIT
1394  */
1395
1396 void User::WriteCommonExcept(const char* text, ...)
1397 {
1398         char textbuffer[MAXBUF];
1399         va_list argsPtr;
1400
1401         va_start(argsPtr, text);
1402         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1403         va_end(argsPtr);
1404
1405         this->WriteCommonExcept(std::string(textbuffer));
1406 }
1407
1408 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1409 {
1410         char tb1[MAXBUF];
1411         char tb2[MAXBUF];
1412
1413         if (this->registered != REG_ALL)
1414                 return;
1415
1416         uniq_id++;
1417         snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1418         snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1419         std::string out1 = tb1;
1420         std::string out2 = tb2;
1421
1422         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1423         {
1424                 CUList *ulist = v->first->GetUsers();
1425                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1426                 {
1427                         if (this != i->first)
1428                         {
1429                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1430                                 {
1431                                         already_sent[i->first->fd] = uniq_id;
1432                                         i->first->Write(IS_OPER(i->first) ? out2 : out1);
1433                                 }
1434                         }
1435                 }
1436         }
1437 }
1438
1439 void User::WriteCommonExcept(const std::string &text)
1440 {
1441         char tb1[MAXBUF];
1442         std::string out1;
1443
1444         if (this->registered != REG_ALL)
1445                 return;
1446
1447         uniq_id++;
1448         snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1449         out1 = tb1;
1450
1451         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1452         {
1453                 CUList *ulist = v->first->GetUsers();
1454                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1455                 {
1456                         if (this != i->first)
1457                         {
1458                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1459                                 {
1460                                         already_sent[i->first->fd] = uniq_id;
1461                                         i->first->Write(out1);
1462                                 }
1463                         }
1464                 }
1465         }
1466
1467 }
1468
1469 void User::WriteWallOps(const std::string &text)
1470 {
1471         if (!IS_OPER(this) && IS_LOCAL(this))
1472                 return;
1473
1474         std::string wallop("WALLOPS :");
1475         wallop.append(text);
1476
1477         for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1478         {
1479                 User* t = *i;
1480                 if (t->IsModeSet('w'))
1481                         this->WriteTo(t,wallop);
1482         }
1483 }
1484
1485 void User::WriteWallOps(const char* text, ...)
1486 {
1487         char textbuffer[MAXBUF];
1488         va_list argsPtr;
1489
1490         va_start(argsPtr, text);
1491         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1492         va_end(argsPtr);
1493
1494         this->WriteWallOps(std::string(textbuffer));
1495 }
1496
1497 /* return 0 or 1 depending if users u and u2 share one or more common channels
1498  * (used by QUIT, NICK etc which arent channel specific notices)
1499  *
1500  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1501  * the first users channels then the second users channels within the outer loop,
1502  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1503  * all possible iterations). However this new function instead checks against the
1504  * channel's userlist in the inner loop which is a std::map<User*,User*>
1505  * and saves us time as we already know what pointer value we are after.
1506  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1507  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1508  */
1509 bool User::SharesChannelWith(User *other)
1510 {
1511         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1512                 return false;
1513
1514         /* Outer loop */
1515         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1516         {
1517                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1518                  * by replacing it with a map::find which *should* be more efficient
1519                  */
1520                 if (i->first->HasUser(other))
1521                         return true;
1522         }
1523         return false;
1524 }
1525
1526 bool User::ChangeName(const char* gecos)
1527 {
1528         if (!strcmp(gecos, this->fullname))
1529                 return true;
1530
1531         if (IS_LOCAL(this))
1532         {
1533                 int MOD_RESULT = 0;
1534                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1535                 if (MOD_RESULT)
1536                         return false;
1537                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1538         }
1539         strlcpy(this->fullname,gecos,MAXGECOS+1);
1540
1541         return true;
1542 }
1543
1544 bool User::ChangeDisplayedHost(const char* host)
1545 {
1546         if (!strcmp(host, this->dhost))
1547                 return true;
1548
1549         if (IS_LOCAL(this))
1550         {
1551                 int MOD_RESULT = 0;
1552                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1553                 if (MOD_RESULT)
1554                         return false;
1555                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1556         }
1557         if (this->ServerInstance->Config->CycleHosts)
1558                 this->WriteCommonExcept("QUIT :Changing hosts");
1559
1560         /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1561         strlcpy(this->dhost,host,64);
1562
1563         this->InvalidateCache();
1564
1565         if (this->ServerInstance->Config->CycleHosts)
1566         {
1567                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1568                 {
1569                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1570                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1571                         if (n.length() > 0)
1572                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1573                 }
1574         }
1575
1576         if (IS_LOCAL(this))
1577                 this->WriteServ("396 %s %s :is now your displayed host",this->nick,this->dhost);
1578
1579         return true;
1580 }
1581
1582 bool User::ChangeIdent(const char* newident)
1583 {
1584         if (!strcmp(newident, this->ident))
1585                 return true;
1586
1587         if (this->ServerInstance->Config->CycleHosts)
1588                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1589
1590         strlcpy(this->ident, newident, IDENTMAX+2);
1591
1592         this->InvalidateCache();
1593
1594         if (this->ServerInstance->Config->CycleHosts)
1595         {
1596                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1597                 {
1598                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1599                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1600                         if (n.length() > 0)
1601                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1602                 }
1603         }
1604
1605         return true;
1606 }
1607
1608 void User::SendAll(const char* command, char* text, ...)
1609 {
1610         char textbuffer[MAXBUF];
1611         char formatbuffer[MAXBUF];
1612         va_list argsPtr;
1613
1614         va_start(argsPtr, text);
1615         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1616         va_end(argsPtr);
1617
1618         snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1619         std::string fmt = formatbuffer;
1620
1621         for (std::vector<User*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1622         {
1623                 (*i)->Write(fmt);
1624         }
1625 }
1626
1627
1628 std::string User::ChannelList(User* source)
1629 {
1630         try
1631         {
1632                 std::string list;
1633                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1634                 {
1635                         /* If the target is the same as the sender, let them see all their channels.
1636                          * If the channel is NOT private/secret OR the user shares a common channel
1637                          * If the user is an oper, and the <options:operspywhois> option is set.
1638                          */
1639                         if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1640                         {
1641                                 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1642                         }
1643                 }
1644                 return list;
1645         }
1646         catch (...)
1647         {
1648                 ServerInstance->Log(DEBUG,"Exception in User::ChannelList()");
1649                 return "";
1650         }
1651 }
1652
1653 void User::SplitChanList(User* dest, const std::string &cl)
1654 {
1655         std::string line;
1656         std::ostringstream prefix;
1657         std::string::size_type start, pos, length;
1658
1659         try
1660         {
1661                 prefix << this->nick << " " << dest->nick << " :";
1662                 line = prefix.str();
1663                 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1664
1665                 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1666                 {
1667                         length = (pos == std::string::npos) ? cl.length() : pos;
1668
1669                         if (line.length() + namelen + length - start > 510)
1670                         {
1671                                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1672                                 line = prefix.str();
1673                         }
1674
1675                         if(pos == std::string::npos)
1676                         {
1677                                 line.append(cl.substr(start, length - start));
1678                                 break;
1679                         }
1680                         else
1681                         {
1682                                 line.append(cl.substr(start, length - start + 1));
1683                         }
1684                 }
1685
1686                 if (line.length())
1687                 {
1688                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1689                 }
1690         }
1691
1692         catch (...)
1693         {
1694                 ServerInstance->Log(DEBUG,"Exception in User::SplitChanList()");
1695         }
1696 }
1697
1698 unsigned int User::GetMaxChans()
1699 {
1700         return this->MaxChans;
1701 }
1702
1703
1704 /*
1705  * Sets a user's connection class.
1706  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1707  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1708  * then their ip will be taken as 'priority' anyway, so for example,
1709  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1710  */
1711 ConnectClass* User::SetClass(const std::string &explicit_name)
1712 {
1713         ConnectClass *found = NULL;
1714
1715         if (!IS_LOCAL(this))
1716                 return NULL;
1717
1718         if (!explicit_name.empty())
1719         {
1720                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1721                 {
1722                         ConnectClass* c = *i;
1723
1724                         if (explicit_name == c->GetName() && !c->GetDisabled())
1725                         {
1726                                 found = c;
1727                         }
1728                 }
1729         }
1730         else
1731         {
1732                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1733                 {
1734                         ConnectClass* c = *i;
1735
1736                         if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1737                         {
1738                                 if (c->GetPort())
1739                                 {
1740                                         if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1741                                         {
1742                                                 found = c;
1743                                         }
1744                                         else
1745                                                 continue;
1746                                 }
1747                                 else
1748                                 {
1749                                         if (!c->GetDisabled())
1750                                                 found = c;
1751                                 }
1752                         }
1753                 }
1754         }
1755
1756         /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1757         if (found)
1758         {
1759                 /* deny change if change will take class over the limit */
1760                 if (found->limit && (found->RefCount + 1 >= found->limit))
1761                 {
1762                         ServerInstance->Log(DEBUG, "OOPS: Connect class limit (%u) hit, denying", found->limit);
1763                         return this->MyClass;
1764                 }
1765
1766                 /* should always be valid, but just in case .. */
1767                 if (this->MyClass)
1768                 {
1769                         if (found == this->MyClass) // no point changing this shit :P
1770                                 return this->MyClass;
1771                         this->MyClass->RefCount--;
1772                         ServerInstance->Log(DEBUG, "Untying user from connect class -- refcount: %u", this->MyClass->RefCount);
1773                 }
1774
1775                 this->MyClass = found;
1776                 this->MyClass->RefCount++;
1777                 ServerInstance->Log(DEBUG, "User tied to new class -- connect refcount now: %u", this->MyClass->RefCount);
1778         }
1779
1780         return this->MyClass;
1781 }
1782
1783 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1784  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1785  * then their ip will be taken as 'priority' anyway, so for example,
1786  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1787  */
1788 ConnectClass* User::GetClass()
1789 {
1790         return this->MyClass;
1791 }
1792
1793 void User::PurgeEmptyChannels()
1794 {
1795         std::vector<Channel*> to_delete;
1796
1797         // firstly decrement the count on each channel
1798         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1799         {
1800                 f->first->RemoveAllPrefixes(this);
1801                 if (f->first->DelUser(this) == 0)
1802                 {
1803                         /* No users left in here, mark it for deletion */
1804                         try
1805                         {
1806                                 to_delete.push_back(f->first);
1807                         }
1808                         catch (...)
1809                         {
1810                                 ServerInstance->Log(DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1811                         }
1812                 }
1813         }
1814
1815         for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1816         {
1817                 Channel* thischan = *n;
1818                 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1819                 if (i2 != ServerInstance->chanlist->end())
1820                 {
1821                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1822                         delete i2->second;
1823                         ServerInstance->chanlist->erase(i2);
1824                         this->chans.erase(*n);
1825                 }
1826         }
1827
1828         this->UnOper();
1829 }
1830
1831 void User::ShowMOTD()
1832 {
1833         if (!ServerInstance->Config->MOTD.size())
1834         {
1835                 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1836                 return;
1837         }
1838         this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1839
1840         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1841                 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1842
1843         this->WriteServ("376 %s :End of message of the day.", this->nick);
1844 }
1845
1846 void User::ShowRULES()
1847 {
1848         if (!ServerInstance->Config->RULES.size())
1849         {
1850                 this->WriteServ("434 %s :RULES File is missing",this->nick);
1851                 return;
1852         }
1853
1854         this->WriteServ("308 %s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1855
1856         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1857                 this->WriteServ("232 %s :- %s",this->nick,i->c_str());
1858
1859         this->WriteServ("309 %s :End of RULES command.",this->nick);
1860 }
1861
1862 void User::HandleEvent(EventType et, int errornum)
1863 {
1864         /* WARNING: May delete this user! */
1865         int thisfd = this->GetFd();
1866
1867         try
1868         {
1869                 switch (et)
1870                 {
1871                         case EVENT_READ:
1872                                 ServerInstance->ProcessUser(this);
1873                         break;
1874                         case EVENT_WRITE:
1875                                 this->FlushWriteBuf();
1876                         break;
1877                         case EVENT_ERROR:
1878                                 /** This should be safe, but dont DARE do anything after it -- Brain */
1879                                 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1880                         break;
1881                 }
1882         }
1883         catch (...)
1884         {
1885                 ServerInstance->Log(DEBUG,"Exception in User::HandleEvent intercepted");
1886         }
1887
1888         /* If the user has raised an error whilst being processed, quit them now we're safe to */
1889         if ((ServerInstance->SE->GetRef(thisfd) == this))
1890         {
1891                 if (!WriteError.empty())
1892                 {
1893                         User::QuitUser(ServerInstance, this, GetWriteError());
1894                 }
1895         }
1896 }
1897
1898 void User::SetOperQuit(const std::string &oquit)
1899 {
1900         if (operquit)
1901                 return;
1902
1903         operquit = strdup(oquit.c_str());
1904 }
1905
1906 const char* User::GetOperQuit()
1907 {
1908         return operquit ? operquit : "";
1909 }
1910
1911 void User::IncreasePenalty(int increase)
1912 {
1913         this->Penalty += increase;
1914 }
1915
1916 void User::DecreasePenalty(int decrease)
1917 {
1918         this->Penalty -= decrease;
1919 }
1920
1921 VisData::VisData()
1922 {
1923 }
1924
1925 VisData::~VisData()
1926 {
1927 }
1928
1929 bool VisData::VisibleTo(User* user)
1930 {
1931         return true;
1932 }
1933