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