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