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