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