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