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