]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
6faea40ce1f36625424d16407011143b5c295449
[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 #include "helperfuncs.h"
27 #include "typedefs.h"
28 #include "socketengine.h"
29 #include "hashcomp.h"
30 #include "message.h"
31 #include "wildcard.h"
32 #include "xline.h"
33 #include "cull_list.h"
34
35 extern InspIRCd* ServerInstance;
36 extern std::vector<Module*> modules;
37 extern std::vector<ircd_module*> factory;
38 extern std::vector<InspSocket*> module_sockets;
39 extern int MODCOUNT;
40 extern time_t TIME;
41 extern user_hash clientlist;
42 extern Server* MyServer;
43 extern std::vector<userrec*> local_users;
44
45 irc::whowas::whowas_users whowas;
46 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
47 std::vector<userrec*> all_opers;
48
49 typedef std::map<irc::string,char*> opertype_t;
50 typedef opertype_t operclass_t;
51
52 opertype_t opertypes;
53 operclass_t operclass;
54
55 /* XXX: Used for speeding up WriteCommon operations */
56 unsigned long uniq_id = 0;
57
58 bool InitTypes(ServerConfig* conf, const char* tag)
59 {
60         for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
61         {
62                 if (n->second)
63                         delete[] n->second;
64         }
65         
66         opertypes.clear();
67         return true;
68 }
69
70 bool InitClasses(ServerConfig* conf, const char* tag)
71 {
72         for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
73         {
74                 if (n->second)
75                         delete[] n->second;
76         }
77         
78         operclass.clear();
79         return true;
80 }
81
82 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
83 {
84         char* TypeName = (char*)values[0];
85         char* Classes = (char*)values[1];
86         
87         opertypes[TypeName] = strdup(Classes);
88         log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
89         return true;
90 }
91
92 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
93 {
94         char* ClassName = (char*)values[0];
95         char* CommandList = (char*)values[1];
96         
97         operclass[ClassName] = strdup(CommandList);
98         log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
99         return true;
100 }
101
102 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
103 {
104         return true;
105 }
106
107 bool userrec::ProcessNoticeMasks(const char *sm)
108 {
109         bool adding = true;
110         const char *c = sm;
111
112         while (c && *c)
113         {
114                 switch (*c)
115                 {
116                         case '+':
117                                 adding = true;
118                                 break;
119                         case '-':
120                                 adding = false;
121                                 break;
122                         default:
123                                 if ((*c >= 'A') && (*c <= 'z'))
124                                         this->SetNoticeMask(*c, adding);
125                                 break;
126                 }
127
128                 *c++;
129         }
130
131         return true;
132 }
133
134 void userrec::StartDNSLookup()
135 {
136         log(DEBUG,"Commencing reverse lookup");
137         try
138         {
139                 res_reverse = new UserResolver(this, this->GetIPString(), false);
140                 MyServer->AddResolver(res_reverse);
141         }
142         catch (ModuleException& e)
143         {
144                 log(DEBUG,"Error in resolver: %s",e.GetReason());
145         }
146 }
147
148 UserResolver::UserResolver(userrec* user, std::string to_resolve, bool forward) : Resolver(to_resolve, forward ? DNS_QUERY_FORWARD : DNS_QUERY_REVERSE), bound_user(user)
149 {
150         this->fwd = forward;
151         this->bound_fd = user->fd;
152 }
153
154 void UserResolver::OnLookupComplete(const std::string &result)
155 {
156         if ((!this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
157         {
158                 log(DEBUG,"Commencing forward lookup");
159                 this->bound_user->stored_host = result;
160                 try
161                 {
162                         bound_user->res_forward = new UserResolver(this->bound_user, result, true);
163                         MyServer->AddResolver(bound_user->res_forward);
164                 }
165                 catch (ModuleException& e)
166                 {
167                         log(DEBUG,"Error in resolver: %s",e.GetReason());
168                 }
169         }
170         else if ((this->fwd) && (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user))
171         {
172                 /* Both lookups completed */
173                 if (this->bound_user->GetIPString() == result)
174                 {
175                         std::string hostname = this->bound_user->stored_host;
176                         if (hostname.length() < 65)
177                         {
178                                 /* Hostnames starting with : are not a good thing (tm) */
179                                 if (*(hostname.c_str()) == ':')
180                                         hostname = "0" + hostname;
181
182                                 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
183                                 this->bound_user->dns_done = true;
184                                 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
185                                 strlcpy(this->bound_user->host, hostname.c_str(),64);
186                         }
187                         else
188                         {
189                                 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());
190                         }
191                 }
192                 else
193                 {
194                         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());
195                 }
196         }
197 }
198
199 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
200 {
201         if (ServerInstance->fd_ref_table[this->bound_fd] == this->bound_user)
202         {
203                 /* Error message here */
204                 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
205                 this->bound_user->dns_done = true;
206         }
207 }
208
209
210 bool userrec::IsNoticeMaskSet(unsigned char sm)
211 {
212         return (snomasks[sm-65]);
213 }
214
215 void userrec::SetNoticeMask(unsigned char sm, bool value)
216 {
217         snomasks[sm-65] = value;
218 }
219
220 const char* userrec::FormatNoticeMasks()
221 {
222         static char data[MAXBUF];
223         int offset = 0;
224
225         for (int n = 0; n < 64; n++)
226         {
227                 if (snomasks[n])
228                         data[offset++] = n+65;
229         }
230
231         data[offset] = 0;
232         return data;
233 }
234
235
236
237 bool userrec::IsModeSet(unsigned char m)
238 {
239         return (modes[m-65]);
240 }
241
242 void userrec::SetMode(unsigned char m, bool value)
243 {
244         modes[m-65] = value;
245 }
246
247 const char* userrec::FormatModes()
248 {
249         static char data[MAXBUF];
250         int offset = 0;
251         for (int n = 0; n < 64; n++)
252         {
253                 if (modes[n])
254                         data[offset++] = n+65;
255         }
256         data[offset] = 0;
257         return data;
258 }
259
260 userrec::userrec()
261 {
262         // the PROPER way to do it, AVOID bzero at *ALL* costs
263         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
264         server = (char*)FindServerNamePtr(ServerInstance->Config->ServerName);
265         reset_due = TIME;
266         lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
267         timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
268         haspassed = dns_done = false;
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         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
482 bool userrec::AddBuffer(const std::string &a)
483 {
484         std::string b = "";
485
486         /* NB: std::string is arsey about \r and \n and tries to translate them
487          * somehow, so we CANNOT use std::string::find() here :(
488          */
489         for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
490         {
491                 if (*i != '\r')
492                         b += *i;
493         }
494
495         if (b.length())
496                 recvq.append(b);
497
498         if (recvq.length() > (unsigned)this->recvqmax)
499         {
500                 this->SetWriteError("RecvQ exceeded");
501                 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
502                 return false;
503         }
504
505         return true;
506 }
507
508 bool userrec::BufferIsReady()
509 {
510         return (recvq.find('\n') != std::string::npos);
511 }
512
513 void userrec::ClearBuffer()
514 {
515         recvq = "";
516 }
517
518 std::string userrec::GetBuffer()
519 {
520         if (!recvq.length())
521                 return "";
522
523         /* Strip any leading \r or \n off the string.
524          * Usually there are only one or two of these,
525          * so its is computationally cheap to do.
526          */
527         while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
528                 recvq.erase(recvq.begin());
529
530         for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
531         {
532                 /* Find the first complete line, return it as the
533                  * result, and leave the recvq as whats left
534                  */
535                 if (*x == '\n')
536                 {
537                         std::string ret = std::string(recvq.begin(), x);
538                         recvq.erase(recvq.begin(), x + 1);
539                         return ret;
540                 }
541         }
542         return "";
543 }
544
545 void userrec::AddWriteBuf(const std::string &data)
546 {
547         if (*this->GetWriteError())
548                 return;
549         
550         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
551         {
552                 /*
553                  * Fix by brain - Set the error text BEFORE calling writeopers, because
554                  * if we dont it'll recursively  call here over and over again trying
555                  * to repeatedly add the text to the sendq!
556                  */
557                 this->SetWriteError("SendQ exceeded");
558                 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
559                 return;
560         }
561         
562         if (data.length() > 512)
563         {
564                 std::string newdata(data);
565                 newdata.resize(510);
566                 newdata.append("\r\n");
567                 sendq.append(newdata);
568         }
569         else
570         {
571                 sendq.append(data);
572         }
573 }
574
575 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
576 void userrec::FlushWriteBuf()
577 {
578         if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
579         {
580                 const char* tb = this->sendq.c_str();
581                 int n_sent = write(this->fd,tb,this->sendq.length());
582                 if (n_sent == -1)
583                 {
584                         if (errno != EAGAIN)
585                                 this->SetWriteError(strerror(errno));
586                 }
587                 else
588                 {
589                         // advance the queue
590                         tb += n_sent;
591                         this->sendq = tb;
592                         // update the user's stats counters
593                         this->bytes_out += n_sent;
594                         this->cmds_out++;
595                 }
596         }
597 }
598
599 void userrec::SetWriteError(const std::string &error)
600 {
601         log(DEBUG,"SetWriteError: %s",error.c_str());
602         // don't try to set the error twice, its already set take the first string.
603         if (!this->WriteError.length())
604         {
605                 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
606                 this->WriteError = error;
607         }
608 }
609
610 const char* userrec::GetWriteError()
611 {
612         return this->WriteError.c_str();
613 }
614
615 void userrec::Oper(const std::string &opertype)
616 {
617         this->modes[UM_OPERATOR] = 1;
618         this->WriteServ("MODE %s :+o", this->nick);
619         FOREACH_MOD(I_OnOper, OnOper(this, opertype));
620         log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
621         strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
622         all_opers.push_back(this);
623         FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
624 }
625
626 void userrec::UnOper()
627 {
628         if (*this->oper)
629         {
630                 *this->oper = 0;
631                 this->modes[UM_OPERATOR] = 0;
632                 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
633                 {
634                         if (*a == this)
635                         {
636                                 log(DEBUG,"Oper removed from optimization list");
637                                 all_opers.erase(a);
638                                 return;
639                         }
640                 }
641         }
642 }
643
644 void userrec::QuitUser(userrec *user,const std::string &quitreason)
645 {
646         user_hash::iterator iter = clientlist.find(user->nick);
647
648 /*
649  * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
650  * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
651  *
652  * I can't imagine this blowing up, so I'm commenting it out. We still check
653  * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
654  *
655  *      if (iter == clientlist.end())
656  *              return;
657  */
658         std::string reason = quitreason;
659
660         if (reason.length() > MAXQUIT - 1)
661                 reason.resize(MAXQUIT - 1);
662         
663         if (IS_LOCAL(user))
664                 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
665
666         if (user->registered == REG_ALL)
667         {
668                 purge_empty_chans(user);
669                 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
670                 user->WriteCommonExcept("QUIT :%s",reason.c_str());
671         }
672
673         if (IS_LOCAL(user))
674                 user->FlushWriteBuf();
675
676         FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
677
678         if (IS_LOCAL(user))
679         {
680                 if (ServerInstance->Config->GetIOHook(user->GetPort()))
681                 {
682                         try
683                         {
684                                 ServerInstance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
685                         }
686                         catch (ModuleException& modexcept)
687                         {
688                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
689                         }
690                 }
691                 
692                 ServerInstance->SE->DelFd(user->fd);
693                 user->CloseSocket();
694         }
695
696         /*
697          * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
698          * if they were an oper with +s.
699          *
700          * XXX -
701          * In the current implementation, we only show local quits, as we only show local connects. With 
702          * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
703          */
704         if (user->registered == REG_ALL)
705         {
706                 if (IS_LOCAL(user))
707                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
708                 user->AddToWhoWas();
709         }
710
711         if (iter != clientlist.end())
712         {
713                 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
714                 if (IS_LOCAL(user))
715                 {
716                         ServerInstance->fd_ref_table[user->fd] = NULL;
717                         if (find(local_users.begin(),local_users.end(),user) != local_users.end())
718                                 local_users.erase(find(local_users.begin(),local_users.end(),user));
719                 }
720                 clientlist.erase(iter);
721                 DELETE(user);
722         }
723 }
724
725 namespace irc
726 {
727         namespace whowas
728         {
729
730                 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
731                 {
732                         this->host = strdup(user->host);
733                         this->dhost = strdup(user->dhost);
734                         this->ident = strdup(user->ident);
735                         this->server = user->server;
736                         this->gecos = strdup(user->fullname);
737                 }
738
739                 WhoWasGroup::~WhoWasGroup()
740                 {
741                         if (host)
742                                 free(host);
743                         if (dhost)
744                                 free(dhost);
745                         if (ident)
746                                 free(ident);
747                         if (gecos)
748                                 free(gecos);
749                 }
750
751                 /* every hour, run this function which removes all entries over 3 days */
752                 void MaintainWhoWas(time_t TIME)
753                 {
754                         for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
755                         {
756                                 whowas_set* n = (whowas_set*)iter->second;
757                                 if (n->size())
758                                 {
759                                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
760                                         {
761                                                 WhoWasGroup *a = *(n->begin());
762                                                 DELETE(a);
763                                                 n->erase(n->begin());
764                                         }
765                                 }
766                         }
767                 }
768         };
769 };
770
771 /* adds or updates an entry in the whowas list */
772 void userrec::AddToWhoWas()
773 {
774         irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
775
776         if (iter == whowas.end())
777         {
778                 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
779                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
780                 n->push_back(a);
781                 whowas[this->nick] = n;
782         }
783         else
784         {
785                 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
786
787                 if (group->size() > 10)
788                 {
789                         irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
790                         DELETE(a);
791                         group->pop_front();
792                 }
793
794                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
795                 group->push_back(a);
796         }
797 }
798
799 /* add a client connection to the sockets list */
800 void userrec::AddClient(int socket, int port, bool iscached, insp_inaddr ip)
801 {
802         std::string tempnick = ConvToStr(socket) + "-unknown";
803         user_hash::iterator iter = clientlist.find(tempnick);
804         const char *ipaddr = insp_ntoa(ip);
805         userrec* _new;
806         int j = 0;
807
808         /*
809          * fix by brain.
810          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
811          * using one as a registered connection. As they are per fd, we can also safely assume
812          * that we wont have collisions. Therefore, if the nick exists in the list, its only
813          * used by a dead socket, erase the iterator so that the new client may reclaim it.
814          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
815          * issue in earlier alphas/betas
816          */
817         if (iter != clientlist.end())
818         {
819                 userrec* goner = iter->second;
820                 DELETE(goner);
821                 clientlist.erase(iter);
822         }
823
824         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
825         
826         _new = new userrec();
827         clientlist[tempnick] = _new;
828         _new->fd = socket;
829         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
830
831         _new->server = FindServerNamePtr(ServerInstance->Config->ServerName);
832         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
833         strcpy(_new->ident, "unknown");
834
835         _new->registered = REG_NONE;
836         _new->signon = TIME + ServerInstance->Config->dns_timeout;
837         _new->lastping = 1;
838
839         log(DEBUG,"Setting socket addresses");
840         _new->SetSockAddr(AF_FAMILY, ipaddr, port);
841         log(DEBUG,"Socket addresses set.");
842
843         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
844         for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
845                 _new->dhost[j] = _new->host[j] = *temp;
846         _new->dhost[j] = _new->host[j] = 0;
847                         
848         // set the registration timeout for this user
849         unsigned long class_regtimeout = 90;
850         int class_flood = 0;
851         long class_threshold = 5;
852         long class_sqmax = 262144;      // 256kb
853         long class_rqmax = 4096;        // 4k
854
855         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
856         {
857                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
858                 {
859                         class_regtimeout = (unsigned long)i->registration_timeout;
860                         class_flood = i->flood;
861                         _new->pingmax = i->pingtime;
862                         class_threshold = i->threshold;
863                         class_sqmax = i->sendqmax;
864                         class_rqmax = i->recvqmax;
865                         break;
866                 }
867         }
868
869         _new->nping = TIME + _new->pingmax + ServerInstance->Config->dns_timeout;
870         _new->timeout = TIME+class_regtimeout;
871         _new->flood = class_flood;
872         _new->threshold = class_threshold;
873         _new->sendqmax = class_sqmax;
874         _new->recvqmax = class_rqmax;
875
876         ServerInstance->fd_ref_table[socket] = _new;
877         local_users.push_back(_new);
878
879         if (local_users.size() > ServerInstance->Config->SoftLimit)
880         {
881                 userrec::QuitUser(_new,"No more connections allowed");
882                 return;
883         }
884
885         if (local_users.size() >= MAXCLIENTS)
886         {
887                 userrec::QuitUser(_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(_new,"Server is full");
904                 return;
905         }
906         char* e = matches_exception(ipaddr);
907         if (!e)
908         {
909                 char* r = matches_zline(ipaddr);
910                 if (r)
911                 {
912                         char reason[MAXBUF];
913                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
914                         userrec::QuitUser(_new,reason);
915                         return;
916                 }
917         }
918
919         if (socket > -1)
920         {
921                 if (!ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
922                 {
923                         userrec::QuitUser(_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 = clientlist.begin(); a != 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 = local_users.begin(); a != 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 = TIME;
973
974         ConnectClass a = GetClass(this);
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                 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                 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 = matches_exception(match_against);
1004
1005         if (!e)
1006         {
1007                 char* r = 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 = 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->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->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         ShowMOTD(this);
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         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 = clientlist.find(this->nick);
1076
1077         if (!strcasecmp(this->nick,New))
1078                 return oldnick->second;
1079
1080         if (oldnick == clientlist.end())
1081                 return NULL; /* doesnt exist */
1082
1083         userrec* olduser = oldnick->second;
1084         clientlist[New] = olduser;
1085         clientlist.erase(oldnick);
1086         return 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 (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                         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                         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                         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                         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                         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                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1271                 break;
1272         }
1273         return "";
1274 }
1275
1276
1277 void userrec::Write(const std::string &text)
1278 {
1279         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1280                 return;
1281
1282         std::string crlf = text;
1283         crlf.append("\r\n");
1284
1285         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1286         {
1287                 try
1288                 {
1289                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, crlf.data(), crlf.length());
1290                 }
1291                 catch (ModuleException& modexcept)
1292                 {
1293                         log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1294                 }
1295         }
1296         else
1297         {
1298                 this->AddWriteBuf(crlf);
1299         }
1300         ServerInstance->stats->statsSent += crlf.length();
1301 }
1302
1303 /** Write()
1304  */
1305 void userrec::Write(const char *text, ...)
1306 {
1307         va_list argsPtr;
1308         char textbuffer[MAXBUF];
1309
1310         va_start(argsPtr, text);
1311         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1312         va_end(argsPtr);
1313
1314         this->Write(std::string(textbuffer));
1315 }
1316
1317 void userrec::WriteServ(const std::string& text)
1318 {
1319         char textbuffer[MAXBUF];
1320
1321         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1322         this->Write(std::string(textbuffer));
1323 }
1324
1325 /** WriteServ()
1326  *  Same as Write(), except `text' is prefixed with `:server.name '.
1327  */
1328 void userrec::WriteServ(const char* text, ...)
1329 {
1330         va_list argsPtr;
1331         char textbuffer[MAXBUF];
1332
1333         va_start(argsPtr, text);
1334         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1335         va_end(argsPtr);
1336
1337         this->WriteServ(std::string(textbuffer));
1338 }
1339
1340
1341 void userrec::WriteFrom(userrec *user, const std::string &text)
1342 {
1343         char tb[MAXBUF];
1344
1345         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1346         
1347         this->Write(std::string(tb));
1348 }
1349
1350
1351 /* write text from an originating user to originating user */
1352
1353 void userrec::WriteFrom(userrec *user, const char* text, ...)
1354 {
1355         va_list argsPtr;
1356         char textbuffer[MAXBUF];
1357
1358         va_start(argsPtr, text);
1359         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1360         va_end(argsPtr);
1361
1362         this->WriteFrom(user, std::string(textbuffer));
1363 }
1364
1365
1366 /* write text to an destination user from a source user (e.g. user privmsg) */
1367
1368 void userrec::WriteTo(userrec *dest, const char *data, ...)
1369 {
1370         char textbuffer[MAXBUF];
1371         va_list argsPtr;
1372
1373         va_start(argsPtr, data);
1374         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1375         va_end(argsPtr);
1376
1377         this->WriteTo(dest, std::string(textbuffer));
1378 }
1379
1380 void userrec::WriteTo(userrec *dest, const std::string &data)
1381 {
1382         dest->WriteFrom(this, data);
1383 }
1384
1385
1386 void userrec::WriteCommon(const char* text, ...)
1387 {
1388         char textbuffer[MAXBUF];
1389         va_list argsPtr;
1390
1391         if (this->registered != REG_ALL)
1392                 return;
1393
1394         va_start(argsPtr, text);
1395         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1396         va_end(argsPtr);
1397
1398         this->WriteCommon(std::string(textbuffer));
1399 }
1400
1401 void userrec::WriteCommon(const std::string &text)
1402 {
1403         bool sent_to_at_least_one = false;
1404
1405         if (this->registered != REG_ALL)
1406                 return;
1407
1408         uniq_id++;
1409
1410         for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1411         {
1412                 ucrec *n = *v;
1413                 if (n->channel)
1414                 {
1415                         CUList *ulist= n->channel->GetUsers();
1416
1417                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1418                         {
1419                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1420                                 {
1421                                         already_sent[i->second->fd] = uniq_id;
1422                                         i->second->WriteFrom(this, std::string(text));
1423                                         sent_to_at_least_one = true;
1424                                 }
1425                         }
1426                 }
1427         }
1428
1429         /*
1430          * if the user was not in any channels, no users will receive the text. Make sure the user
1431          * receives their OWN message for WriteCommon
1432          */
1433         if (!sent_to_at_least_one)
1434         {
1435                 this->WriteFrom(this,std::string(text));
1436         }
1437 }
1438
1439
1440 /* write a formatted string to all users who share at least one common
1441  * channel, NOT including the source user e.g. for use in QUIT
1442  */
1443
1444 void userrec::WriteCommonExcept(const char* text, ...)
1445 {
1446         char textbuffer[MAXBUF];
1447         va_list argsPtr;
1448
1449         va_start(argsPtr, text);
1450         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1451         va_end(argsPtr);
1452
1453         this->WriteCommonExcept(std::string(textbuffer));
1454 }
1455
1456 void userrec::WriteCommonExcept(const std::string &text)
1457 {
1458         bool quit_munge = true;
1459         char oper_quit[MAXBUF];
1460         char textbuffer[MAXBUF];
1461
1462         strlcpy(textbuffer, text.c_str(), MAXBUF);
1463
1464         if (this->registered != REG_ALL)
1465                 return;
1466
1467         uniq_id++;
1468
1469         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1470          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1471          * can go byebye.
1472          */
1473         if (ServerInstance->Config->HideSplits)
1474         {
1475                 char* check = textbuffer + 6;
1476
1477                 if (!strncasecmp(textbuffer, "QUIT :",6))
1478                 {
1479                         std::stringstream split(check);
1480                         std::string server_one;
1481                         std::string server_two;
1482
1483                         split >> server_one;
1484                         split >> server_two;
1485
1486                         if ((FindServerName(server_one)) && (FindServerName(server_two)))
1487                         {
1488                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1489                                 strlcpy(check,"*.net *.split",MAXQUIT);
1490                                 quit_munge = true;
1491                         }
1492                 }
1493         }
1494
1495         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1496         {
1497                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1498                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1499                 {
1500                         char* check = textbuffer + 13;
1501                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1502                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1503                         quit_munge = true;
1504                 }
1505         }
1506
1507         for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1508         {
1509                 ucrec* n = *v;
1510                 if (n->channel)
1511                 {
1512                         CUList *ulist= n->channel->GetUsers();
1513
1514                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1515                         {
1516                                 if (this != i->second)
1517                                 {
1518                                         if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1519                                         {
1520                                                 already_sent[i->second->fd] = uniq_id;
1521                                                 if (quit_munge)
1522                                                         i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1523                                                 else
1524                                                         i->second->WriteFrom(this, std::string(textbuffer));
1525                                         }
1526                                 }
1527                         }
1528                 }
1529         }
1530
1531 }
1532
1533 void userrec::WriteWallOps(const std::string &text)
1534 {
1535         /* Does nothing if theyre not opered */
1536         if ((!*this->oper) && (IS_LOCAL(this)))
1537                 return;
1538
1539         std::string wallop = "WALLOPS :";
1540         wallop.append(text);
1541
1542         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1543         {
1544                 userrec* t = *i;
1545                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1546                         this->WriteTo(t,wallop);
1547         }
1548 }
1549
1550 void userrec::WriteWallOps(const char* text, ...)
1551 {       
1552         char textbuffer[MAXBUF];
1553         va_list argsPtr;
1554
1555         va_start(argsPtr, text);
1556         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1557         va_end(argsPtr);                
1558                                         
1559         this->WriteWallOps(std::string(textbuffer));
1560 }                                      
1561
1562 /* return 0 or 1 depending if users u and u2 share one or more common channels
1563  * (used by QUIT, NICK etc which arent channel specific notices)
1564  *
1565  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1566  * the first users channels then the second users channels within the outer loop,
1567  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1568  * all possible iterations). However this new function instead checks against the
1569  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1570  * and saves us time as we already know what pointer value we are after.
1571  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1572  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1573  */
1574 bool userrec::SharesChannelWith(userrec *other)
1575 {
1576         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1577                 return false;
1578
1579         /* Outer loop */
1580         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1581         {
1582                 /* Fetch the channel from the user */
1583                 ucrec* user_channel = *i;
1584
1585                 if (user_channel->channel)
1586                 {
1587                         /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1588                          * by replacing it with a map::find which *should* be more efficient
1589                          */
1590                         if (user_channel->channel->HasUser(other))
1591                                 return true;
1592                 }
1593         }
1594         return false;
1595 }
1596
1597 int userrec::CountChannels()
1598 {
1599         int z = 0;
1600         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1601                 if ((*i)->channel)
1602                         z++;
1603         return z;
1604 }
1605
1606 bool userrec::ChangeName(const char* gecos)
1607 {
1608         if (IS_LOCAL(this))
1609         {
1610                 int MOD_RESULT = 0;
1611                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1612                 if (MOD_RESULT)
1613                         return false;
1614                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1615         }
1616         strlcpy(this->fullname,gecos,MAXGECOS+1);
1617         return true;
1618 }
1619
1620 bool userrec::ChangeDisplayedHost(const char* host)
1621 {
1622         if (IS_LOCAL(this))
1623         {
1624                 int MOD_RESULT = 0;
1625                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1626                 if (MOD_RESULT)
1627                         return false;
1628                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1629         }
1630         strlcpy(this->dhost,host,63);
1631
1632         if (IS_LOCAL(this))
1633                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1634
1635         return true;
1636 }
1637