1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
18 #include "socketengine.h"
21 #include "commands/cmd_whowas.h"
23 static unsigned long uniq_id = 1;
25 static unsigned long* already_sent = NULL;
27 void InitializeAlreadySent(SocketEngine* SE)
29 already_sent = new unsigned long[SE->GetMaxFds()];
30 memset(already_sent, 0, SE->GetMaxFds() * sizeof(unsigned long));
33 std::string User::ProcessNoticeMasks(const char *sm)
35 bool adding = true, oldadding = false;
50 for (unsigned char d = 'A'; d <= 'z'; d++)
52 if (ServerInstance->SNO->IsEnabled(d))
54 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
56 if ((oldadding != adding) || (!output.length()))
57 output += (adding ? '+' : '-');
59 this->SetNoticeMask(d, adding);
68 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
70 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
72 if ((oldadding != adding) || (!output.length()))
73 output += (adding ? '+' : '-');
75 this->SetNoticeMask(*c, adding);
81 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
90 std::string s = this->FormatNoticeMasks();
93 this->modes[UM_SNOMASK] = false;
99 void User::StartDNSLookup()
104 const char* sip = this->GetIPString();
105 UserResolver *res_reverse;
107 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
108 res_reverse = new UserResolver(this, sip, resolvtype, cached);
110 ServerInstance->AddResolver(res_reverse, cached);
112 catch (CoreException& e)
114 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
118 bool User::IsNoticeMaskSet(unsigned char sm)
122 return (snomasks[sm-65]);
125 void User::SetNoticeMask(unsigned char sm, bool value)
129 snomasks[sm-65] = value;
132 const char* User::FormatNoticeMasks()
134 static char data[MAXBUF];
137 for (int n = 0; n < 64; n++)
140 data[offset++] = n+65;
147 bool User::IsModeSet(unsigned char m)
151 return (modes[m-65]);
154 void User::SetMode(unsigned char m, bool value)
161 const char* User::FormatModes(bool showparameters)
163 static char data[MAXBUF];
167 for (unsigned char n = 0; n < 64; n++)
171 data[offset++] = n + 65;
172 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
173 if (showparameters && mh && mh->GetNumParams(true))
175 std::string p = mh->GetUserParameter(this);
177 params.append(" ").append(p);
182 strlcat(data, params.c_str(), MAXBUF);
186 void User::DecrementModes()
188 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
189 for (unsigned char n = 'A'; n <= 'z'; n++)
193 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
194 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
197 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
204 User::User(const std::string &uid)
206 server = ServerInstance->Config->ServerName;
207 age = ServerInstance->Time();
209 lastping = signon = idle_lastmsg = nping = registered = 0;
210 bytes_in = bytes_out = cmds_in = cmds_out = 0;
211 quietquit = quitting = exempt = haspassed = dns_done = false;
213 server_sa.sa.sa_family = AF_UNSPEC;
214 client_sa.sa.sa_family = AF_UNSPEC;
216 AllowedPrivs = AllowedOperCommands = NULL;
219 uuid.assign(ServerInstance->GetUID(), 0, UUID_LENGTH - 1);
221 uuid.assign(uid, 0, UUID_LENGTH - 1);
223 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid.c_str(), uid.empty() ? "allocated new" : "used remote");
225 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
226 if (finduuid == ServerInstance->Users->uuidlist->end())
227 (*ServerInstance->Users->uuidlist)[uuid] = this;
229 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
235 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
238 const std::string& User::MakeHost()
240 if (!this->cached_makehost.empty())
241 return this->cached_makehost;
244 /* This is much faster than snprintf */
246 for(const char* n = ident.c_str(); *n; n++)
249 for(const char* n = host.c_str(); *n; n++)
253 this->cached_makehost.assign(nhost);
255 return this->cached_makehost;
258 const std::string& User::MakeHostIP()
260 if (!this->cached_hostip.empty())
261 return this->cached_hostip;
264 /* This is much faster than snprintf */
266 for(const char* n = ident.c_str(); *n; n++)
269 for(const char* n = this->GetIPString(); *n; n++)
273 this->cached_hostip = ihost;
275 return this->cached_hostip;
278 const std::string User::GetFullHost()
280 if (!this->cached_fullhost.empty())
281 return this->cached_fullhost;
285 for(const char* n = nick.c_str(); *n; n++)
288 for(const char* n = ident.c_str(); *n; n++)
291 for(const char* n = dhost.c_str(); *n; n++)
295 this->cached_fullhost = result;
297 return this->cached_fullhost;
300 char* User::MakeWildHost()
302 static char nresult[MAXBUF];
304 *t++ = '*'; *t++ = '!';
305 *t++ = '*'; *t++ = '@';
306 for(const char* n = dhost.c_str(); *n; n++)
312 const std::string User::GetFullRealHost()
314 if (!this->cached_fullrealhost.empty())
315 return this->cached_fullrealhost;
317 char fresult[MAXBUF];
319 for(const char* n = nick.c_str(); *n; n++)
322 for(const char* n = ident.c_str(); *n; n++)
325 for(const char* n = host.c_str(); *n; n++)
329 this->cached_fullrealhost = fresult;
331 return this->cached_fullrealhost;
334 bool User::IsInvited(const irc::string &channel)
336 time_t now = ServerInstance->Time();
337 InvitedList::iterator safei;
338 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
340 if (channel == i->first)
342 if (i->second != 0 && now > i->second)
344 /* Expired invite, remove it. */
347 invites.erase(safei);
356 InvitedList* User::GetInviteList()
358 time_t now = ServerInstance->Time();
359 /* Weed out expired invites here. */
360 InvitedList::iterator safei;
361 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
363 if (i->second != 0 && now > i->second)
365 /* Expired invite, remove it. */
368 invites.erase(safei);
374 void User::InviteTo(const irc::string &channel, time_t invtimeout)
376 time_t now = ServerInstance->Time();
377 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
378 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
380 if (channel == i->first)
382 if (i->second != 0 && invtimeout > i->second)
384 i->second = invtimeout;
390 invites.push_back(std::make_pair(channel, invtimeout));
393 void User::RemoveInvite(const irc::string &channel)
395 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
397 if (channel == i->first)
405 bool User::HasModePermission(unsigned char mode, ModeType type)
413 if (mode < 'A' || mode > ('A' + 64)) return false;
415 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
419 bool User::HasPermission(const std::string &command)
422 * users on remote servers can completely bypass all permissions based checks.
423 * This prevents desyncs when one server has different type/class tags to another.
424 * That having been said, this does open things up to the possibility of source changes
425 * allowing remote kills, etc - but if they have access to the src, they most likely have
426 * access to the conf - so it's an end to a means either way.
431 // are they even an oper at all?
437 if (!AllowedOperCommands)
440 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
442 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
449 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
453 ServerInstance->Logs->Log("PRIVS", DEBUG, "Remote (yes)");
460 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
467 this->WriteServ("NOTICE %s :Privset empty(!?)", this->nick.c_str());
471 if (AllowedPrivs->find(privstr) != AllowedPrivs->end())
475 else if (AllowedPrivs->find("*") != AllowedPrivs->end())
481 this->WriteServ("NOTICE %s :Oper type %s does not have access to priv %s", this->nick.c_str(), this->oper.c_str(), privstr.c_str());
485 void User::OnDataReady()
490 if (MyClass && recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
492 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
493 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
494 nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
496 unsigned long sendqmax = ULONG_MAX;
497 if (MyClass && !HasPrivPermission("users/flood/increased-buffers"))
498 sendqmax = MyClass->GetSendqSoftMax();
500 while (Penalty < 10 && getSendQSize() < sendqmax)
503 line.reserve(MAXBUF);
504 std::string::size_type qpos = 0;
505 while (qpos < recvq.length())
507 char c = recvq[qpos++];
518 if (line.length() < MAXBUF - 2)
521 // if we got here, the recvq ran out before we found a newline
524 // just found a newline. Terminate the string, and pull it out of recvq
525 recvq = recvq.substr(qpos);
527 // TODO should this be moved to when it was inserted in recvq?
528 ServerInstance->stats->statsRecv += qpos;
529 this->bytes_in += qpos;
532 ServerInstance->Parser->ProcessBuffer(line, this);
534 // Add pseudo-penalty so that we continue processing after sendq recedes
535 if (Penalty == 0 && getSendQSize() >= sendqmax)
539 void User::AddWriteBuf(const std::string &data)
541 // Don't bother sending text to remote users!
544 if (!quitting && MyClass && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
547 * Quit the user FIRST, because otherwise we could recurse
548 * here and hit the same limit.
550 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
551 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
552 nick.c_str(), MyClass->GetSendqHardMax());
556 // We still want to append data to the sendq of a quitting user,
557 // e.g. their ERROR message that says 'closing link'
562 void User::OnError(BufferedSocketError)
564 ServerInstance->Users->QuitUser(this, getError());
570 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
573 ServerInstance->Logs->Log("USERS", DEBUG, "User culled twice? UUID empty");
576 PurgeEmptyChannels();
582 std::vector<User*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
583 if (x != ServerInstance->Users->local_users.end())
584 ServerInstance->Users->local_users.erase(x);
586 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
589 if (this->AllowedOperCommands)
591 delete AllowedOperCommands;
592 AllowedOperCommands = NULL;
595 if (this->AllowedPrivs)
601 this->InvalidateCache();
602 this->DecrementModes();
604 if (client_sa.sa.sa_family != AF_UNSPEC)
605 ServerInstance->Users->RemoveCloneCounts(this);
607 ServerInstance->Users->uuidlist->erase(uuid);
612 void User::Oper(const std::string &opertype, const std::string &opername)
614 if (this->IsModeSet('o'))
617 this->modes[UM_OPERATOR] = 1;
618 this->WriteServ("MODE %s :+o", this->nick.c_str());
619 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
621 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());
622 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()));
624 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());
625 this->oper.assign(opertype, 0, 512);
626 ServerInstance->Users->all_opers.push_back(this);
629 * This might look like it's in the wrong place.
632 * 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.
635 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
636 if (iter_opertype != ServerInstance->Config->opertypes.end())
638 if (AllowedOperCommands)
639 AllowedOperCommands->clear();
641 AllowedOperCommands = new std::set<std::string>;
644 AllowedPrivs->clear();
646 AllowedPrivs = new std::set<std::string>;
648 AllowedUserModes.reset();
649 AllowedChanModes.reset();
650 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
652 std::string myclass, mycmd, mypriv;
653 irc::spacesepstream Classes(iter_opertype->second.c_str());
654 while (Classes.GetToken(myclass))
656 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass.c_str());
657 if (iter_operclass != ServerInstance->Config->operclass.end())
659 /* Process commands */
660 irc::spacesepstream CommandList(iter_operclass->second.commandlist);
661 while (CommandList.GetToken(mycmd))
663 this->AllowedOperCommands->insert(mycmd);
666 irc::spacesepstream PrivList(iter_operclass->second.privs);
667 while (PrivList.GetToken(mypriv))
669 this->AllowedPrivs->insert(mypriv);
672 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist.c_str(); *c; ++c)
676 this->AllowedUserModes.set();
680 this->AllowedUserModes[*c - 'A'] = true;
684 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist.c_str(); *c; ++c)
688 this->AllowedChanModes.set();
692 this->AllowedChanModes[*c - 'A'] = true;
699 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
707 * unset their oper type (what IS_OPER checks).
708 * note, order is important - this must come before modes as -o attempts
709 * to call UnOper. -- w00t
714 /* Remove all oper only modes from the user when the deoper - Bug #466*/
715 std::string moderemove("-");
717 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
719 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
720 if (mh && mh->NeedsOper())
721 moderemove += letter;
725 std::vector<std::string> parameters;
726 parameters.push_back(this->nick);
727 parameters.push_back(moderemove);
729 ServerInstance->Parser->CallHandler("MODE", parameters, this);
731 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
732 ServerInstance->Users->all_opers.remove(this);
734 if (AllowedOperCommands)
736 delete AllowedOperCommands;
737 AllowedOperCommands = NULL;
746 AllowedUserModes.reset();
747 AllowedChanModes.reset();
748 this->modes[UM_OPERATOR] = 0;
752 /* adds or updates an entry in the whowas list */
753 void User::AddToWhoWas()
755 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
758 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
765 * Check class restrictions
767 void User::CheckClass()
769 ConnectClass* a = this->MyClass;
771 if ((!a) || (a->type == CC_DENY))
773 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
776 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
778 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
779 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
782 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
784 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
785 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
789 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
792 bool User::CheckLines(bool doZline)
794 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
798 for (int n = 0; check[n]; ++n)
800 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
813 void User::FullConnect()
815 ServerInstance->stats->statsConnects++;
816 this->idle_lastmsg = ServerInstance->Time();
819 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
820 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
821 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
822 * Don't remove this! -- w00t
826 /* Check the password, if one is required by the user's connect class.
827 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
829 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
831 ServerInstance->Users->QuitUser(this, "Invalid password");
835 if (this->CheckLines())
838 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
839 this->WriteNumeric(RPL_WELCOME, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick.c_str(), ServerInstance->Config->Network.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str());
840 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
841 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
842 this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-2.0 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
844 ServerInstance->Config->Send005(this);
845 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
851 if (ServerInstance->Users->unregistered_count)
852 ServerInstance->Users->unregistered_count--;
854 /* Trigger LUSERS output, give modules a chance too */
855 ModResult MOD_RESULT;
856 std::string command("LUSERS");
857 std::vector<std::string> parameters;
858 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
860 ServerInstance->CallCommandHandler(command, parameters, this);
863 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
864 * for a user that doesn't exist yet.
866 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
868 this->registered = REG_ALL;
870 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
872 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
873 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
874 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
875 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
878 /** User::UpdateNick()
879 * re-allocates a nick in the user_hash after they change nicknames,
880 * returns a pointer to the new user as it may have moved
882 User* User::UpdateNickHash(const char* New)
884 //user_hash::iterator newnick;
885 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
887 if (!irc::string(this->nick.c_str()).compare(New))
888 return oldnick->second;
890 if (oldnick == ServerInstance->Users->clientlist->end())
891 return NULL; /* doesnt exist */
893 User* olduser = oldnick->second;
894 ServerInstance->Users->clientlist->erase(oldnick);
895 (*(ServerInstance->Users->clientlist))[New] = olduser;
899 void User::InvalidateCache()
901 /* Invalidate cache */
902 cached_fullhost.clear();
903 cached_hostip.clear();
904 cached_makehost.clear();
905 cached_fullrealhost.clear();
908 bool User::ForceNickChange(const char* newnick)
910 ModResult MOD_RESULT;
912 this->InvalidateCache();
914 ServerInstance->NICKForced.set(this, 1);
915 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
916 ServerInstance->NICKForced.set(this, 0);
918 if (MOD_RESULT == MOD_RES_DENY)
920 ServerInstance->stats->statsCollisions++;
924 std::deque<classbase*> dummy;
925 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
926 if (nickhandler) // wtfbbq, when would this not be here
928 std::vector<std::string> parameters;
929 parameters.push_back(newnick);
930 ServerInstance->NICKForced.set(this, 1);
931 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
932 ServerInstance->NICKForced.set(this, 0);
936 // Unreachable, we hope
940 int User::GetServerPort()
942 switch (this->server_sa.sa.sa_family)
945 return htons(this->server_sa.in6.sin6_port);
947 return htons(this->server_sa.in4.sin_port);
952 const char* User::GetCIDRMask(int range)
957 throw "Negative range, sorry, no.";
960 * Original code written by Oliver Lupton (Om).
961 * Integrated by me. Thanks. :) -- w00t
963 switch (this->client_sa.sa.sa_family)
967 /* unsigned char s6_addr[16]; */
969 int i, bytestozero, extrabits;
973 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
975 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
976 * to zero. This means the last (128 - range) bits of the address must be set to zero.
977 * Hence this number divided by 8 is the number of whole bytes from the end of the address
978 * which must be set to zero.
980 bytestozero = (128 - range) / 8;
982 /* Some of the least significant bits of the next most significant byte may also have to
983 * be zeroed. The number of bits is the remainder of the above division.
985 extrabits = (128 - range) % 8;
987 /* Populate our working struct with the parts of the user's IP which are required in the
988 * final CIDR mask. Set all the subsequent bytes to zero.
989 * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
991 for(i = 0; i < (16 - bytestozero); i++)
993 v6.s6_addr[i] = client_sa.in6.sin6_addr.s6_addr[i];
996 /* And zero all the remaining bytes in the IP. */
1002 /* And finally, zero the extra bits required. */
1003 v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1005 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1015 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1017 /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1018 v4.s_addr = client_sa.in4.sin_addr.s_addr;
1020 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1021 * to zero. This means the last (32 - range) bits of the address must be set to zero.
1022 * This is done by shifting the value right and then back left by (32 - range) bits.
1026 v4.s_addr = ntohl(v4.s_addr);
1027 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1028 v4.s_addr = htonl(v4.s_addr);
1032 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1033 * this has undefined behaviour, but for CIDR purposes the resulting mask
1034 * from a.b.c.d/0 is 0.0.0.0/0
1039 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1045 return ""; // unused, but oh well
1048 const char* User::GetIPString()
1051 if (cachedip.empty())
1053 irc::sockets::satoap(&client_sa, cachedip, port);
1054 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1055 if (cachedip.c_str()[0] == ':')
1056 cachedip.insert(0,1,'0');
1059 return cachedip.c_str();
1062 bool User::SetClientIP(const char* sip)
1064 this->cachedip = "";
1065 return irc::sockets::aptosa(sip, 0, &client_sa);
1068 static std::string wide_newline("\r\n");
1070 void User::Write(const std::string& text)
1072 if (!ServerInstance->SE->BoundsCheckFd(this))
1075 if (text.length() > MAXBUF - 2)
1077 // this should happen rarely or never. Crop the string at 512 and try again.
1078 std::string try_again = text.substr(0, MAXBUF - 2);
1083 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1085 this->AddWriteBuf(text);
1086 this->AddWriteBuf(wide_newline);
1088 ServerInstance->stats->statsSent += text.length() + 2;
1089 this->bytes_out += text.length() + 2;
1095 void User::Write(const char *text, ...)
1098 char textbuffer[MAXBUF];
1100 va_start(argsPtr, text);
1101 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1104 this->Write(std::string(textbuffer));
1107 void User::WriteServ(const std::string& text)
1109 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1113 * Same as Write(), except `text' is prefixed with `:server.name '.
1115 void User::WriteServ(const char* text, ...)
1118 char textbuffer[MAXBUF];
1120 va_start(argsPtr, text);
1121 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1124 this->WriteServ(std::string(textbuffer));
1128 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1131 char textbuffer[MAXBUF];
1133 va_start(argsPtr, text);
1134 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1137 this->WriteNumeric(numeric, std::string(textbuffer));
1140 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1142 char textbuffer[MAXBUF];
1143 ModResult MOD_RESULT;
1145 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1147 if (MOD_RESULT == MOD_RES_DENY)
1150 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1151 this->Write(std::string(textbuffer));
1154 void User::WriteFrom(User *user, const std::string &text)
1158 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1160 this->Write(std::string(tb));
1164 /* write text from an originating user to originating user */
1166 void User::WriteFrom(User *user, const char* text, ...)
1169 char textbuffer[MAXBUF];
1171 va_start(argsPtr, text);
1172 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1175 this->WriteFrom(user, std::string(textbuffer));
1179 /* write text to an destination user from a source user (e.g. user privmsg) */
1181 void User::WriteTo(User *dest, const char *data, ...)
1183 char textbuffer[MAXBUF];
1186 va_start(argsPtr, data);
1187 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1190 this->WriteTo(dest, std::string(textbuffer));
1193 void User::WriteTo(User *dest, const std::string &data)
1195 dest->WriteFrom(this, data);
1198 void User::WriteCommon(const char* text, ...)
1200 char textbuffer[MAXBUF];
1203 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1206 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1208 va_start(argsPtr, text);
1209 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1212 this->WriteCommonRaw(std::string(textbuffer), true);
1215 void User::WriteCommonExcept(const char* text, ...)
1217 char textbuffer[MAXBUF];
1220 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1223 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1225 va_start(argsPtr, text);
1226 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1229 this->WriteCommonRaw(std::string(textbuffer), false);
1232 void User::WriteCommonRaw(const std::string &line, bool include_self)
1234 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1238 InitializeAlreadySent(ServerInstance->SE);
1241 UserChanList include_c(chans);
1242 std::map<User*,bool> exceptions;
1244 exceptions[this] = include_self;
1246 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1248 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1251 if (IS_LOCAL(u) && !u->quitting)
1253 already_sent[u->fd] = uniq_id;
1258 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1261 const UserMembList* ulist = c->GetUsers();
1262 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1265 if (IS_LOCAL(u) && !u->quitting && already_sent[u->fd] != uniq_id)
1267 already_sent[u->fd] = uniq_id;
1274 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1279 if (this->registered != REG_ALL)
1285 InitializeAlreadySent(ServerInstance->SE);
1287 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1288 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1289 std::string out1 = tb1;
1290 std::string out2 = tb2;
1292 UserChanList include_c(chans);
1293 std::map<User*,bool> exceptions;
1295 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1297 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1300 if (IS_LOCAL(u) && !u->quitting)
1302 already_sent[u->fd] = uniq_id;
1304 u->Write(IS_OPER(u) ? out2 : out1);
1307 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1309 const UserMembList* ulist = (*v)->GetUsers();
1310 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1313 if (IS_LOCAL(u) && !u->quitting && (already_sent[u->fd] != uniq_id))
1315 already_sent[u->fd] = uniq_id;
1316 u->Write(IS_OPER(u) ? out2 : out1);
1322 void User::WriteWallOps(const std::string &text)
1324 std::string wallop("WALLOPS :");
1325 wallop.append(text);
1327 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1330 if (t->IsModeSet('w'))
1331 this->WriteTo(t,wallop);
1335 void User::WriteWallOps(const char* text, ...)
1337 if (!IS_LOCAL(this))
1340 char textbuffer[MAXBUF];
1343 va_start(argsPtr, text);
1344 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1347 this->WriteWallOps(std::string(textbuffer));
1350 /* return 0 or 1 depending if users u and u2 share one or more common channels
1351 * (used by QUIT, NICK etc which arent channel specific notices)
1353 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1354 * the first users channels then the second users channels within the outer loop,
1355 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1356 * all possible iterations). However this new function instead checks against the
1357 * channel's userlist in the inner loop which is a std::map<User*,User*>
1358 * and saves us time as we already know what pointer value we are after.
1359 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1360 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1362 bool User::SharesChannelWith(User *other)
1364 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1368 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1370 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1371 * by replacing it with a map::find which *should* be more efficient
1373 if ((*i)->HasUser(other))
1379 bool User::ChangeName(const char* gecos)
1381 if (!this->fullname.compare(gecos))
1386 ModResult MOD_RESULT;
1387 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (this,gecos));
1388 if (MOD_RESULT == MOD_RES_DENY)
1390 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1392 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1397 void User::DoHostCycle(const std::string &quitline)
1399 char buffer[MAXBUF];
1401 if (!ServerInstance->Config->CycleHosts)
1407 InitializeAlreadySent(ServerInstance->SE);
1409 UserChanList include_c(chans);
1410 std::map<User*,bool> exceptions;
1412 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1414 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1417 if (IS_LOCAL(u) && !u->quitting)
1419 already_sent[u->fd] = uniq_id;
1424 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1427 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1428 std::string joinline(buffer);
1429 std::string modeline = ServerInstance->Modes->ModeString(this, c);
1430 if (modeline.length() > 0)
1432 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1436 const UserMembList *ulist = c->GetUsers();
1437 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1440 if (u == this || !IS_LOCAL(u))
1443 if (already_sent[i->first->fd] != uniq_id)
1446 already_sent[i->first->fd] = uniq_id;
1449 if (modeline.length() > 0)
1455 bool User::ChangeDisplayedHost(const char* shost)
1462 ModResult MOD_RESULT;
1463 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (this,shost));
1464 if (MOD_RESULT == MOD_RES_DENY)
1468 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1470 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1472 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1473 this->dhost.assign(shost, 0, 64);
1475 this->InvalidateCache();
1477 this->DoHostCycle(quitstr);
1480 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1485 bool User::ChangeIdent(const char* newident)
1487 if (this->ident == newident)
1490 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1492 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1494 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1496 this->InvalidateCache();
1498 this->DoHostCycle(quitstr);
1503 void User::SendAll(const char* command, const char* text, ...)
1505 char textbuffer[MAXBUF];
1506 char formatbuffer[MAXBUF];
1509 va_start(argsPtr, text);
1510 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1513 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1514 std::string fmt = formatbuffer;
1516 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1523 std::string User::ChannelList(User* source, bool spy)
1527 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1530 /* If the target is the sender, neither +p nor +s is set, or
1531 * the channel contains the user, it is not a spy channel
1533 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1534 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1540 void User::SplitChanList(User* dest, const std::string &cl)
1543 std::ostringstream prefix;
1544 std::string::size_type start, pos, length;
1546 prefix << this->nick << " " << dest->nick << " :";
1547 line = prefix.str();
1548 int namelen = ServerInstance->Config->ServerName.length() + 6;
1550 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1552 length = (pos == std::string::npos) ? cl.length() : pos;
1554 if (line.length() + namelen + length - start > 510)
1556 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1557 line = prefix.str();
1560 if(pos == std::string::npos)
1562 line.append(cl.substr(start, length - start));
1567 line.append(cl.substr(start, length - start + 1));
1573 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1578 * Sets a user's connection class.
1579 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1580 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1581 * then their ip will be taken as 'priority' anyway, so for example,
1582 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1584 ConnectClass* User::SetClass(const std::string &explicit_name)
1586 ConnectClass *found = NULL;
1588 if (!IS_LOCAL(this))
1591 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1593 if (!explicit_name.empty())
1595 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1597 ConnectClass* c = *i;
1599 if (explicit_name == c->name)
1601 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1608 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1610 ConnectClass* c = *i;
1612 if (c->type == CC_ALLOW)
1614 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1618 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1621 /* check if host matches.. */
1622 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1623 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1625 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1630 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1631 * because we should attempt to find another class if this one doesn't match us. -- w00t
1633 if (c->limit && (c->GetReferenceCount() >= c->limit))
1635 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1639 /* if it requires a port ... */
1642 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1644 /* and our port doesn't match, fail. */
1645 if (this->GetServerPort() != c->GetPort())
1647 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1652 /* we stop at the first class that meets ALL critera. */
1659 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1666 return this->MyClass;
1669 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1670 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1671 * then their ip will be taken as 'priority' anyway, so for example,
1672 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1674 ConnectClass* User::GetClass()
1676 return this->MyClass;
1679 void User::PurgeEmptyChannels()
1681 std::vector<Channel*> to_delete;
1683 // firstly decrement the count on each channel
1684 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1687 c->RemoveAllPrefixes(this);
1688 if (c->DelUser(this) == 0)
1690 /* No users left in here, mark it for deletion */
1693 to_delete.push_back(c);
1697 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1702 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1704 Channel* thischan = *n;
1705 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1706 if (i2 != ServerInstance->chanlist->end())
1708 ModResult MOD_RESULT;
1709 FIRST_MOD_RESULT(OnChannelPreDelete, MOD_RESULT, (i2->second));
1710 if (MOD_RESULT == MOD_RES_DENY)
1711 continue; // delete halted by module
1712 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1714 ServerInstance->chanlist->erase(i2);
1715 this->chans.erase(*n);
1722 void User::ShowMOTD()
1724 if (!ServerInstance->Config->MOTD.size())
1726 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1729 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1731 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1732 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1734 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1737 void User::ShowRULES()
1739 if (!ServerInstance->Config->RULES.size())
1741 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1745 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1747 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1748 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1750 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1753 void User::IncreasePenalty(int increase)
1755 this->Penalty += increase;
1758 void User::DecreasePenalty(int decrease)
1760 this->Penalty -= decrease;
1763 void FakeUser::SetFakeServer(std::string name)
1766 this->server = name;
1769 const std::string FakeUser::GetFullHost()
1771 if (!ServerInstance->Config->HideWhoisServer.empty())
1772 return ServerInstance->Config->HideWhoisServer;
1776 const std::string FakeUser::GetFullRealHost()
1778 if (!ServerInstance->Config->HideWhoisServer.empty())
1779 return ServerInstance->Config->HideWhoisServer;
1783 ConnectClass::ConnectClass(char t, const std::string& mask)
1784 : type(t), name("unnamed"), registration_timeout(0), host(mask),
1785 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1786 recvqmax(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1790 ConnectClass::ConnectClass(char t, const std::string& mask, const ConnectClass& parent)
1791 : type(t), name("unnamed"),
1792 registration_timeout(parent.registration_timeout), host(mask),
1793 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1794 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1795 recvqmax(parent.recvqmax), maxlocal(parent.maxlocal),
1796 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1797 port(parent.port), limit(parent.limit)
1801 void ConnectClass::Update(const ConnectClass* src)
1804 registration_timeout = src->registration_timeout;
1806 pingtime = src->pingtime;
1809 softsendqmax = src->softsendqmax;
1810 hardsendqmax = src->hardsendqmax;
1811 recvqmax = src->recvqmax;
1812 maxlocal = src->maxlocal;
1813 maxglobal = src->maxglobal;