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