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