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