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