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