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