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