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