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