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