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