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