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