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