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