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