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