]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Fix silly bug of the day.
[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                 user->WriteCommonExcept("QUIT :%s",reason.c_str());
790                 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
791         }
792         else
793         {
794                 Instance->Log(DEBUG,"FULL'O'FAIL! user->registered is %d, REG_ALL is %d", user->registered, REG_ALL);
795         }
796
797         FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
798
799         if (IS_LOCAL(user))
800         {
801                 if (Instance->Config->GetIOHook(user->GetPort()))
802                 {
803                         try
804                         {
805                                 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
806                         }
807                         catch (ModuleException& modexcept)
808                         {
809                                 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
810                         }
811                 }
812                 
813                 Instance->SE->DelFd(user);
814                 user->CloseSocket();
815         }
816
817         /*
818          * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
819          * if they were an oper with +sn +qQ.
820          */
821         if (user->registered == REG_ALL)
822         {
823                 if (IS_LOCAL(user))
824                         Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
825                 else
826                         Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
827                 user->AddToWhoWas();
828         }
829
830         if (iter != Instance->clientlist.end())
831         {
832                 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
833                 if (IS_LOCAL(user))
834                 {
835                         if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
836                                 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
837                 }
838                 Instance->clientlist.erase(iter);
839                 DELETE(user);
840         }
841 }
842
843 namespace irc
844 {
845         namespace whowas
846         {
847
848                 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
849                 {
850                         this->host = strdup(user->host);
851                         this->dhost = strdup(user->dhost);
852                         this->ident = strdup(user->ident);
853                         this->server = user->server;
854                         this->gecos = strdup(user->fullname);
855                 }
856
857                 WhoWasGroup::~WhoWasGroup()
858                 {
859                         if (host)
860                                 free(host);
861                         if (dhost)
862                                 free(dhost);
863                         if (ident)
864                                 free(ident);
865                         if (gecos)
866                                 free(gecos);
867                 }
868
869                 /* every hour, run this function which removes all entries older than Config->WhoWasMaxKeep */
870                 void MaintainWhoWas(InspIRCd* ServerInstance, time_t t)
871                 {
872                         for (whowas_users::iterator iter = ServerInstance->whowas.begin(); iter != ServerInstance->whowas.end(); iter++)
873                         {
874                                 whowas_set* n = (whowas_set*)iter->second;
875                                 if (n->size())
876                                 {
877                                         while ((n->begin() != n->end()) && ((*n->begin())->signon < t - ServerInstance->Config->WhoWasMaxKeep))
878                                         {
879                                                 WhoWasGroup *a = *(n->begin());
880                                                 DELETE(a);
881                                                 n->erase(n->begin());
882                                         }
883                                 }
884                         }
885                 }
886                 /* on rehash, refactor maps according to new conf values */
887                 void PruneWhoWas(InspIRCd* ServerInstance, time_t t)
888                 {
889                         /* config values */
890                         int groupsize = ServerInstance->Config->WhoWasGroupSize;
891                         int maxgroups = ServerInstance->Config->WhoWasMaxGroups;
892                         int maxkeep =   ServerInstance->Config->WhoWasMaxKeep;
893
894                         int groupcount = ServerInstance->whowas.size();
895                         /* iterate whowas_fifo oldest first */
896                         whowas_users_fifo::iterator iter, safeiter;
897                         for (iter = ServerInstance->whowas_fifo.begin(); iter != ServerInstance->whowas_fifo.end(); iter++)
898                         {
899                                 /** prune all groups that has expired due to new maxkeep time and
900                                  *  also any group number higher than new maxgroups. The oldest are
901                                  *  removed first due to iteration over whowas_fifo 
902                                  */
903                                 if (groupcount > maxgroups || iter->first < t - maxkeep)
904                                 {
905                                         whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
906                                         if (n->size())
907                                         {
908                                                 while (n->begin() != n->end())
909                                                 {
910                                                         WhoWasGroup *a = *(n->begin());
911                                                         DELETE(a);
912                                                         n->erase(n->begin());
913                                                 }
914                                         }
915                                         ServerInstance->whowas.erase(iter->second);
916                                         /* use a safe iter copy for erase and set the orig iter old valid ref by decrementing it */
917                                         safeiter = iter;
918                                         --iter;
919                                         ServerInstance->whowas_fifo.erase(safeiter);
920                                 }
921                                 else {
922                                         /* also trim individual groupsizes in case groupsize should have been lowered */
923                                         whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
924                                         if (n->size())
925                                         {
926                                                 int nickcount = n->size();
927                                                 while (n->begin() != n->end() && nickcount > groupsize)
928                                                 {
929                                                         WhoWasGroup *a = *(n->begin());
930                                                         DELETE(a);
931                                                         n->erase(n->begin());
932                                                         nickcount--;
933                                                 }
934                                         }
935                                 }
936                                 groupcount--;
937                         }
938                 }
939         };
940 };
941
942 /* adds or updates an entry in the whowas list */
943 void userrec::AddToWhoWas()
944 {
945         /* if whowas disabled */
946         if (ServerInstance->Config->WhoWasGroupSize == 0 || ServerInstance->Config->WhoWasMaxGroups == 0)
947         {
948                 return;
949         }
950
951         irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
952
953         ServerInstance->Log(DEBUG,"Add to whowas lists");
954
955         if (iter == ServerInstance->whowas.end())
956         {
957                 ServerInstance->Log(DEBUG,"Adding new whowas set for %s",this->nick);
958                 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
959                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
960                 n->push_back(a);
961                 ServerInstance->whowas[this->nick] = n;
962                 ServerInstance->whowas_fifo[ServerInstance->Time()] = this->nick;
963                 if ((int)(ServerInstance->whowas.size()) > ServerInstance->Config->WhoWasMaxGroups)
964                 {
965                         ServerInstance->Log(DEBUG,"Maxgroups of %d reached deleting oldest group '%s'",ServerInstance->Config->WhoWasMaxGroups, ServerInstance->whowas_fifo.begin()->second.c_str());
966                         ServerInstance->whowas.erase(ServerInstance->whowas_fifo.begin()->second);
967                         ServerInstance->whowas_fifo.erase(ServerInstance->whowas_fifo.begin());
968                 }
969         }
970         else
971         {
972                 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
973
974                 ServerInstance->Log(DEBUG,"Using existing whowas group for %s",this->nick);
975
976                 if ((int)(group->size()) >= ServerInstance->Config->WhoWasGroupSize)
977                 {
978                         ServerInstance->Log(DEBUG,"Trimming existing group '%s' to %d entries",this->nick, ServerInstance->Config->WhoWasGroupSize);
979                         irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
980                         DELETE(a);
981                         group->pop_front();
982                 }
983
984                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
985                 group->push_back(a);
986         }
987 }
988
989 /* add a client connection to the sockets list */
990 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
991 {
992         std::string tempnick = ConvToStr(socket) + "-unknown";
993         user_hash::iterator iter = Instance->clientlist.find(tempnick);
994         const char *ipaddr = insp_ntoa(ip);
995         userrec* New;
996         int j = 0;
997
998         /*
999          * fix by brain.
1000          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1001          * using one as a registered connection. As they are per fd, we can also safely assume
1002          * that we wont have collisions. Therefore, if the nick exists in the list, its only
1003          * used by a dead socket, erase the iterator so that the new client may reclaim it.
1004          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
1005          * issue in earlier alphas/betas
1006          */
1007         if (iter != Instance->clientlist.end())
1008         {
1009                 userrec* goner = iter->second;
1010                 DELETE(goner);
1011                 Instance->clientlist.erase(iter);
1012         }
1013
1014         Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
1015
1016         New = new userrec(Instance);
1017         Instance->clientlist[tempnick] = New;
1018         New->fd = socket;
1019         strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
1020
1021         New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
1022         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
1023         strcpy(New->ident, "unknown");
1024
1025         New->registered = REG_NONE;
1026         New->signon = Instance->Time() + Instance->Config->dns_timeout;
1027         New->lastping = 1;
1028
1029         New->SetSockAddr(AF_FAMILY, ipaddr, port);
1030
1031         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
1032         for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
1033                 New->dhost[j] = New->host[j] = *temp;
1034         New->dhost[j] = New->host[j] = 0;
1035
1036         Instance->AddLocalClone(New);
1037         Instance->AddGlobalClone(New);
1038
1039         // set the registration timeout for this user
1040         unsigned long class_regtimeout = 90;
1041         int class_flood = 0;
1042         long class_threshold = 5;
1043         long class_sqmax = 262144;      // 256kb
1044         long class_rqmax = 4096;        // 4k
1045
1046         for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
1047         {
1048                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
1049                 {
1050                         class_regtimeout = (unsigned long)i->registration_timeout;
1051                         class_flood = i->flood;
1052                         New->pingmax = i->pingtime;
1053                         class_threshold = i->threshold;
1054                         class_sqmax = i->sendqmax;
1055                         class_rqmax = i->recvqmax;
1056                         break;
1057                 }
1058         }
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->local_users.push_back(New);
1068
1069         if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
1070         {
1071                 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
1072                 userrec::QuitUser(Instance, New,"No more connections allowed");
1073                 return;
1074         }
1075
1076         /*
1077          * XXX -
1078          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1079          * its a pretty big but for the moment valid assumption:
1080          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
1081          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1082          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
1083          * which for the time being is a physical impossibility (even the largest networks dont have more
1084          * than about 10,000 users on ONE server!)
1085          */
1086         if ((unsigned int)socket >= MAX_DESCRIPTORS)
1087         {
1088                 userrec::QuitUser(Instance, New, "Server is full");
1089                 return;
1090         }
1091
1092         New->exempt = (Instance->XLines->matches_exception(New) != NULL);
1093         if (!New->exempt)
1094         {
1095                 ZLine* r = Instance->XLines->matches_zline(ipaddr);
1096                 if (r)
1097                 {
1098                         char reason[MAXBUF];
1099                         snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
1100                         userrec::QuitUser(Instance, New, reason);
1101                         return;
1102                 }
1103         }
1104
1105         if (socket > -1)
1106         {
1107                 if (!Instance->SE->AddFd(New))
1108                 {
1109                         userrec::QuitUser(Instance, New, "Internal error handling connection");
1110                         return;
1111                 }
1112         }
1113
1114         /* NOTE: even if dns lookups are *off*, we still need to display this.
1115          * BOPM and other stuff requires it.
1116          */
1117         New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
1118 }
1119
1120 long userrec::GlobalCloneCount()
1121 {
1122         clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
1123         if (x != ServerInstance->global_clones.end())
1124                 return x->second;
1125         else
1126                 return 0;
1127 }
1128
1129 long userrec::LocalCloneCount()
1130 {
1131         clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
1132         if (x != ServerInstance->local_clones.end())
1133                 return x->second;
1134         else
1135                 return 0;
1136 }
1137
1138 void userrec::FullConnect(CullList* Goners)
1139 {
1140         ServerInstance->stats->statsConnects++;
1141         this->idle_lastmsg = ServerInstance->Time();
1142
1143         ConnectClass a = this->GetClass();
1144
1145         if (a.type == CC_DENY)
1146         {
1147                 Goners->AddItem(this,"Unauthorised connection");
1148                 return;
1149         }
1150         
1151         if ((*(a.pass.c_str())) && (!this->haspassed))
1152         {
1153                 Goners->AddItem(this,"Invalid password");
1154                 return;
1155         }
1156         
1157         if (this->LocalCloneCount() > a.maxlocal)
1158         {
1159                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1160                 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1161                 return;
1162         }
1163         else if (this->GlobalCloneCount() > a.maxglobal)
1164         {
1165                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1166                 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1167                 return;
1168         }
1169
1170         if (!this->exempt)
1171         {
1172                 GLine* r = ServerInstance->XLines->matches_gline(this);
1173                 
1174                 if (r)
1175                 {
1176                         char reason[MAXBUF];
1177                         snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1178                         Goners->AddItem(this, reason);
1179                         return;
1180                 }
1181                 
1182                 KLine* n = ServerInstance->XLines->matches_kline(this);
1183                 
1184                 if (n)
1185                 {
1186                         char reason[MAXBUF];
1187                         snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1188                         Goners->AddItem(this, reason);
1189                         return;
1190                 }
1191         }
1192
1193
1194         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1195         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1196         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1197         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1198         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());
1199
1200         ServerInstance->Config->Send005(this);
1201
1202         this->ShowMOTD();
1203
1204         /*
1205          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1206          * changes dont go out onto the network and produce 'fake direction'.
1207          */
1208         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1209
1210         this->registered = REG_ALL;
1211
1212         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1213
1214         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1215 }
1216
1217 /** userrec::UpdateNick()
1218  * re-allocates a nick in the user_hash after they change nicknames,
1219  * returns a pointer to the new user as it may have moved
1220  */
1221 userrec* userrec::UpdateNickHash(const char* New)
1222 {
1223         try
1224         {
1225                 //user_hash::iterator newnick;
1226                 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1227
1228                 if (!strcasecmp(this->nick,New))
1229                         return oldnick->second;
1230
1231                 if (oldnick == ServerInstance->clientlist.end())
1232                         return NULL; /* doesnt exist */
1233
1234                 userrec* olduser = oldnick->second;
1235                 ServerInstance->clientlist[New] = olduser;
1236                 ServerInstance->clientlist.erase(oldnick);
1237                 return ServerInstance->clientlist[New];
1238         }
1239
1240         catch (...)
1241         {
1242                 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1243                 return NULL;
1244         }
1245 }
1246
1247 bool userrec::ForceNickChange(const char* newnick)
1248 {
1249         try
1250         {
1251                 int MOD_RESULT = 0;
1252         
1253                 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1254
1255                 if (MOD_RESULT)
1256                 {
1257                         ServerInstance->stats->statsCollisions++;
1258                         return false;
1259                 }
1260         
1261                 if (ServerInstance->XLines->matches_qline(newnick))
1262                 {
1263                         ServerInstance->stats->statsCollisions++;
1264                         return false;
1265                 }
1266
1267                 if (this->registered == REG_ALL)
1268                 {
1269                         const char* pars[1];
1270                         pars[0] = newnick;
1271                         std::string cmd = "NICK";
1272                         return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1273                 }
1274                 return false;
1275         }
1276
1277         catch (...)
1278         {
1279                 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1280                 return false;
1281         }
1282 }
1283
1284 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1285 {
1286         switch (protocol_family)
1287         {
1288 #ifdef SUPPORT_IP6LINKS
1289                 case AF_INET6:
1290                 {
1291                         ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1292                         sockaddr_in6* sin = new sockaddr_in6;
1293                         sin->sin6_family = AF_INET6;
1294                         sin->sin6_port = port;
1295                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1296                         this->ip = (sockaddr*)sin;
1297                 }
1298                 break;
1299 #endif
1300                 case AF_INET:
1301                 {
1302                         ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1303                         sockaddr_in* sin = new sockaddr_in;
1304                         sin->sin_family = AF_INET;
1305                         sin->sin_port = port;
1306                         inet_pton(AF_INET, ip, &sin->sin_addr);
1307                         this->ip = (sockaddr*)sin;
1308                 }
1309                 break;
1310                 default:
1311                         ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1312                 break;
1313         }
1314 }
1315
1316 int userrec::GetPort()
1317 {
1318         if (this->ip == NULL)
1319                 return 0;
1320
1321         switch (this->GetProtocolFamily())
1322         {
1323 #ifdef SUPPORT_IP6LINKS
1324                 case AF_INET6:
1325                 {
1326                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1327                         return sin->sin6_port;
1328                 }
1329                 break;
1330 #endif
1331                 case AF_INET:
1332                 {
1333                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1334                         return sin->sin_port;
1335                 }
1336                 break;
1337                 default:
1338                 break;
1339         }
1340         return 0;
1341 }
1342
1343 int userrec::GetProtocolFamily()
1344 {
1345         if (this->ip == NULL)
1346                 return 0;
1347
1348         sockaddr_in* sin = (sockaddr_in*)this->ip;
1349         return sin->sin_family;
1350 }
1351
1352 const char* userrec::GetIPString()
1353 {
1354         static char buf[1024];
1355
1356         if (this->ip == NULL)
1357                 return "";
1358
1359         switch (this->GetProtocolFamily())
1360         {
1361 #ifdef SUPPORT_IP6LINKS
1362                 case AF_INET6:
1363                 {
1364                         static char temp[1024];
1365                 
1366                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1367                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1368                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1369                         if (*buf == ':')
1370                         {
1371                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1372                                 *temp = '0';
1373                                 return temp;
1374                         }
1375                         return buf;
1376                 }
1377                 break;
1378 #endif
1379                 case AF_INET:
1380                 {
1381                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1382                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1383                         return buf;
1384                 }
1385                 break;
1386                 default:
1387                 break;
1388         }
1389         return "";
1390 }
1391
1392 const char* userrec::GetIPString(char* buf)
1393 {
1394         if (this->ip == NULL)
1395         {
1396                 *buf = 0;
1397                 return buf;
1398         }
1399
1400         switch (this->GetProtocolFamily())
1401         {
1402 #ifdef SUPPORT_IP6LINKS
1403                 case AF_INET6:
1404                 {
1405                         static char temp[1024];
1406                 
1407                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1408                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1409                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1410                         if (*buf == ':')
1411                         {
1412                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1413                                 *temp = '0';
1414                                 strlcpy(buf, temp, sizeof(temp));
1415                         }
1416                         return buf;
1417                 }
1418                 break;
1419 #endif
1420                 case AF_INET:
1421                 {
1422                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1423                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1424                         return buf;
1425                 }
1426                 break;
1427
1428                 default:
1429                 break;
1430         }
1431         return "";
1432 }
1433
1434 /** NOTE: We cannot pass a const reference to this method.
1435  * The string is changed by the workings of the method,
1436  * so that if we pass const ref, we end up copying it to
1437  * something we can change anyway. Makes sense to just let
1438  * the compiler do that copy for us.
1439  */
1440 void userrec::Write(std::string text)
1441 {
1442         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1443                 return;
1444
1445         try
1446         {
1447                 text.append("\r\n");
1448         }
1449         catch (...)
1450         {
1451                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1452                 return;
1453         }
1454
1455         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1456         {
1457                 try
1458                 {
1459                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1460                 }
1461                 catch (ModuleException& modexcept)
1462                 {
1463                         ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1464                 }
1465         }
1466         else
1467         {
1468                 this->AddWriteBuf(text);
1469         }
1470         ServerInstance->stats->statsSent += text.length();
1471         this->ServerInstance->SE->WantWrite(this);
1472 }
1473
1474 /** Write()
1475  */
1476 void userrec::Write(const char *text, ...)
1477 {
1478         va_list argsPtr;
1479         char textbuffer[MAXBUF];
1480
1481         va_start(argsPtr, text);
1482         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1483         va_end(argsPtr);
1484
1485         this->Write(std::string(textbuffer));
1486 }
1487
1488 void userrec::WriteServ(const std::string& text)
1489 {
1490         char textbuffer[MAXBUF];
1491
1492         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1493         this->Write(std::string(textbuffer));
1494 }
1495
1496 /** WriteServ()
1497  *  Same as Write(), except `text' is prefixed with `:server.name '.
1498  */
1499 void userrec::WriteServ(const char* text, ...)
1500 {
1501         va_list argsPtr;
1502         char textbuffer[MAXBUF];
1503
1504         va_start(argsPtr, text);
1505         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1506         va_end(argsPtr);
1507
1508         this->WriteServ(std::string(textbuffer));
1509 }
1510
1511
1512 void userrec::WriteFrom(userrec *user, const std::string &text)
1513 {
1514         char tb[MAXBUF];
1515
1516         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1517         
1518         this->Write(std::string(tb));
1519 }
1520
1521
1522 /* write text from an originating user to originating user */
1523
1524 void userrec::WriteFrom(userrec *user, const char* text, ...)
1525 {
1526         va_list argsPtr;
1527         char textbuffer[MAXBUF];
1528
1529         va_start(argsPtr, text);
1530         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1531         va_end(argsPtr);
1532
1533         this->WriteFrom(user, std::string(textbuffer));
1534 }
1535
1536
1537 /* write text to an destination user from a source user (e.g. user privmsg) */
1538
1539 void userrec::WriteTo(userrec *dest, const char *data, ...)
1540 {
1541         char textbuffer[MAXBUF];
1542         va_list argsPtr;
1543
1544         va_start(argsPtr, data);
1545         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1546         va_end(argsPtr);
1547
1548         this->WriteTo(dest, std::string(textbuffer));
1549 }
1550
1551 void userrec::WriteTo(userrec *dest, const std::string &data)
1552 {
1553         dest->WriteFrom(this, data);
1554 }
1555
1556
1557 void userrec::WriteCommon(const char* text, ...)
1558 {
1559         char textbuffer[MAXBUF];
1560         va_list argsPtr;
1561
1562         if (this->registered != REG_ALL)
1563                 return;
1564
1565         va_start(argsPtr, text);
1566         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1567         va_end(argsPtr);
1568
1569         this->WriteCommon(std::string(textbuffer));
1570 }
1571
1572 void userrec::WriteCommon(const std::string &text)
1573 {
1574         try
1575         {
1576                 bool sent_to_at_least_one = false;
1577         
1578                 if (this->registered != REG_ALL)
1579                         return;
1580         
1581                 uniq_id++;
1582         
1583                 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1584                 {
1585                         CUList* ulist = v->first->GetUsers();
1586                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1587                         {
1588                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1589                                 {
1590                                         already_sent[i->second->fd] = uniq_id;
1591                                         i->second->WriteFrom(this, std::string(text));
1592                                         sent_to_at_least_one = true;
1593                                 }
1594                         }
1595                 }
1596         
1597                 /*
1598                  * if the user was not in any channels, no users will receive the text. Make sure the user
1599                  * receives their OWN message for WriteCommon
1600                  */
1601                 if (!sent_to_at_least_one)
1602                 {
1603                         this->WriteFrom(this,std::string(text));
1604                 }
1605         }
1606
1607         catch (...)
1608         {
1609                 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1610         }
1611 }
1612
1613
1614 /* write a formatted string to all users who share at least one common
1615  * channel, NOT including the source user e.g. for use in QUIT
1616  */
1617
1618 void userrec::WriteCommonExcept(const char* text, ...)
1619 {
1620         char textbuffer[MAXBUF];
1621         va_list argsPtr;
1622
1623         va_start(argsPtr, text);
1624         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1625         va_end(argsPtr);
1626
1627         this->WriteCommonExcept(std::string(textbuffer));
1628 }
1629
1630 void userrec::WriteCommonExcept(const std::string &text)
1631 {
1632         bool quit_munge = false;
1633         char oper_quit[MAXBUF];
1634         char textbuffer[MAXBUF];
1635
1636         strlcpy(textbuffer, text.c_str(), MAXBUF);
1637
1638         if (this->registered != REG_ALL)
1639                 return;
1640
1641         uniq_id++;
1642
1643         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1644          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1645          * can go byebye.
1646          */
1647         if (ServerInstance->Config->HideSplits)
1648         {
1649                 char* check = textbuffer + 6;
1650
1651                 if (!strncasecmp(textbuffer, "QUIT :",6))
1652                 {
1653                         std::stringstream split(check);
1654                         std::string server_one;
1655                         std::string server_two;
1656
1657                         split >> server_one;
1658                         split >> server_two;
1659
1660                         if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1661                         {
1662                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1663                                 strlcpy(check,"*.net *.split",MAXQUIT);
1664                                 quit_munge = true;
1665                         }
1666                 }
1667         }
1668
1669         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1670         {
1671                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1672                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1673                 {
1674                         char* check = textbuffer + 13;
1675                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1676                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1677                         quit_munge = true;
1678                 }
1679         }
1680
1681         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1682         {
1683                 CUList *ulist = v->first->GetUsers();
1684                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1685                 {
1686                         if (this != i->second)
1687                         {
1688                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1689                                 {
1690                                         already_sent[i->second->fd] = uniq_id;
1691                                         if (quit_munge)
1692                                                 i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1693                                         else
1694                                                 i->second->WriteFrom(this, std::string(textbuffer));
1695                                 }
1696                         }
1697                 }
1698         }
1699
1700 }
1701
1702 void userrec::WriteWallOps(const std::string &text)
1703 {
1704         /* Does nothing if theyre not opered */
1705         if ((!*this->oper) && (IS_LOCAL(this)))
1706                 return;
1707
1708         std::string wallop = "WALLOPS :";
1709
1710         try
1711         {
1712                 wallop.append(text);
1713         }
1714         catch (...)
1715         {
1716                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1717                 return;
1718         }
1719
1720         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1721         {
1722                 userrec* t = *i;
1723                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1724                         this->WriteTo(t,wallop);
1725         }
1726 }
1727
1728 void userrec::WriteWallOps(const char* text, ...)
1729 {       
1730         char textbuffer[MAXBUF];
1731         va_list argsPtr;
1732
1733         va_start(argsPtr, text);
1734         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1735         va_end(argsPtr);                
1736                                         
1737         this->WriteWallOps(std::string(textbuffer));
1738 }                                      
1739
1740 /* return 0 or 1 depending if users u and u2 share one or more common channels
1741  * (used by QUIT, NICK etc which arent channel specific notices)
1742  *
1743  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1744  * the first users channels then the second users channels within the outer loop,
1745  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1746  * all possible iterations). However this new function instead checks against the
1747  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1748  * and saves us time as we already know what pointer value we are after.
1749  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1750  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1751  */
1752 bool userrec::SharesChannelWith(userrec *other)
1753 {
1754         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1755                 return false;
1756
1757         /* Outer loop */
1758         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1759         {
1760                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1761                  * by replacing it with a map::find which *should* be more efficient
1762                  */
1763                 if (i->first->HasUser(other))
1764                         return true;
1765         }
1766         return false;
1767 }
1768
1769 int userrec::CountChannels()
1770 {
1771         return ChannelCount;
1772 }
1773
1774 void userrec::ModChannelCount(int n)
1775 {
1776         ChannelCount += n;
1777 }
1778
1779 bool userrec::ChangeName(const char* gecos)
1780 {
1781         if (!strcmp(gecos, this->fullname))
1782                 return true;
1783
1784         if (IS_LOCAL(this))
1785         {
1786                 int MOD_RESULT = 0;
1787                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1788                 if (MOD_RESULT)
1789                         return false;
1790                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1791         }
1792         strlcpy(this->fullname,gecos,MAXGECOS+1);
1793         return true;
1794 }
1795
1796 bool userrec::ChangeDisplayedHost(const char* host)
1797 {
1798         if (!strcmp(host, this->dhost))
1799                 return true;
1800
1801         if (IS_LOCAL(this))
1802         {
1803                 int MOD_RESULT = 0;
1804                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1805                 if (MOD_RESULT)
1806                         return false;
1807                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1808         }
1809         if (this->ServerInstance->Config->CycleHosts)
1810                 this->WriteCommonExcept("QUIT :Changing hosts");
1811
1812         /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1813         strlcpy(this->dhost,host,64);
1814
1815         if (this->ServerInstance->Config->CycleHosts)
1816         {
1817                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1818                 {
1819                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1820                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1821                         if (n.length() > 0)
1822                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1823                 }
1824         }
1825
1826         if (IS_LOCAL(this))
1827                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1828
1829         return true;
1830 }
1831
1832 bool userrec::ChangeIdent(const char* newident)
1833 {
1834         if (!strcmp(newident, this->ident))
1835                 return true;
1836
1837         if (this->ServerInstance->Config->CycleHosts)
1838                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1839
1840         strlcpy(this->ident, newident, IDENTMAX+2);
1841
1842         if (this->ServerInstance->Config->CycleHosts)
1843         {
1844                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1845                 {
1846                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1847                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1848                         if (n.length() > 0)
1849                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1850                 }
1851         }
1852
1853         return true;
1854 }
1855
1856 void userrec::NoticeAll(char* text, ...)
1857 {
1858         char textbuffer[MAXBUF];
1859         char formatbuffer[MAXBUF];
1860         va_list argsPtr;
1861
1862         va_start(argsPtr, text);
1863         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1864         va_end(argsPtr);
1865
1866         snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1867
1868         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1869         {
1870                 userrec* t = *i;
1871                 t->WriteFrom(this, std::string(formatbuffer));
1872         }
1873 }
1874
1875
1876 std::string userrec::ChannelList(userrec* source)
1877 {
1878         try
1879         {
1880                 std::string list;
1881                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1882                 {
1883                         /* If the target is the same as the sender, let them see all their channels.
1884                          * If the channel is NOT private/secret OR the user shares a common channel
1885                          * If the user is an oper, and the <options:operspywhois> option is set.
1886                          */
1887                         if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1888                         {
1889                                 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1890                         }
1891                 }
1892                 return list;
1893         }
1894         catch (...)
1895         {
1896                 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1897                 return "";
1898         }
1899 }
1900
1901 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1902 {
1903         std::string line;
1904         std::ostringstream prefix;
1905         std::string::size_type start, pos, length;
1906
1907         try
1908         {
1909                 prefix << this->nick << " " << dest->nick << " :";
1910                 line = prefix.str();
1911                 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1912         
1913                 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1914                 {
1915                         length = (pos == std::string::npos) ? cl.length() : pos;
1916         
1917                         if (line.length() + namelen + length - start > 510)
1918                         {
1919                                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1920                                 line = prefix.str();
1921                         }
1922         
1923                         if(pos == std::string::npos)
1924                         {
1925                                 line.append(cl.substr(start, length - start));
1926                                 break;
1927                         }
1928                         else
1929                         {
1930                                 line.append(cl.substr(start, length - start + 1));
1931                         }
1932                 }
1933         
1934                 if (line.length())
1935                 {
1936                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1937                 }
1938         }
1939
1940         catch (...)
1941         {
1942                 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1943         }
1944 }
1945
1946
1947 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1948  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1949  * then their ip will be taken as 'priority' anyway, so for example,
1950  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1951  */
1952 ConnectClass& userrec::GetClass()
1953 {
1954         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1955         {
1956                 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1957                         return *i;
1958         }
1959
1960         return *(ServerInstance->Config->Classes.begin());
1961 }
1962
1963 void userrec::PurgeEmptyChannels()
1964 {
1965         ServerInstance->Log(DEBUG,"In PurgeEmptyChannels");
1966         std::vector<chanrec*> to_delete;
1967
1968         // firstly decrement the count on each channel
1969         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1970         {
1971                 ServerInstance->Log(DEBUG,"Iterate channel %s", f->first->name);
1972                 f->first->RemoveAllPrefixes(this);
1973                 if (f->first->DelUser(this) == 0)
1974                 {
1975                         /* No users left in here, mark it for deletion */
1976                         try
1977                         {
1978                                 to_delete.push_back(f->first);
1979                         }
1980                         catch (...)
1981                         {
1982                                 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1983                         }
1984                 }
1985         }
1986
1987         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1988         {
1989                 chanrec* thischan = *n;
1990                 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
1991                 if (i2 != ServerInstance->chanlist.end())
1992                 {
1993                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1994                         DELETE(i2->second);
1995                         ServerInstance->chanlist.erase(i2);
1996                 }
1997         }
1998
1999         this->UnOper();
2000 }
2001
2002 void userrec::ShowMOTD()
2003 {
2004         if (!ServerInstance->Config->MOTD.size())
2005         {
2006                 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
2007                 return;
2008         }
2009         this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
2010
2011         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
2012                 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
2013
2014         this->WriteServ("376 %s :End of message of the day.", this->nick);
2015 }
2016
2017 void userrec::ShowRULES()
2018 {
2019         if (!ServerInstance->Config->RULES.size())
2020         {
2021                 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
2022                 return;
2023         }
2024         this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
2025
2026         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
2027                 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
2028
2029         this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
2030 }
2031
2032 void userrec::HandleEvent(EventType et, int errornum)
2033 {
2034         /* WARNING: May delete this user! */
2035         try
2036         {
2037                 switch (et)
2038                 {
2039                         case EVENT_READ:
2040                                 ServerInstance->ProcessUser(this);
2041
2042                         break;
2043                         case EVENT_WRITE:
2044                                 this->FlushWriteBuf();
2045                         break;
2046                         case EVENT_ERROR:
2047                                 /** This should be safe, but dont DARE do anything after it -- Brain */
2048                                 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
2049                         break;
2050                 }
2051         }
2052         catch (...)
2053         {
2054                 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
2055         }
2056
2057         /* If the user has raised an error whilst being processed, quit them now we're safe to */
2058         if (!WriteError.empty())
2059         {
2060                 ServerInstance->Log(DEBUG,"Write error is set, quitting user with error '%s'", GetWriteError());
2061                 userrec::QuitUser(ServerInstance, this, GetWriteError());
2062         }
2063 }
2064