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