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