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