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