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