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