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