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