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