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