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