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