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