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