]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
d923cdb2633ccb73581cdb95de0f7f5a718eff23
[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                 /* ServerInstance->Log(DEBUG,"<- %s", text.c_str());
1337                  * WARNING: The above debug line is VERY loud, do NOT
1338                  * enable it till we have a good way of filtering it
1339                  * out of the logs (e.g. 1.2 would be good).
1340                  */
1341                 text.append("\r\n");
1342         }
1343         catch (...)
1344         {
1345                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1346                 return;
1347         }
1348
1349         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1350         {
1351                 try
1352                 {
1353                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1354                 }
1355                 catch (CoreException& modexcept)
1356                 {
1357                         ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1358                 }
1359         }
1360         else
1361         {
1362                 this->AddWriteBuf(text);
1363         }
1364         ServerInstance->stats->statsSent += text.length();
1365         this->ServerInstance->SE->WantWrite(this);
1366 }
1367
1368 /** Write()
1369  */
1370 void userrec::Write(const char *text, ...)
1371 {
1372         va_list argsPtr;
1373         char textbuffer[MAXBUF];
1374
1375         va_start(argsPtr, text);
1376         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1377         va_end(argsPtr);
1378
1379         this->Write(std::string(textbuffer));
1380 }
1381
1382 void userrec::WriteServ(const std::string& text)
1383 {
1384         char textbuffer[MAXBUF];
1385
1386         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1387         this->Write(std::string(textbuffer));
1388 }
1389
1390 /** WriteServ()
1391  *  Same as Write(), except `text' is prefixed with `:server.name '.
1392  */
1393 void userrec::WriteServ(const char* text, ...)
1394 {
1395         va_list argsPtr;
1396         char textbuffer[MAXBUF];
1397
1398         va_start(argsPtr, text);
1399         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1400         va_end(argsPtr);
1401
1402         this->WriteServ(std::string(textbuffer));
1403 }
1404
1405
1406 void userrec::WriteFrom(userrec *user, const std::string &text)
1407 {
1408         char tb[MAXBUF];
1409
1410         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1411         
1412         this->Write(std::string(tb));
1413 }
1414
1415
1416 /* write text from an originating user to originating user */
1417
1418 void userrec::WriteFrom(userrec *user, const char* text, ...)
1419 {
1420         va_list argsPtr;
1421         char textbuffer[MAXBUF];
1422
1423         va_start(argsPtr, text);
1424         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1425         va_end(argsPtr);
1426
1427         this->WriteFrom(user, std::string(textbuffer));
1428 }
1429
1430
1431 /* write text to an destination user from a source user (e.g. user privmsg) */
1432
1433 void userrec::WriteTo(userrec *dest, const char *data, ...)
1434 {
1435         char textbuffer[MAXBUF];
1436         va_list argsPtr;
1437
1438         va_start(argsPtr, data);
1439         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1440         va_end(argsPtr);
1441
1442         this->WriteTo(dest, std::string(textbuffer));
1443 }
1444
1445 void userrec::WriteTo(userrec *dest, const std::string &data)
1446 {
1447         dest->WriteFrom(this, data);
1448 }
1449
1450
1451 void userrec::WriteCommon(const char* text, ...)
1452 {
1453         char textbuffer[MAXBUF];
1454         va_list argsPtr;
1455
1456         if (this->registered != REG_ALL)
1457                 return;
1458
1459         va_start(argsPtr, text);
1460         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1461         va_end(argsPtr);
1462
1463         this->WriteCommon(std::string(textbuffer));
1464 }
1465
1466 void userrec::WriteCommon(const std::string &text)
1467 {
1468         try
1469         {
1470                 bool sent_to_at_least_one = false;
1471                 char tb[MAXBUF];
1472         
1473                 if (this->registered != REG_ALL)
1474                         return;
1475         
1476                 uniq_id++;
1477
1478                 /* We dont want to be doing this n times, just once */
1479                 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1480                 std::string out = tb;
1481         
1482                 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1483                 {
1484                         CUList* ulist = v->first->GetUsers();
1485                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1486                         {
1487                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1488                                 {
1489                                         already_sent[i->second->fd] = uniq_id;
1490                                         i->second->Write(out);
1491                                         sent_to_at_least_one = true;
1492                                 }
1493                         }
1494                 }
1495         
1496                 /*
1497                  * if the user was not in any channels, no users will receive the text. Make sure the user
1498                  * receives their OWN message for WriteCommon
1499                  */
1500                 if (!sent_to_at_least_one)
1501                 {
1502                         this->Write(std::string(tb));
1503                 }
1504         }
1505
1506         catch (...)
1507         {
1508                 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1509         }
1510 }
1511
1512
1513 /* write a formatted string to all users who share at least one common
1514  * channel, NOT including the source user e.g. for use in QUIT
1515  */
1516
1517 void userrec::WriteCommonExcept(const char* text, ...)
1518 {
1519         char textbuffer[MAXBUF];
1520         va_list argsPtr;
1521
1522         va_start(argsPtr, text);
1523         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1524         va_end(argsPtr);
1525
1526         this->WriteCommonExcept(std::string(textbuffer));
1527 }
1528
1529 void userrec::WriteCommonExcept(const std::string &text)
1530 {
1531         bool quit_munge = false;
1532         char oper_quit[MAXBUF];
1533         char textbuffer[MAXBUF];
1534         char tb1[MAXBUF];
1535         char tb2[MAXBUF];
1536         std::string out1;
1537         std::string out2;
1538
1539         strlcpy(textbuffer, text.c_str(), MAXBUF);
1540
1541         if (this->registered != REG_ALL)
1542                 return;
1543
1544         uniq_id++;
1545
1546         snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),textbuffer);
1547
1548         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1549          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1550          * can go byebye.
1551          */
1552         if (ServerInstance->Config->HideSplits)
1553         {
1554                 char* check = textbuffer + 6;
1555
1556                 if (!strncasecmp(textbuffer, "QUIT :",6))
1557                 {
1558                         std::stringstream split(check);
1559                         std::string server_one;
1560                         std::string server_two;
1561
1562                         split >> server_one;
1563                         split >> server_two;
1564
1565                         if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1566                         {
1567                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1568                                 strlcpy(check,"*.net *.split",MAXQUIT);
1569                                 quit_munge = true;
1570                                 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1571                                 out2 = tb2;
1572                         }
1573                 }
1574         }
1575
1576         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1577         {
1578                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1579                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1580                 {
1581                         char* check = textbuffer + 13;
1582                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1583                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1584                         quit_munge = true;
1585                         snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1586                         out2 = tb2;
1587                 }
1588         }
1589
1590         out1 = tb1;
1591
1592         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1593         {
1594                 CUList *ulist = v->first->GetUsers();
1595                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1596                 {
1597                         if (this != i->second)
1598                         {
1599                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1600                                 {
1601                                         already_sent[i->second->fd] = uniq_id;
1602                                         if (quit_munge)
1603                                                 i->second->Write(*i->second->oper ? out2 : out1);
1604                                         else
1605                                                 i->second->Write(out1);
1606                                 }
1607                         }
1608                 }
1609         }
1610
1611 }
1612
1613 void userrec::WriteWallOps(const std::string &text)
1614 {
1615         /* Does nothing if theyre not opered */
1616         if ((!*this->oper) && (IS_LOCAL(this)))
1617                 return;
1618
1619         std::string wallop = "WALLOPS :";
1620
1621         try
1622         {
1623                 wallop.append(text);
1624         }
1625         catch (...)
1626         {
1627                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1628                 return;
1629         }
1630
1631         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1632         {
1633                 userrec* t = *i;
1634                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1635                         this->WriteTo(t,wallop);
1636         }
1637 }
1638
1639 void userrec::WriteWallOps(const char* text, ...)
1640 {       
1641         char textbuffer[MAXBUF];
1642         va_list argsPtr;
1643
1644         va_start(argsPtr, text);
1645         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1646         va_end(argsPtr);                
1647                                         
1648         this->WriteWallOps(std::string(textbuffer));
1649 }                                      
1650
1651 /* return 0 or 1 depending if users u and u2 share one or more common channels
1652  * (used by QUIT, NICK etc which arent channel specific notices)
1653  *
1654  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1655  * the first users channels then the second users channels within the outer loop,
1656  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1657  * all possible iterations). However this new function instead checks against the
1658  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1659  * and saves us time as we already know what pointer value we are after.
1660  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1661  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1662  */
1663 bool userrec::SharesChannelWith(userrec *other)
1664 {
1665         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1666                 return false;
1667
1668         /* Outer loop */
1669         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1670         {
1671                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1672                  * by replacing it with a map::find which *should* be more efficient
1673                  */
1674                 if (i->first->HasUser(other))
1675                         return true;
1676         }
1677         return false;
1678 }
1679
1680 bool userrec::ChangeName(const char* gecos)
1681 {
1682         if (!strcmp(gecos, this->fullname))
1683                 return true;
1684
1685         if (IS_LOCAL(this))
1686         {
1687                 int MOD_RESULT = 0;
1688                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1689                 if (MOD_RESULT)
1690                         return false;
1691                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1692         }
1693         strlcpy(this->fullname,gecos,MAXGECOS+1);
1694
1695         return true;
1696 }
1697
1698 bool userrec::ChangeDisplayedHost(const char* host)
1699 {
1700         if (!strcmp(host, this->dhost))
1701                 return true;
1702
1703         if (IS_LOCAL(this))
1704         {
1705                 int MOD_RESULT = 0;
1706                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1707                 if (MOD_RESULT)
1708                         return false;
1709                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1710         }
1711         if (this->ServerInstance->Config->CycleHosts)
1712                 this->WriteCommonExcept("QUIT :Changing hosts");
1713
1714         /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1715         strlcpy(this->dhost,host,64);
1716
1717         this->InvalidateCache();
1718
1719         if (this->ServerInstance->Config->CycleHosts)
1720         {
1721                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1722                 {
1723                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1724                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1725                         if (n.length() > 0)
1726                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1727                 }
1728         }
1729
1730         if (IS_LOCAL(this))
1731                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1732
1733         return true;
1734 }
1735
1736 bool userrec::ChangeIdent(const char* newident)
1737 {
1738         if (!strcmp(newident, this->ident))
1739                 return true;
1740
1741         if (this->ServerInstance->Config->CycleHosts)
1742                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1743
1744         strlcpy(this->ident, newident, IDENTMAX+2);
1745
1746         this->InvalidateCache();
1747
1748         if (this->ServerInstance->Config->CycleHosts)
1749         {
1750                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1751                 {
1752                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1753                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1754                         if (n.length() > 0)
1755                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1756                 }
1757         }
1758
1759         return true;
1760 }
1761
1762 void userrec::NoticeAll(char* text, ...)
1763 {
1764         char textbuffer[MAXBUF];
1765         char formatbuffer[MAXBUF];
1766         va_list argsPtr;
1767
1768         va_start(argsPtr, text);
1769         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1770         va_end(argsPtr);
1771
1772         snprintf(formatbuffer,MAXBUF,":%s NOTICE $* :%s", this->GetFullHost(), textbuffer);
1773         std::string fmt = formatbuffer;
1774
1775         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1776         {
1777                 (*i)->Write(fmt);
1778         }
1779 }
1780
1781
1782 std::string userrec::ChannelList(userrec* source)
1783 {
1784         try
1785         {
1786                 std::string list;
1787                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1788                 {
1789                         /* If the target is the same as the sender, let them see all their channels.
1790                          * If the channel is NOT private/secret OR the user shares a common channel
1791                          * If the user is an oper, and the <options:operspywhois> option is set.
1792                          */
1793                         if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1794                         {
1795                                 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1796                         }
1797                 }
1798                 return list;
1799         }
1800         catch (...)
1801         {
1802                 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1803                 return "";
1804         }
1805 }
1806
1807 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1808 {
1809         std::string line;
1810         std::ostringstream prefix;
1811         std::string::size_type start, pos, length;
1812
1813         try
1814         {
1815                 prefix << this->nick << " " << dest->nick << " :";
1816                 line = prefix.str();
1817                 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1818         
1819                 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1820                 {
1821                         length = (pos == std::string::npos) ? cl.length() : pos;
1822         
1823                         if (line.length() + namelen + length - start > 510)
1824                         {
1825                                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1826                                 line = prefix.str();
1827                         }
1828         
1829                         if(pos == std::string::npos)
1830                         {
1831                                 line.append(cl.substr(start, length - start));
1832                                 break;
1833                         }
1834                         else
1835                         {
1836                                 line.append(cl.substr(start, length - start + 1));
1837                         }
1838                 }
1839         
1840                 if (line.length())
1841                 {
1842                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1843                 }
1844         }
1845
1846         catch (...)
1847         {
1848                 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1849         }
1850 }
1851
1852
1853 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1854  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1855  * then their ip will be taken as 'priority' anyway, so for example,
1856  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1857  */
1858 ConnectClass* userrec::GetClass()
1859 {
1860         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1861         {
1862                 if ((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str())))
1863                         return &(*i);
1864         }
1865         return NULL;
1866 }
1867
1868 void userrec::PurgeEmptyChannels()
1869 {
1870         std::vector<chanrec*> to_delete;
1871
1872         // firstly decrement the count on each channel
1873         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1874         {
1875                 f->first->RemoveAllPrefixes(this);
1876                 if (f->first->DelUser(this) == 0)
1877                 {
1878                         /* No users left in here, mark it for deletion */
1879                         try
1880                         {
1881                                 to_delete.push_back(f->first);
1882                         }
1883                         catch (...)
1884                         {
1885                                 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1886                         }
1887                 }
1888         }
1889
1890         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1891         {
1892                 chanrec* thischan = *n;
1893                 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1894                 if (i2 != ServerInstance->chanlist->end())
1895                 {
1896                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1897                         DELETE(i2->second);
1898                         ServerInstance->chanlist->erase(i2);
1899                         this->chans.erase(*n);
1900                 }
1901         }
1902
1903         this->UnOper();
1904 }
1905
1906 void userrec::ShowMOTD()
1907 {
1908         if (!ServerInstance->Config->MOTD.size())
1909         {
1910                 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1911                 return;
1912         }
1913         this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1914
1915         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1916                 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1917
1918         this->WriteServ("376 %s :End of message of the day.", this->nick);
1919 }
1920
1921 void userrec::ShowRULES()
1922 {
1923         if (!ServerInstance->Config->RULES.size())
1924         {
1925                 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1926                 return;
1927         }
1928         this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1929
1930         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1931                 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
1932
1933         this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1934 }
1935
1936 void userrec::HandleEvent(EventType et, int errornum)
1937 {
1938         /* WARNING: May delete this user! */
1939         int thisfd = this->GetFd();
1940
1941         try
1942         {
1943                 switch (et)
1944                 {
1945                         case EVENT_READ:
1946                                 ServerInstance->ProcessUser(this);
1947                         break;
1948                         case EVENT_WRITE:
1949                                 this->FlushWriteBuf();
1950                         break;
1951                         case EVENT_ERROR:
1952                                 /** This should be safe, but dont DARE do anything after it -- Brain */
1953                                 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1954                         break;
1955                 }
1956         }
1957         catch (...)
1958         {
1959                 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
1960         }
1961
1962         /* If the user has raised an error whilst being processed, quit them now we're safe to */
1963         if ((ServerInstance->SE->GetRef(thisfd) == this))
1964         {
1965                 if (!WriteError.empty())
1966                 {
1967                         userrec::QuitUser(ServerInstance, this, GetWriteError());
1968                 }
1969         }
1970 }
1971