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