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