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