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