]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
8273acc88eb96185245e92c74e0b496a99a0acc6
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "inspircd_config.h"
18 #include "configreader.h"
19 #include "channels.h"
20 #include "connection.h"
21 #include "users.h"
22 #include "inspircd.h"
23 #include <stdarg.h>
24 #include "inspstring.h"
25 #include "commands.h"
26 #include "helperfuncs.h"
27 #include "typedefs.h"
28 #include "socketengine.h"
29 #include "hashcomp.h"
30 #include "wildcard.h"
31 #include "xline.h"
32 #include "cull_list.h"
33
34 extern std::vector<Module*> modules;
35 extern std::vector<ircd_module*> factory;
36 extern int MODCOUNT;
37 extern time_t TIME;
38 extern Server* MyServer;
39
40 irc::whowas::whowas_users whowas;
41 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
42 std::vector<userrec*> all_opers;
43
44 typedef std::map<irc::string,char*> opertype_t;
45 typedef opertype_t operclass_t;
46
47 opertype_t opertypes;
48 operclass_t operclass;
49
50 /* XXX: Used for speeding up WriteCommon operations */
51 unsigned long uniq_id = 0;
52
53 bool InitTypes(ServerConfig* conf, const char* tag)
54 {
55         for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
56         {
57                 if (n->second)
58                         delete[] n->second;
59         }
60         
61         opertypes.clear();
62         return true;
63 }
64
65 bool InitClasses(ServerConfig* conf, const char* tag)
66 {
67         for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
68         {
69                 if (n->second)
70                         delete[] n->second;
71         }
72         
73         operclass.clear();
74         return true;
75 }
76
77 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
78 {
79         char* TypeName = (char*)values[0];
80         char* Classes = (char*)values[1];
81         
82         opertypes[TypeName] = strdup(Classes);
83         log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
84         return true;
85 }
86
87 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
88 {
89         char* ClassName = (char*)values[0];
90         char* CommandList = (char*)values[1];
91         
92         operclass[ClassName] = strdup(CommandList);
93         log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
94         return true;
95 }
96
97 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
98 {
99         return true;
100 }
101
102 bool userrec::ProcessNoticeMasks(const char *sm)
103 {
104         bool adding = true;
105         const char *c = sm;
106
107         while (c && *c)
108         {
109                 switch (*c)
110                 {
111                         case '+':
112                                 adding = true;
113                                 break;
114                         case '-':
115                                 adding = false;
116                                 break;
117                         default:
118                                 if ((*c >= 'A') && (*c <= 'z'))
119                                         this->SetNoticeMask(*c, adding);
120                                 break;
121                 }
122
123                 *c++;
124         }
125
126         return true;
127 }
128
129 void userrec::StartDNSLookup()
130 {
131         log(DEBUG,"Commencing reverse lookup");
132         try
133         {
134                 log(DEBUG,"Passing instance: %08x",this->ServerInstance);
135                 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), false);
136                 MyServer->AddResolver(res_reverse);
137         }
138         catch (ModuleException& e)
139         {
140                 log(DEBUG,"Error in resolver: %s",e.GetReason());
141         }
142 }
143
144 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward) :
145         Resolver(Instance, to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
146 {
147         this->fwd = forward;
148         this->bound_fd = user->fd;
149 }
150
151 void UserResolver::OnLookupComplete(const std::string &result)
152 {
153         if ((!this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
154         {
155                 log(DEBUG,"Commencing forward lookup");
156                 this->bound_user->stored_host = result;
157                 try
158                 {
159                         bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, true);
160                         MyServer->AddResolver(bound_user->res_forward);
161                 }
162                 catch (ModuleException& e)
163                 {
164                         log(DEBUG,"Error in resolver: %s",e.GetReason());
165                 }
166         }
167         else if ((this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
168         {
169                 /* Both lookups completed */
170                 if (this->bound_user->GetIPString() == result)
171                 {
172                         std::string hostname = this->bound_user->stored_host;
173                         if (hostname.length() < 65)
174                         {
175                                 /* Hostnames starting with : are not a good thing (tm) */
176                                 if (*(hostname.c_str()) == ':')
177                                         hostname = "0" + hostname;
178
179                                 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
180                                 this->bound_user->dns_done = true;
181                                 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
182                                 strlcpy(this->bound_user->host, hostname.c_str(),64);
183                         }
184                         else
185                         {
186                                 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
187                         }
188                 }
189                 else
190                 {
191                         this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
192                 }
193         }
194 }
195
196 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
197 {
198         if (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user)
199         {
200                 /* Error message here */
201                 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
202                 this->bound_user->dns_done = true;
203         }
204 }
205
206
207 bool userrec::IsNoticeMaskSet(unsigned char sm)
208 {
209         return (snomasks[sm-65]);
210 }
211
212 void userrec::SetNoticeMask(unsigned char sm, bool value)
213 {
214         snomasks[sm-65] = value;
215 }
216
217 const char* userrec::FormatNoticeMasks()
218 {
219         static char data[MAXBUF];
220         int offset = 0;
221
222         for (int n = 0; n < 64; n++)
223         {
224                 if (snomasks[n])
225                         data[offset++] = n+65;
226         }
227
228         data[offset] = 0;
229         return data;
230 }
231
232
233
234 bool userrec::IsModeSet(unsigned char m)
235 {
236         return (modes[m-65]);
237 }
238
239 void userrec::SetMode(unsigned char m, bool value)
240 {
241         modes[m-65] = value;
242 }
243
244 const char* userrec::FormatModes()
245 {
246         static char data[MAXBUF];
247         int offset = 0;
248         for (int n = 0; n < 64; n++)
249         {
250                 if (modes[n])
251                         data[offset++] = n+65;
252         }
253         data[offset] = 0;
254         return data;
255 }
256
257 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
258 {
259         log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
260         // the PROPER way to do it, AVOID bzero at *ALL* costs
261         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
262         server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
263         reset_due = TIME;
264         lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
265         timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
266         haspassed = dns_done = false;
267         recvq = "";
268         sendq = "";
269         WriteError = "";
270         res_forward = res_reverse = NULL;
271         ip = NULL;
272         chans.clear();
273         invites.clear();
274         chans.resize(MAXCHANS);
275         memset(modes,0,sizeof(modes));
276         
277         for (unsigned int n = 0; n < MAXCHANS; n++)
278         {
279                 ucrec* x = new ucrec();
280                 chans[n] = x;
281                 x->channel = NULL;
282                 x->uc_modes = 0;
283         }
284 }
285
286 userrec::~userrec()
287 {
288         for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
289         {
290                 ucrec* x = (ucrec*)*n;
291                 delete x;
292         }
293
294         if (ip)
295         {
296                 if (this->GetProtocolFamily() == AF_INET)
297                 {
298                         delete (sockaddr_in*)ip;
299                 }
300 #ifdef SUPPORT_IP6LINKS
301                 else
302                 {
303                         delete (sockaddr_in6*)ip;
304                 }
305 #endif
306         }
307 }
308
309 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
310 void userrec::MakeHost(char* nhost)
311 {
312         /* This is much faster than snprintf */
313         char* t = nhost;
314         for(char* n = ident; *n; n++)
315                 *t++ = *n;
316         *t++ = '@';
317         for(char* n = host; *n; n++)
318                 *t++ = *n;
319         *t = 0;
320 }
321
322 void userrec::CloseSocket()
323 {
324         shutdown(this->fd,2);
325         close(this->fd);
326 }
327  
328 char* userrec::GetFullHost()
329 {
330         static char result[MAXBUF];
331         char* t = result;
332         for(char* n = nick; *n; n++)
333                 *t++ = *n;
334         *t++ = '!';
335         for(char* n = ident; *n; n++)
336                 *t++ = *n;
337         *t++ = '@';
338         for(char* n = dhost; *n; n++)
339                 *t++ = *n;
340         *t = 0;
341         return result;
342 }
343
344 char* userrec::MakeWildHost()
345 {
346         static char nresult[MAXBUF];
347         char* t = nresult;
348         *t++ = '*';     *t++ = '!';
349         *t++ = '*';     *t++ = '@';
350         for(char* n = dhost; *n; n++)
351                 *t++ = *n;
352         *t = 0;
353         return nresult;
354 }
355
356 int userrec::ReadData(void* buffer, size_t size)
357 {
358         if (this->fd > -1)
359         {
360                 return read(this->fd, buffer, size);
361         }
362         else
363                 return 0;
364 }
365
366
367 char* userrec::GetFullRealHost()
368 {
369         static char fresult[MAXBUF];
370         char* t = fresult;
371         for(char* n = nick; *n; n++)
372                 *t++ = *n;
373         *t++ = '!';
374         for(char* n = ident; *n; n++)
375                 *t++ = *n;
376         *t++ = '@';
377         for(char* n = host; *n; n++)
378                 *t++ = *n;
379         *t = 0;
380         return fresult;
381 }
382
383 bool userrec::IsInvited(irc::string &channel)
384 {
385         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
386         {
387                 irc::string compare = i->channel;
388                 
389                 if (compare == channel)
390                 {
391                         return true;
392                 }
393         }
394         return false;
395 }
396
397 InvitedList* userrec::GetInviteList()
398 {
399         return &invites;
400 }
401
402 void userrec::InviteTo(irc::string &channel)
403 {
404         Invited i;
405         i.channel = channel;
406         invites.push_back(i);
407 }
408
409 void userrec::RemoveInvite(irc::string &channel)
410 {
411         log(DEBUG,"Removing invites");
412         
413         if (invites.size())
414         {
415                 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
416                 {
417                         irc::string compare = i->channel;
418                         
419                         if (compare == channel)
420                         {
421                                 invites.erase(i);
422                                 return;
423                         }
424                 }
425         }
426 }
427
428 bool userrec::HasPermission(const std::string &command)
429 {
430         char* mycmd;
431         char* savept;
432         char* savept2;
433         
434         /*
435          * users on remote servers can completely bypass all permissions based checks.
436          * This prevents desyncs when one server has different type/class tags to another.
437          * That having been said, this does open things up to the possibility of source changes
438          * allowing remote kills, etc - but if they have access to the src, they most likely have
439          * access to the conf - so it's an end to a means either way.
440          */
441         if (!IS_LOCAL(this))
442                 return true;
443         
444         // are they even an oper at all?
445         if (*this->oper)
446         {
447                 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
448                 if (iter_opertype != opertypes.end())
449                 {
450                         char* Classes = strdup(iter_opertype->second);
451                         char* myclass = strtok_r(Classes," ",&savept);
452                         while (myclass)
453                         {
454                                 operclass_t::iterator iter_operclass = operclass.find(myclass);
455                                 if (iter_operclass != operclass.end())
456                                 {
457                                         char* CommandList = strdup(iter_operclass->second);
458                                         mycmd = strtok_r(CommandList," ",&savept2);
459                                         while (mycmd)
460                                         {
461                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
462                                                 {
463                                                         free(Classes);
464                                                         free(CommandList);
465                                                         return true;
466                                                 }
467                                                 mycmd = strtok_r(NULL," ",&savept2);
468                                         }
469                                         free(CommandList);
470                                 }
471                                 myclass = strtok_r(NULL," ",&savept);
472                         }
473                         free(Classes);
474                 }
475         }
476         return false;
477 }
478
479
480 bool userrec::AddBuffer(const std::string &a)
481 {
482         std::string b = "";
483
484         /* NB: std::string is arsey about \r and \n and tries to translate them
485          * somehow, so we CANNOT use std::string::find() here :(
486          */
487         for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
488         {
489                 if (*i != '\r')
490                         b += *i;
491         }
492
493         if (b.length())
494                 recvq.append(b);
495
496         if (recvq.length() > (unsigned)this->recvqmax)
497         {
498                 this->SetWriteError("RecvQ exceeded");
499                 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
500                 return false;
501         }
502
503         return true;
504 }
505
506 bool userrec::BufferIsReady()
507 {
508         return (recvq.find('\n') != std::string::npos);
509 }
510
511 void userrec::ClearBuffer()
512 {
513         recvq = "";
514 }
515
516 std::string userrec::GetBuffer()
517 {
518         if (!recvq.length())
519                 return "";
520
521         /* Strip any leading \r or \n off the string.
522          * Usually there are only one or two of these,
523          * so its is computationally cheap to do.
524          */
525         while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
526                 recvq.erase(recvq.begin());
527
528         for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
529         {
530                 /* Find the first complete line, return it as the
531                  * result, and leave the recvq as whats left
532                  */
533                 if (*x == '\n')
534                 {
535                         std::string ret = std::string(recvq.begin(), x);
536                         recvq.erase(recvq.begin(), x + 1);
537                         return ret;
538                 }
539         }
540         return "";
541 }
542
543 void userrec::AddWriteBuf(const std::string &data)
544 {
545         if (*this->GetWriteError())
546                 return;
547         
548         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
549         {
550                 /*
551                  * Fix by brain - Set the error text BEFORE calling writeopers, because
552                  * if we dont it'll recursively  call here over and over again trying
553                  * to repeatedly add the text to the sendq!
554                  */
555                 this->SetWriteError("SendQ exceeded");
556                 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
557                 return;
558         }
559         
560         if (data.length() > 512)
561         {
562                 std::string newdata(data);
563                 newdata.resize(510);
564                 newdata.append("\r\n");
565                 sendq.append(newdata);
566         }
567         else
568         {
569                 sendq.append(data);
570         }
571 }
572
573 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
574 void userrec::FlushWriteBuf()
575 {
576         if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
577         {
578                 const char* tb = this->sendq.c_str();
579                 int n_sent = write(this->fd,tb,this->sendq.length());
580                 if (n_sent == -1)
581                 {
582                         if (errno != EAGAIN)
583                                 this->SetWriteError(strerror(errno));
584                 }
585                 else
586                 {
587                         // advance the queue
588                         tb += n_sent;
589                         this->sendq = tb;
590                         // update the user's stats counters
591                         this->bytes_out += n_sent;
592                         this->cmds_out++;
593                 }
594         }
595 }
596
597 void userrec::SetWriteError(const std::string &error)
598 {
599         log(DEBUG,"SetWriteError: %s",error.c_str());
600         // don't try to set the error twice, its already set take the first string.
601         if (!this->WriteError.length())
602         {
603                 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
604                 this->WriteError = error;
605         }
606 }
607
608 const char* userrec::GetWriteError()
609 {
610         return this->WriteError.c_str();
611 }
612
613 void userrec::Oper(const std::string &opertype)
614 {
615         this->modes[UM_OPERATOR] = 1;
616         this->WriteServ("MODE %s :+o", this->nick);
617         FOREACH_MOD(I_OnOper, OnOper(this, opertype));
618         log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
619         strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
620         all_opers.push_back(this);
621         FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
622 }
623
624 void userrec::UnOper()
625 {
626         if (*this->oper)
627         {
628                 *this->oper = 0;
629                 this->modes[UM_OPERATOR] = 0;
630                 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
631                 {
632                         if (*a == this)
633                         {
634                                 log(DEBUG,"Oper removed from optimization list");
635                                 all_opers.erase(a);
636                                 return;
637                         }
638                 }
639         }
640 }
641
642 void userrec::QuitUser(InspIRCd* Instance, userrec *user,const std::string &quitreason)
643 {
644         user_hash::iterator iter = Instance->clientlist.find(user->nick);
645
646 /*
647  * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
648  * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
649  *
650  * I can't imagine this blowing up, so I'm commenting it out. We still check
651  * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
652  *
653  *      if (iter == clientlist.end())
654  *              return;
655  */
656         std::string reason = quitreason;
657
658         if (reason.length() > MAXQUIT - 1)
659                 reason.resize(MAXQUIT - 1);
660         
661         if (IS_LOCAL(user))
662                 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
663
664         if (user->registered == REG_ALL)
665         {
666                 user->PurgeEmptyChannels();
667                 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
668                 user->WriteCommonExcept("QUIT :%s",reason.c_str());
669         }
670
671         if (IS_LOCAL(user))
672                 user->FlushWriteBuf();
673
674         FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
675
676         if (IS_LOCAL(user))
677         {
678                 if (Instance->Config->GetIOHook(user->GetPort()))
679                 {
680                         try
681                         {
682                                 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
683                         }
684                         catch (ModuleException& modexcept)
685                         {
686                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
687                         }
688                 }
689                 
690                 Instance->SE->DelFd(user->fd);
691                 user->CloseSocket();
692         }
693
694         /*
695          * this must come before the ServerInstance->WriteOpers so that it doesnt try to fill their buffer with anything
696          * if they were an oper with +s.
697          *
698          * XXX -
699          * In the current implementation, we only show local quits, as we only show local connects. With 
700          * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
701          */
702         if (user->registered == REG_ALL)
703         {
704                 if (IS_LOCAL(user))
705                         Instance->WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
706                 user->AddToWhoWas();
707         }
708
709         if (iter != Instance->clientlist.end())
710         {
711                 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
712                 if (IS_LOCAL(user))
713                 {
714                         Instance->fd_ref_table[user->fd] = NULL;
715                         if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
716                                 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
717                 }
718                 Instance->clientlist.erase(iter);
719                 DELETE(user);
720         }
721 }
722
723 namespace irc
724 {
725         namespace whowas
726         {
727
728                 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
729                 {
730                         this->host = strdup(user->host);
731                         this->dhost = strdup(user->dhost);
732                         this->ident = strdup(user->ident);
733                         this->server = user->server;
734                         this->gecos = strdup(user->fullname);
735                 }
736
737                 WhoWasGroup::~WhoWasGroup()
738                 {
739                         if (host)
740                                 free(host);
741                         if (dhost)
742                                 free(dhost);
743                         if (ident)
744                                 free(ident);
745                         if (gecos)
746                                 free(gecos);
747                 }
748
749                 /* every hour, run this function which removes all entries over 3 days */
750                 void MaintainWhoWas(time_t TIME)
751                 {
752                         for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
753                         {
754                                 whowas_set* n = (whowas_set*)iter->second;
755                                 if (n->size())
756                                 {
757                                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
758                                         {
759                                                 WhoWasGroup *a = *(n->begin());
760                                                 DELETE(a);
761                                                 n->erase(n->begin());
762                                         }
763                                 }
764                         }
765                 }
766         };
767 };
768
769 /* adds or updates an entry in the whowas list */
770 void userrec::AddToWhoWas()
771 {
772         irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
773
774         if (iter == whowas.end())
775         {
776                 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
777                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
778                 n->push_back(a);
779                 whowas[this->nick] = n;
780         }
781         else
782         {
783                 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
784
785                 if (group->size() > 10)
786                 {
787                         irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
788                         DELETE(a);
789                         group->pop_front();
790                 }
791
792                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
793                 group->push_back(a);
794         }
795 }
796
797 /* add a client connection to the sockets list */
798 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
799 {
800         std::string tempnick = ConvToStr(socket) + "-unknown";
801         user_hash::iterator iter = Instance->clientlist.find(tempnick);
802         const char *ipaddr = insp_ntoa(ip);
803         userrec* _new;
804         int j = 0;
805
806         /*
807          * fix by brain.
808          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
809          * using one as a registered connection. As they are per fd, we can also safely assume
810          * that we wont have collisions. Therefore, if the nick exists in the list, its only
811          * used by a dead socket, erase the iterator so that the new client may reclaim it.
812          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
813          * issue in earlier alphas/betas
814          */
815         if (iter != Instance->clientlist.end())
816         {
817                 userrec* goner = iter->second;
818                 DELETE(goner);
819                 Instance->clientlist.erase(iter);
820         }
821
822         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
823         
824         _new = new userrec(Instance);
825         Instance->clientlist[tempnick] = _new;
826         _new->fd = socket;
827         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
828
829         _new->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
830         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
831         strcpy(_new->ident, "unknown");
832
833         _new->registered = REG_NONE;
834         _new->signon = TIME + Instance->Config->dns_timeout;
835         _new->lastping = 1;
836
837         log(DEBUG,"Setting socket addresses");
838         _new->SetSockAddr(AF_FAMILY, ipaddr, port);
839         log(DEBUG,"Socket addresses set.");
840
841         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
842         for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
843                 _new->dhost[j] = _new->host[j] = *temp;
844         _new->dhost[j] = _new->host[j] = 0;
845                         
846         // set the registration timeout for this user
847         unsigned long class_regtimeout = 90;
848         int class_flood = 0;
849         long class_threshold = 5;
850         long class_sqmax = 262144;      // 256kb
851         long class_rqmax = 4096;        // 4k
852
853         for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
854         {
855                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
856                 {
857                         class_regtimeout = (unsigned long)i->registration_timeout;
858                         class_flood = i->flood;
859                         _new->pingmax = i->pingtime;
860                         class_threshold = i->threshold;
861                         class_sqmax = i->sendqmax;
862                         class_rqmax = i->recvqmax;
863                         break;
864                 }
865         }
866
867         _new->nping = TIME + _new->pingmax + Instance->Config->dns_timeout;
868         _new->timeout = TIME+class_regtimeout;
869         _new->flood = class_flood;
870         _new->threshold = class_threshold;
871         _new->sendqmax = class_sqmax;
872         _new->recvqmax = class_rqmax;
873
874         Instance->fd_ref_table[socket] = _new;
875         Instance->local_users.push_back(_new);
876
877         if (Instance->local_users.size() > Instance->Config->SoftLimit)
878         {
879                 userrec::QuitUser(Instance, _new,"No more connections allowed");
880                 return;
881         }
882
883         if (Instance->local_users.size() >= MAXCLIENTS)
884         {
885                 userrec::QuitUser(Instance, _new,"No more connections allowed");
886                 return;
887         }
888
889         /*
890          * XXX -
891          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
892          * its a pretty big but for the moment valid assumption:
893          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
894          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
895          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
896          * which for the time being is a physical impossibility (even the largest networks dont have more
897          * than about 10,000 users on ONE server!)
898          */
899         if ((unsigned)socket >= MAX_DESCRIPTORS)
900         {
901                 userrec::QuitUser(Instance, _new,"Server is full");
902                 return;
903         }
904         char* e = matches_exception(ipaddr);
905         if (!e)
906         {
907                 char* r = matches_zline(ipaddr);
908                 if (r)
909                 {
910                         char reason[MAXBUF];
911                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
912                         userrec::QuitUser(Instance, _new,reason);
913                         return;
914                 }
915         }
916
917         if (socket > -1)
918         {
919                 if (!Instance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
920                 {
921                         userrec::QuitUser(Instance, _new, "Internal error handling connection");
922                         return;
923                 }
924         }
925
926         _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
927 }
928
929 long userrec::GlobalCloneCount()
930 {
931         char u1[1024];
932         char u2[1024];
933         long x = 0;
934         for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
935         {
936                 /* We have to match ip's as strings - we don't know what protocol
937                  * a remote user may be using
938                  */
939                 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
940                                 x++;
941         }
942         return x;
943 }
944
945 long userrec::LocalCloneCount()
946 {
947         long x = 0;
948         for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
949         {
950                 userrec* comp = *a;
951 #ifdef IPV6
952                 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
953                 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
954                 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
955                 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
956                         x++;
957 #else
958                 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
959                 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
960                 if (s1->s_addr == s2->s_addr)
961                         x++;
962 #endif
963         }
964         return x;
965 }
966
967 void userrec::FullConnect(CullList* Goners)
968 {
969         ServerInstance->stats->statsConnects++;
970         this->idle_lastmsg = TIME;
971
972         ConnectClass a = this->GetClass();
973
974         if (a.type == CC_DENY)
975         {
976                 Goners->AddItem(this,"Unauthorised connection");
977                 return;
978         }
979         
980         if ((*(a.pass.c_str())) && (!this->haspassed))
981         {
982                 Goners->AddItem(this,"Invalid password");
983                 return;
984         }
985         
986         if (this->LocalCloneCount() > a.maxlocal)
987         {
988                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
989                 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
990                 return;
991         }
992         else if (this->GlobalCloneCount() > a.maxglobal)
993         {
994                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
995                 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
996                 return;
997         }
998
999         char match_against[MAXBUF];
1000         snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1001         char* e = matches_exception(match_against);
1002
1003         if (!e)
1004         {
1005                 char* r = matches_gline(match_against);
1006                 
1007                 if (r)
1008                 {
1009                         char reason[MAXBUF];
1010                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1011                         Goners->AddItem(this, reason);
1012                         return;
1013                 }
1014                 
1015                 r = matches_kline(match_against);
1016                 
1017                 if (r)
1018                 {
1019                         char reason[MAXBUF];
1020                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1021                         Goners->AddItem(this, reason);
1022                         return;
1023                 }
1024         }
1025
1026
1027         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1028         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1029         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1030         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1031         this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->ParaModeList().c_str());
1032
1033         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1034         // so i'd better split it :)
1035         std::stringstream out(ServerInstance->Config->data005);
1036         std::string token = "";
1037         std::string line5 = "";
1038         int token_counter = 0;
1039         
1040         while (!out.eof())
1041         {
1042                 out >> token;
1043                 line5 = line5 + token + " ";
1044                 token_counter++;
1045                 
1046                 if ((token_counter >= 13) || (out.eof() == true))
1047                 {
1048                         this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1049                         line5 = "";
1050                         token_counter = 0;
1051                 }
1052         }
1053         
1054         ShowMOTD(this);
1055
1056         /*
1057          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1058          * changes dont go out onto the network and produce 'fake direction'.
1059          */
1060         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1061         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1062         this->registered = REG_ALL;
1063         ServerInstance->WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1064 }
1065
1066 /** userrec::UpdateNick()
1067  * re-allocates a nick in the user_hash after they change nicknames,
1068  * returns a pointer to the new user as it may have moved
1069  */
1070 userrec* userrec::UpdateNickHash(const char* New)
1071 {
1072         //user_hash::iterator newnick;
1073         user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1074
1075         if (!strcasecmp(this->nick,New))
1076                 return oldnick->second;
1077
1078         if (oldnick == ServerInstance->clientlist.end())
1079                 return NULL; /* doesnt exist */
1080
1081         userrec* olduser = oldnick->second;
1082         ServerInstance->clientlist[New] = olduser;
1083         ServerInstance->clientlist.erase(oldnick);
1084         return ServerInstance->clientlist[New];
1085 }
1086
1087 bool userrec::ForceNickChange(const char* newnick)
1088 {
1089         char nick[MAXBUF];
1090         int MOD_RESULT = 0;
1091
1092         *nick = 0;
1093
1094         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1095         
1096         if (MOD_RESULT)
1097         {
1098                 ServerInstance->stats->statsCollisions++;
1099                 return false;
1100         }
1101         
1102         if (matches_qline(newnick))
1103         {
1104                 ServerInstance->stats->statsCollisions++;
1105                 return false;
1106         }
1107
1108         if (newnick)
1109         {
1110                 strlcpy(this->nick, newnick, NICKMAX - 1);
1111         }
1112         if (this->registered == REG_ALL)
1113         {
1114                 const char* pars[1];
1115                 pars[0] = nick;
1116                 std::string cmd = "NICK";
1117                 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1118         }
1119         return true;
1120 }
1121
1122 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1123 {
1124         switch (protocol_family)
1125         {
1126 #ifdef SUPPORT_IP6LINKS
1127                 case AF_INET6:
1128                 {
1129                         log(DEBUG,"Set inet6 protocol address");
1130                         sockaddr_in6* sin = new sockaddr_in6;
1131                         sin->sin6_family = AF_INET6;
1132                         sin->sin6_port = port;
1133                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1134                         this->ip = (sockaddr*)sin;
1135                 }
1136                 break;
1137 #endif
1138                 case AF_INET:
1139                 {
1140                         log(DEBUG,"Set inet4 protocol address");
1141                         sockaddr_in* sin = new sockaddr_in;
1142                         sin->sin_family = AF_INET;
1143                         sin->sin_port = port;
1144                         inet_pton(AF_INET, ip, &sin->sin_addr);
1145                         this->ip = (sockaddr*)sin;
1146                 }
1147                 break;
1148                 default:
1149                         log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1150                 break;
1151         }
1152 }
1153
1154 int userrec::GetPort()
1155 {
1156         if (this->ip == NULL)
1157                 return 0;
1158
1159         switch (this->GetProtocolFamily())
1160         {
1161 #ifdef SUPPORT_IP6LINKS
1162                 case AF_INET6:
1163                 {
1164                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1165                         return sin->sin6_port;
1166                 }
1167                 break;
1168 #endif
1169                 case AF_INET:
1170                 {
1171                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1172                         return sin->sin_port;
1173                 }
1174                 break;
1175                 default:
1176                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1177                 break;
1178         }
1179         return 0;
1180 }
1181
1182 int userrec::GetProtocolFamily()
1183 {
1184         if (this->ip == NULL)
1185                 return 0;
1186
1187         sockaddr_in* sin = (sockaddr_in*)this->ip;
1188         return sin->sin_family;
1189 }
1190
1191 const char* userrec::GetIPString()
1192 {
1193         static char buf[1024];
1194         static char temp[1024];
1195
1196         if (this->ip == NULL)
1197                 return "";
1198
1199         switch (this->GetProtocolFamily())
1200         {
1201 #ifdef SUPPORT_IP6LINKS
1202                 case AF_INET6:
1203                 {
1204                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1205                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1206                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1207                         if (*buf == ':')
1208                         {
1209                                 strlcpy(&temp[1], buf, sizeof(temp));
1210                                 *temp = '0';
1211                                 return temp;
1212                         }
1213                         return buf;
1214                 }
1215                 break;
1216 #endif
1217                 case AF_INET:
1218                 {
1219                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1220                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1221                         return buf;
1222                 }
1223                 break;
1224                 default:
1225                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1226                 break;
1227         }
1228         return "";
1229 }
1230
1231 const char* userrec::GetIPString(char* buf)
1232 {
1233         static char temp[1024];
1234
1235         if (this->ip == NULL)
1236         {
1237                 *buf = 0;
1238                 return buf;
1239         }
1240
1241         switch (this->GetProtocolFamily())
1242         {
1243 #ifdef SUPPORT_IP6LINKS
1244                 case AF_INET6:
1245                 {
1246                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1247                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1248                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1249                         if (*buf == ':')
1250                         {
1251                                 strlcpy(&temp[1], buf, sizeof(temp));
1252                                 *temp = '0';
1253                                 strlcpy(buf, temp, sizeof(temp));
1254                         }
1255                         return buf;
1256                 }
1257                 break;
1258 #endif
1259                 case AF_INET:
1260                 {
1261                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1262                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1263                         return buf;
1264                 }
1265                 break;
1266
1267                 default:
1268                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1269                 break;
1270         }
1271         return "";
1272 }
1273
1274
1275 void userrec::Write(const std::string &text)
1276 {
1277         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1278                 return;
1279
1280         std::string crlf = text;
1281         crlf.append("\r\n");
1282
1283         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1284         {
1285                 try
1286                 {
1287                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1288                 }
1289                 catch (ModuleException& modexcept)
1290                 {
1291                         log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1292                 }
1293         }
1294         else
1295         {
1296                 this->AddWriteBuf(crlf);
1297         }
1298         ServerInstance->stats->statsSent += crlf.length();
1299 }
1300
1301 /** Write()
1302  */
1303 void userrec::Write(const char *text, ...)
1304 {
1305         va_list argsPtr;
1306         char textbuffer[MAXBUF];
1307
1308         va_start(argsPtr, text);
1309         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1310         va_end(argsPtr);
1311
1312         this->Write(std::string(textbuffer));
1313 }
1314
1315 void userrec::WriteServ(const std::string& text)
1316 {
1317         char textbuffer[MAXBUF];
1318
1319         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1320         this->Write(std::string(textbuffer));
1321 }
1322
1323 /** WriteServ()
1324  *  Same as Write(), except `text' is prefixed with `:server.name '.
1325  */
1326 void userrec::WriteServ(const char* text, ...)
1327 {
1328         va_list argsPtr;
1329         char textbuffer[MAXBUF];
1330
1331         va_start(argsPtr, text);
1332         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1333         va_end(argsPtr);
1334
1335         this->WriteServ(std::string(textbuffer));
1336 }
1337
1338
1339 void userrec::WriteFrom(userrec *user, const std::string &text)
1340 {
1341         char tb[MAXBUF];
1342
1343         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1344         
1345         this->Write(std::string(tb));
1346 }
1347
1348
1349 /* write text from an originating user to originating user */
1350
1351 void userrec::WriteFrom(userrec *user, const char* text, ...)
1352 {
1353         va_list argsPtr;
1354         char textbuffer[MAXBUF];
1355
1356         va_start(argsPtr, text);
1357         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1358         va_end(argsPtr);
1359
1360         this->WriteFrom(user, std::string(textbuffer));
1361 }
1362
1363
1364 /* write text to an destination user from a source user (e.g. user privmsg) */
1365
1366 void userrec::WriteTo(userrec *dest, const char *data, ...)
1367 {
1368         char textbuffer[MAXBUF];
1369         va_list argsPtr;
1370
1371         va_start(argsPtr, data);
1372         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1373         va_end(argsPtr);
1374
1375         this->WriteTo(dest, std::string(textbuffer));
1376 }
1377
1378 void userrec::WriteTo(userrec *dest, const std::string &data)
1379 {
1380         dest->WriteFrom(this, data);
1381 }
1382
1383
1384 void userrec::WriteCommon(const char* text, ...)
1385 {
1386         char textbuffer[MAXBUF];
1387         va_list argsPtr;
1388
1389         if (this->registered != REG_ALL)
1390                 return;
1391
1392         va_start(argsPtr, text);
1393         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1394         va_end(argsPtr);
1395
1396         this->WriteCommon(std::string(textbuffer));
1397 }
1398
1399 void userrec::WriteCommon(const std::string &text)
1400 {
1401         bool sent_to_at_least_one = false;
1402
1403         if (this->registered != REG_ALL)
1404                 return;
1405
1406         uniq_id++;
1407
1408         for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1409         {
1410                 ucrec *n = *v;
1411                 if (n->channel)
1412                 {
1413                         CUList *ulist= n->channel->GetUsers();
1414
1415                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1416                         {
1417                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1418                                 {
1419                                         already_sent[i->second->fd] = uniq_id;
1420                                         i->second->WriteFrom(this, std::string(text));
1421                                         sent_to_at_least_one = true;
1422                                 }
1423                         }
1424                 }
1425         }
1426
1427         /*
1428          * if the user was not in any channels, no users will receive the text. Make sure the user
1429          * receives their OWN message for WriteCommon
1430          */
1431         if (!sent_to_at_least_one)
1432         {
1433                 this->WriteFrom(this,std::string(text));
1434         }
1435 }
1436
1437
1438 /* write a formatted string to all users who share at least one common
1439  * channel, NOT including the source user e.g. for use in QUIT
1440  */
1441
1442 void userrec::WriteCommonExcept(const char* text, ...)
1443 {
1444         char textbuffer[MAXBUF];
1445         va_list argsPtr;
1446
1447         va_start(argsPtr, text);
1448         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1449         va_end(argsPtr);
1450
1451         this->WriteCommonExcept(std::string(textbuffer));
1452 }
1453
1454 void userrec::WriteCommonExcept(const std::string &text)
1455 {
1456         bool quit_munge = true;
1457         char oper_quit[MAXBUF];
1458         char textbuffer[MAXBUF];
1459
1460         strlcpy(textbuffer, text.c_str(), MAXBUF);
1461
1462         if (this->registered != REG_ALL)
1463                 return;
1464
1465         uniq_id++;
1466
1467         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1468          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1469          * can go byebye.
1470          */
1471         if (ServerInstance->Config->HideSplits)
1472         {
1473                 char* check = textbuffer + 6;
1474
1475                 if (!strncasecmp(textbuffer, "QUIT :",6))
1476                 {
1477                         std::stringstream split(check);
1478                         std::string server_one;
1479                         std::string server_two;
1480
1481                         split >> server_one;
1482                         split >> server_two;
1483
1484                         if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1485                         {
1486                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1487                                 strlcpy(check,"*.net *.split",MAXQUIT);
1488                                 quit_munge = true;
1489                         }
1490                 }
1491         }
1492
1493         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1494         {
1495                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1496                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1497                 {
1498                         char* check = textbuffer + 13;
1499                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1500                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1501                         quit_munge = true;
1502                 }
1503         }
1504
1505         for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1506         {
1507                 ucrec* n = *v;
1508                 if (n->channel)
1509                 {
1510                         CUList *ulist= n->channel->GetUsers();
1511
1512                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1513                         {
1514                                 if (this != i->second)
1515                                 {
1516                                         if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1517                                         {
1518                                                 already_sent[i->second->fd] = uniq_id;
1519                                                 if (quit_munge)
1520                                                         i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1521                                                 else
1522                                                         i->second->WriteFrom(this, std::string(textbuffer));
1523                                         }
1524                                 }
1525                         }
1526                 }
1527         }
1528
1529 }
1530
1531 void userrec::WriteWallOps(const std::string &text)
1532 {
1533         /* Does nothing if theyre not opered */
1534         if ((!*this->oper) && (IS_LOCAL(this)))
1535                 return;
1536
1537         std::string wallop = "WALLOPS :";
1538         wallop.append(text);
1539
1540         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1541         {
1542                 userrec* t = *i;
1543                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1544                         this->WriteTo(t,wallop);
1545         }
1546 }
1547
1548 void userrec::WriteWallOps(const char* text, ...)
1549 {       
1550         char textbuffer[MAXBUF];
1551         va_list argsPtr;
1552
1553         va_start(argsPtr, text);
1554         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1555         va_end(argsPtr);                
1556                                         
1557         this->WriteWallOps(std::string(textbuffer));
1558 }                                      
1559
1560 /* return 0 or 1 depending if users u and u2 share one or more common channels
1561  * (used by QUIT, NICK etc which arent channel specific notices)
1562  *
1563  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1564  * the first users channels then the second users channels within the outer loop,
1565  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1566  * all possible iterations). However this new function instead checks against the
1567  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1568  * and saves us time as we already know what pointer value we are after.
1569  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1570  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1571  */
1572 bool userrec::SharesChannelWith(userrec *other)
1573 {
1574         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1575                 return false;
1576
1577         /* Outer loop */
1578         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1579         {
1580                 /* Fetch the channel from the user */
1581                 ucrec* user_channel = *i;
1582
1583                 if (user_channel->channel)
1584                 {
1585                         /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1586                          * by replacing it with a map::find which *should* be more efficient
1587                          */
1588                         if (user_channel->channel->HasUser(other))
1589                                 return true;
1590                 }
1591         }
1592         return false;
1593 }
1594
1595 int userrec::CountChannels()
1596 {
1597         int z = 0;
1598         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1599                 if ((*i)->channel)
1600                         z++;
1601         return z;
1602 }
1603
1604 bool userrec::ChangeName(const char* gecos)
1605 {
1606         if (IS_LOCAL(this))
1607         {
1608                 int MOD_RESULT = 0;
1609                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1610                 if (MOD_RESULT)
1611                         return false;
1612                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1613         }
1614         strlcpy(this->fullname,gecos,MAXGECOS+1);
1615         return true;
1616 }
1617
1618 bool userrec::ChangeDisplayedHost(const char* host)
1619 {
1620         if (IS_LOCAL(this))
1621         {
1622                 int MOD_RESULT = 0;
1623                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1624                 if (MOD_RESULT)
1625                         return false;
1626                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1627         }
1628         strlcpy(this->dhost,host,63);
1629
1630         if (IS_LOCAL(this))
1631                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1632
1633         return true;
1634 }
1635
1636 void userrec::NoticeAll(char* text, ...)
1637 {
1638         char textbuffer[MAXBUF];
1639         char formatbuffer[MAXBUF];
1640         va_list argsPtr;
1641
1642         va_start(argsPtr, text);
1643         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1644         va_end(argsPtr);
1645
1646         snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1647
1648         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1649         {
1650                 userrec* t = *i;
1651                 t->WriteFrom(this, std::string(formatbuffer));
1652         }
1653 }
1654
1655
1656 std::string userrec::ChannelList(userrec* source)
1657 {
1658         std::string list;
1659         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1660         {
1661                 ucrec* rec = *i;
1662
1663                 if(rec->channel && rec->channel->name)
1664                 {
1665                         /* If the target is the same as the sender, let them see all their channels.
1666                          * If the channel is NOT private/secret OR the user shares a common channel
1667                          * If the user is an oper, and the <options:operspywhois> option is set.
1668                          */
1669                         if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1670                         {
1671                                 list.append(rec->channel->GetStatusChar(this)).append(rec->channel->name).append(" ");
1672                         }
1673                 }
1674         }
1675         return list;
1676 }
1677
1678 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1679 {
1680         std::string line;
1681         std::ostringstream prefix;
1682         std::string::size_type start, pos, length;
1683
1684         prefix << ":" << ServerInstance->Config->ServerName << " 319 " << this->nick << " " << dest->nick << " :";
1685         line = prefix.str();
1686
1687         for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1688         {
1689                 length = (pos == std::string::npos) ? cl.length() : pos;
1690
1691                 if (line.length() + length - start > 510)
1692                 {
1693                         this->Write(line);
1694                         line = prefix.str();
1695                 }
1696
1697                 if(pos == std::string::npos)
1698                 {
1699                         line += cl.substr(start, length - start);
1700                         break;
1701                 }
1702                 else
1703                 {
1704                         line += cl.substr(start, length - start + 1);
1705                 }
1706         }
1707
1708         if (line.length())
1709         {
1710                 this->Write(line);
1711         }
1712 }
1713
1714
1715 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1716  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1717  * then their ip will be taken as 'priority' anyway, so for example,
1718  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1719  */
1720 ConnectClass& userrec::GetClass()
1721 {
1722         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1723         {
1724                 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1725                         return *i;
1726         }
1727
1728         return *(ServerInstance->Config->Classes.begin());
1729 }
1730
1731 void userrec::PurgeEmptyChannels()
1732 {
1733         std::vector<chanrec*> to_delete;
1734
1735         // firstly decrement the count on each channel
1736         for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1737         {
1738                 ucrec* uc = *f;
1739                 if (uc->channel)
1740                 {
1741                         if (uc->channel->DelUser(this) == 0)
1742                         {
1743                                 /* No users left in here, mark it for deletion */
1744                                 to_delete.push_back(uc->channel);
1745                                 uc->channel = NULL;
1746                         }
1747                 }
1748         }
1749
1750         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1751         {
1752                 chanrec* thischan = *n;
1753                 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1754                 if (i2 != ServerInstance->chanlist.end())
1755                 {
1756                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1757                         DELETE(i2->second);
1758                         ServerInstance->chanlist.erase(i2);
1759                 }
1760         }
1761
1762         this->UnOper();
1763 }
1764