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