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