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