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