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