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