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