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