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