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