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