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