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