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