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