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