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