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