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