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