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