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