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