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