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