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