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 /* XXX: Used for speeding up WriteCommon operations */
24 unsigned long uniq_id = 1;
26 static unsigned long* already_sent = NULL;
28 LocalIntExt User::NICKForced("NICKForced", NULL);
29 LocalStringExt User::OperQuit("OperQuit", NULL);
31 void InitializeAlreadySent(SocketEngine* SE)
33 already_sent = new unsigned long[SE->GetMaxFds()];
34 memset(already_sent, 0, SE->GetMaxFds() * sizeof(unsigned long));
37 std::string User::ProcessNoticeMasks(const char *sm)
39 bool adding = true, oldadding = false;
54 for (unsigned char d = 'A'; d <= 'z'; d++)
56 if (ServerInstance->SNO->IsEnabled(d))
58 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
60 if ((oldadding != adding) || (!output.length()))
61 output += (adding ? '+' : '-');
63 this->SetNoticeMask(d, adding);
72 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
74 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
76 if ((oldadding != adding) || (!output.length()))
77 output += (adding ? '+' : '-');
79 this->SetNoticeMask(*c, adding);
85 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
94 std::string s = this->FormatNoticeMasks();
97 this->modes[UM_SNOMASK] = false;
103 void User::StartDNSLookup()
108 const char* sip = this->GetIPString();
109 UserResolver *res_reverse;
111 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
112 res_reverse = new UserResolver(this, sip, resolvtype, cached);
114 ServerInstance->AddResolver(res_reverse, cached);
116 catch (CoreException& e)
118 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
122 bool User::IsNoticeMaskSet(unsigned char sm)
126 return (snomasks[sm-65]);
129 void User::SetNoticeMask(unsigned char sm, bool value)
133 snomasks[sm-65] = value;
136 const char* User::FormatNoticeMasks()
138 static char data[MAXBUF];
141 for (int n = 0; n < 64; n++)
144 data[offset++] = n+65;
151 bool User::IsModeSet(unsigned char m)
155 return (modes[m-65]);
158 void User::SetMode(unsigned char m, bool value)
165 const char* User::FormatModes(bool showparameters)
167 static char data[MAXBUF];
171 for (unsigned char n = 0; n < 64; n++)
175 data[offset++] = n + 65;
176 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
177 if (showparameters && mh && mh->GetNumParams(true))
179 std::string p = mh->GetUserParameter(this);
181 params.append(" ").append(p);
186 strlcat(data, params.c_str(), MAXBUF);
190 void User::DecrementModes()
192 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
193 for (unsigned char n = 'A'; n <= 'z'; n++)
197 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
198 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
201 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
208 User::User(const std::string &uid)
210 server = ServerInstance->Config->ServerName;
211 age = ServerInstance->Time();
213 lastping = signon = idle_lastmsg = nping = registered = 0;
214 bytes_in = bytes_out = cmds_in = cmds_out = 0;
215 quietquit = quitting = exempt = haspassed = dns_done = false;
217 server_sa.sa.sa_family = AF_UNSPEC;
218 client_sa.sa.sa_family = AF_UNSPEC;
220 AllowedPrivs = AllowedOperCommands = NULL;
223 uuid.assign(ServerInstance->GetUID(), 0, UUID_LENGTH - 1);
225 uuid.assign(uid, 0, UUID_LENGTH - 1);
227 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid.c_str(), uid.empty() ? "allocated new" : "used remote");
229 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
230 if (finduuid == ServerInstance->Users->uuidlist->end())
231 (*ServerInstance->Users->uuidlist)[uuid] = this;
233 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
239 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
242 const std::string& User::MakeHost()
244 if (!this->cached_makehost.empty())
245 return this->cached_makehost;
248 /* This is much faster than snprintf */
250 for(const char* n = ident.c_str(); *n; n++)
253 for(const char* n = host.c_str(); *n; n++)
257 this->cached_makehost.assign(nhost);
259 return this->cached_makehost;
262 const std::string& User::MakeHostIP()
264 if (!this->cached_hostip.empty())
265 return this->cached_hostip;
268 /* This is much faster than snprintf */
270 for(const char* n = ident.c_str(); *n; n++)
273 for(const char* n = this->GetIPString(); *n; n++)
277 this->cached_hostip = ihost;
279 return this->cached_hostip;
282 const std::string User::GetFullHost()
284 if (!this->cached_fullhost.empty())
285 return this->cached_fullhost;
289 for(const char* n = nick.c_str(); *n; n++)
292 for(const char* n = ident.c_str(); *n; n++)
295 for(const char* n = dhost.c_str(); *n; n++)
299 this->cached_fullhost = result;
301 return this->cached_fullhost;
304 char* User::MakeWildHost()
306 static char nresult[MAXBUF];
308 *t++ = '*'; *t++ = '!';
309 *t++ = '*'; *t++ = '@';
310 for(const char* n = dhost.c_str(); *n; n++)
316 const std::string User::GetFullRealHost()
318 if (!this->cached_fullrealhost.empty())
319 return this->cached_fullrealhost;
321 char fresult[MAXBUF];
323 for(const char* n = nick.c_str(); *n; n++)
326 for(const char* n = ident.c_str(); *n; n++)
329 for(const char* n = host.c_str(); *n; n++)
333 this->cached_fullrealhost = fresult;
335 return this->cached_fullrealhost;
338 bool User::IsInvited(const irc::string &channel)
340 time_t now = ServerInstance->Time();
341 InvitedList::iterator safei;
342 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
344 if (channel == i->first)
346 if (i->second != 0 && now > i->second)
348 /* Expired invite, remove it. */
351 invites.erase(safei);
360 InvitedList* User::GetInviteList()
362 time_t now = ServerInstance->Time();
363 /* Weed out expired invites here. */
364 InvitedList::iterator safei;
365 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
367 if (i->second != 0 && now > i->second)
369 /* Expired invite, remove it. */
372 invites.erase(safei);
378 void User::InviteTo(const irc::string &channel, time_t invtimeout)
380 time_t now = ServerInstance->Time();
381 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
382 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
384 if (channel == i->first)
386 if (i->second != 0 && invtimeout > i->second)
388 i->second = invtimeout;
394 invites.push_back(std::make_pair(channel, invtimeout));
397 void User::RemoveInvite(const irc::string &channel)
399 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
401 if (channel == i->first)
409 bool User::HasModePermission(unsigned char mode, ModeType type)
417 if (mode < 'A' || mode > ('A' + 64)) return false;
419 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
423 bool User::HasPermission(const std::string &command)
426 * users on remote servers can completely bypass all permissions based checks.
427 * This prevents desyncs when one server has different type/class tags to another.
428 * That having been said, this does open things up to the possibility of source changes
429 * allowing remote kills, etc - but if they have access to the src, they most likely have
430 * access to the conf - so it's an end to a means either way.
435 // are they even an oper at all?
441 if (!AllowedOperCommands)
444 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
446 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
453 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
457 ServerInstance->Logs->Log("PRIVS", DEBUG, "Remote (yes)");
464 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
471 this->WriteServ("NOTICE %s :Privset empty(!?)", this->nick.c_str());
475 if (AllowedPrivs->find(privstr) != AllowedPrivs->end())
479 else if (AllowedPrivs->find("*") != AllowedPrivs->end())
485 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());
489 void User::OnDataReady()
494 if (MyClass && recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
496 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
497 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
498 nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
500 unsigned long sendqmax = ULONG_MAX;
501 if (MyClass && !HasPrivPermission("users/flood/increased-buffers"))
502 sendqmax = MyClass->GetSendqSoftMax();
504 while (Penalty < 10 && getSendQSize() < sendqmax)
507 line.reserve(MAXBUF);
508 std::string::size_type qpos = 0;
509 while (qpos < recvq.length())
511 char c = recvq[qpos++];
522 if (line.length() < MAXBUF - 2)
525 // if we got here, the recvq ran out before we found a newline
528 // just found a newline. Terminate the string, and pull it out of recvq
529 recvq = recvq.substr(qpos);
531 // TODO should this be moved to when it was inserted in recvq?
532 ServerInstance->stats->statsRecv += qpos;
533 this->bytes_in += qpos;
536 ServerInstance->Parser->ProcessBuffer(line, this);
538 // Add pseudo-penalty so that we continue processing after sendq recedes
539 if (Penalty == 0 && getSendQSize() >= sendqmax)
543 void User::AddWriteBuf(const std::string &data)
545 // Don't bother sending text to remote users!
548 if (!quitting && MyClass && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
551 * Quit the user FIRST, because otherwise we could recurse
552 * here and hit the same limit.
554 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
555 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
556 nick.c_str(), MyClass->GetSendqHardMax());
560 // We still want to append data to the sendq of a quitting user,
561 // e.g. their ERROR message that says 'closing link'
566 void User::OnError(BufferedSocketError)
568 ServerInstance->Users->QuitUser(this, getError());
574 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
577 ServerInstance->Logs->Log("USERS", DEBUG, "User culled twice? UUID empty");
580 PurgeEmptyChannels();
586 std::vector<User*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
587 if (x != ServerInstance->Users->local_users.end())
588 ServerInstance->Users->local_users.erase(x);
590 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
593 if (this->AllowedOperCommands)
595 delete AllowedOperCommands;
596 AllowedOperCommands = NULL;
599 if (this->AllowedPrivs)
605 this->InvalidateCache();
606 this->DecrementModes();
608 if (client_sa.sa.sa_family != AF_UNSPEC)
609 ServerInstance->Users->RemoveCloneCounts(this);
611 ServerInstance->Users->uuidlist->erase(uuid);
616 void User::Oper(const std::string &opertype, const std::string &opername)
618 if (this->IsModeSet('o'))
621 this->modes[UM_OPERATOR] = 1;
622 this->WriteServ("MODE %s :+o", this->nick.c_str());
623 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
625 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());
626 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()));
628 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());
629 this->oper.assign(opertype, 0, 512);
630 ServerInstance->Users->all_opers.push_back(this);
633 * This might look like it's in the wrong place.
636 * 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.
639 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
640 if (iter_opertype != ServerInstance->Config->opertypes.end())
642 if (AllowedOperCommands)
643 AllowedOperCommands->clear();
645 AllowedOperCommands = new std::set<std::string>;
648 AllowedPrivs->clear();
650 AllowedPrivs = new std::set<std::string>;
652 AllowedUserModes.reset();
653 AllowedChanModes.reset();
654 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
656 std::string myclass, mycmd, mypriv;
657 irc::spacesepstream Classes(iter_opertype->second.c_str());
658 while (Classes.GetToken(myclass))
660 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass.c_str());
661 if (iter_operclass != ServerInstance->Config->operclass.end())
663 /* Process commands */
664 irc::spacesepstream CommandList(iter_operclass->second.commandlist);
665 while (CommandList.GetToken(mycmd))
667 this->AllowedOperCommands->insert(mycmd);
670 irc::spacesepstream PrivList(iter_operclass->second.privs);
671 while (PrivList.GetToken(mypriv))
673 this->AllowedPrivs->insert(mypriv);
676 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist.c_str(); *c; ++c)
680 this->AllowedUserModes.set();
684 this->AllowedUserModes[*c - 'A'] = true;
688 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist.c_str(); *c; ++c)
692 this->AllowedChanModes.set();
696 this->AllowedChanModes[*c - 'A'] = true;
703 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
711 * unset their oper type (what IS_OPER checks).
712 * note, order is important - this must come before modes as -o attempts
713 * to call UnOper. -- w00t
718 /* Remove all oper only modes from the user when the deoper - Bug #466*/
719 std::string moderemove("-");
721 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
723 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
724 if (mh && mh->NeedsOper())
725 moderemove += letter;
729 std::vector<std::string> parameters;
730 parameters.push_back(this->nick);
731 parameters.push_back(moderemove);
733 ServerInstance->Parser->CallHandler("MODE", parameters, this);
735 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
736 ServerInstance->Users->all_opers.remove(this);
738 if (AllowedOperCommands)
740 delete AllowedOperCommands;
741 AllowedOperCommands = NULL;
750 AllowedUserModes.reset();
751 AllowedChanModes.reset();
752 this->modes[UM_OPERATOR] = 0;
756 /* adds or updates an entry in the whowas list */
757 void User::AddToWhoWas()
759 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
762 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
769 * Check class restrictions
771 void User::CheckClass()
773 ConnectClass* a = this->MyClass;
775 if ((!a) || (a->type == CC_DENY))
777 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
780 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
782 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
783 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
786 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
788 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
789 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
793 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
796 bool User::CheckLines(bool doZline)
798 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
802 for (int n = 0; check[n]; ++n)
804 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
817 void User::FullConnect()
819 ServerInstance->stats->statsConnects++;
820 this->idle_lastmsg = ServerInstance->Time();
823 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
824 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
825 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
826 * Don't remove this! -- w00t
830 /* Check the password, if one is required by the user's connect class.
831 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
833 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
835 ServerInstance->Users->QuitUser(this, "Invalid password");
839 if (this->CheckLines())
842 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
843 this->WriteNumeric(RPL_WELCOME, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick.c_str(), ServerInstance->Config->Network.c_str(), this->nick.c_str(), this->ident.c_str(), this->host.c_str());
844 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
845 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
846 this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-2.0 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
848 ServerInstance->Config->Send005(this);
849 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
855 if (ServerInstance->Users->unregistered_count)
856 ServerInstance->Users->unregistered_count--;
858 /* Trigger LUSERS output, give modules a chance too */
859 ModResult MOD_RESULT;
860 std::string command("LUSERS");
861 std::vector<std::string> parameters;
862 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
864 ServerInstance->CallCommandHandler(command, parameters, this);
867 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
868 * for a user that doesn't exist yet.
870 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
872 this->registered = REG_ALL;
874 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
876 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
877 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
878 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
879 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
882 /** User::UpdateNick()
883 * re-allocates a nick in the user_hash after they change nicknames,
884 * returns a pointer to the new user as it may have moved
886 User* User::UpdateNickHash(const char* New)
888 //user_hash::iterator newnick;
889 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
891 if (!irc::string(this->nick.c_str()).compare(New))
892 return oldnick->second;
894 if (oldnick == ServerInstance->Users->clientlist->end())
895 return NULL; /* doesnt exist */
897 User* olduser = oldnick->second;
898 ServerInstance->Users->clientlist->erase(oldnick);
899 (*(ServerInstance->Users->clientlist))[New] = olduser;
903 void User::InvalidateCache()
905 /* Invalidate cache */
906 cached_fullhost.clear();
907 cached_hostip.clear();
908 cached_makehost.clear();
909 cached_fullrealhost.clear();
912 bool User::ForceNickChange(const char* newnick)
914 ModResult MOD_RESULT;
916 this->InvalidateCache();
918 NICKForced.set(this, 1);
919 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
920 NICKForced.set(this, 0);
922 if (MOD_RESULT == MOD_RES_DENY)
924 ServerInstance->stats->statsCollisions++;
928 std::deque<classbase*> dummy;
929 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
930 if (nickhandler) // wtfbbq, when would this not be here
932 std::vector<std::string> parameters;
933 parameters.push_back(newnick);
934 NICKForced.set(this, 1);
935 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
936 NICKForced.set(this, 0);
940 // Unreachable, we hope
944 int User::GetServerPort()
946 switch (this->server_sa.sa.sa_family)
949 return htons(this->server_sa.in6.sin6_port);
951 return htons(this->server_sa.in4.sin_port);
956 const char* User::GetCIDRMask(int range)
961 throw "Negative range, sorry, no.";
964 * Original code written by Oliver Lupton (Om).
965 * Integrated by me. Thanks. :) -- w00t
967 switch (this->client_sa.sa.sa_family)
971 /* unsigned char s6_addr[16]; */
973 int i, bytestozero, extrabits;
977 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
979 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
980 * to zero. This means the last (128 - range) bits of the address must be set to zero.
981 * Hence this number divided by 8 is the number of whole bytes from the end of the address
982 * which must be set to zero.
984 bytestozero = (128 - range) / 8;
986 /* Some of the least significant bits of the next most significant byte may also have to
987 * be zeroed. The number of bits is the remainder of the above division.
989 extrabits = (128 - range) % 8;
991 /* Populate our working struct with the parts of the user's IP which are required in the
992 * final CIDR mask. Set all the subsequent bytes to zero.
993 * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
995 for(i = 0; i < (16 - bytestozero); i++)
997 v6.s6_addr[i] = client_sa.in6.sin6_addr.s6_addr[i];
1000 /* And zero all the remaining bytes in the IP. */
1006 /* And finally, zero the extra bits required. */
1007 v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1009 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1019 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1021 /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1022 v4.s_addr = client_sa.in4.sin_addr.s_addr;
1024 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1025 * to zero. This means the last (32 - range) bits of the address must be set to zero.
1026 * This is done by shifting the value right and then back left by (32 - range) bits.
1030 v4.s_addr = ntohl(v4.s_addr);
1031 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1032 v4.s_addr = htonl(v4.s_addr);
1036 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1037 * this has undefined behaviour, but for CIDR purposes the resulting mask
1038 * from a.b.c.d/0 is 0.0.0.0/0
1043 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1049 return ""; // unused, but oh well
1052 const char* User::GetIPString()
1055 if (cachedip.empty())
1057 irc::sockets::satoap(&client_sa, cachedip, port);
1058 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1059 if (cachedip.c_str()[0] == ':')
1060 cachedip.insert(0,1,'0');
1063 return cachedip.c_str();
1066 bool User::SetClientIP(const char* sip)
1068 this->cachedip = "";
1069 return irc::sockets::aptosa(sip, 0, &client_sa);
1072 static std::string wide_newline("\r\n");
1074 void User::Write(const std::string& text)
1076 if (!ServerInstance->SE->BoundsCheckFd(this))
1079 if (text.length() > MAXBUF - 2)
1081 // this should happen rarely or never. Crop the string at 512 and try again.
1082 std::string try_again = text.substr(0, MAXBUF - 2);
1087 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1089 this->AddWriteBuf(text);
1090 this->AddWriteBuf(wide_newline);
1092 ServerInstance->stats->statsSent += text.length() + 2;
1093 this->bytes_out += text.length() + 2;
1099 void User::Write(const char *text, ...)
1102 char textbuffer[MAXBUF];
1104 va_start(argsPtr, text);
1105 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1108 this->Write(std::string(textbuffer));
1111 void User::WriteServ(const std::string& text)
1113 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1117 * Same as Write(), except `text' is prefixed with `:server.name '.
1119 void User::WriteServ(const char* text, ...)
1122 char textbuffer[MAXBUF];
1124 va_start(argsPtr, text);
1125 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1128 this->WriteServ(std::string(textbuffer));
1132 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1135 char textbuffer[MAXBUF];
1137 va_start(argsPtr, text);
1138 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1141 this->WriteNumeric(numeric, std::string(textbuffer));
1144 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1146 char textbuffer[MAXBUF];
1147 ModResult MOD_RESULT;
1149 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1151 if (MOD_RESULT == MOD_RES_DENY)
1154 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1155 this->Write(std::string(textbuffer));
1158 void User::WriteFrom(User *user, const std::string &text)
1162 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1164 this->Write(std::string(tb));
1168 /* write text from an originating user to originating user */
1170 void User::WriteFrom(User *user, const char* text, ...)
1173 char textbuffer[MAXBUF];
1175 va_start(argsPtr, text);
1176 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1179 this->WriteFrom(user, std::string(textbuffer));
1183 /* write text to an destination user from a source user (e.g. user privmsg) */
1185 void User::WriteTo(User *dest, const char *data, ...)
1187 char textbuffer[MAXBUF];
1190 va_start(argsPtr, data);
1191 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1194 this->WriteTo(dest, std::string(textbuffer));
1197 void User::WriteTo(User *dest, const std::string &data)
1199 dest->WriteFrom(this, data);
1203 void User::WriteCommon(const char* text, ...)
1205 char textbuffer[MAXBUF];
1208 if (this->registered != REG_ALL)
1211 va_start(argsPtr, text);
1212 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1215 this->WriteCommon(std::string(textbuffer));
1218 void User::WriteCommon(const std::string &text)
1220 bool sent_to_at_least_one = false;
1223 if (this->registered != REG_ALL)
1229 InitializeAlreadySent(ServerInstance->SE);
1231 /* We dont want to be doing this n times, just once */
1232 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1233 std::string out = tb;
1235 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1237 const UserMembList* ulist = (*v)->GetUsers();
1238 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1240 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1242 already_sent[i->first->fd] = uniq_id;
1243 i->first->Write(out);
1244 sent_to_at_least_one = true;
1250 * if the user was not in any channels, no users will receive the text. Make sure the user
1251 * receives their OWN message for WriteCommon
1253 if (!sent_to_at_least_one)
1255 this->Write(std::string(tb));
1260 /* write a formatted string to all users who share at least one common
1261 * channel, NOT including the source user e.g. for use in QUIT
1264 void User::WriteCommonExcept(const char* text, ...)
1266 char textbuffer[MAXBUF];
1269 va_start(argsPtr, text);
1270 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1273 this->WriteCommonExcept(std::string(textbuffer));
1276 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1281 if (this->registered != REG_ALL)
1287 InitializeAlreadySent(ServerInstance->SE);
1289 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1290 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1291 std::string out1 = tb1;
1292 std::string out2 = tb2;
1294 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1296 const UserMembList* ulist = (*v)->GetUsers();
1297 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1300 if (IS_LOCAL(u) && !u->quitting && (already_sent[u->fd] != uniq_id))
1302 already_sent[u->fd] = uniq_id;
1303 u->Write(IS_OPER(u) ? out2 : out1);
1309 void User::WriteCommonExcept(const std::string &text)
1314 if (this->registered != REG_ALL)
1320 InitializeAlreadySent(ServerInstance->SE);
1322 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1325 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1327 const UserMembList* ulist = (*v)->GetUsers();
1328 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1330 if (this != i->first)
1332 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1334 already_sent[i->first->fd] = uniq_id;
1335 i->first->Write(out1);
1343 void User::WriteWallOps(const std::string &text)
1345 std::string wallop("WALLOPS :");
1346 wallop.append(text);
1348 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1351 if (t->IsModeSet('w'))
1352 this->WriteTo(t,wallop);
1356 void User::WriteWallOps(const char* text, ...)
1358 if (!IS_LOCAL(this))
1361 char textbuffer[MAXBUF];
1364 va_start(argsPtr, text);
1365 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1368 this->WriteWallOps(std::string(textbuffer));
1371 /* return 0 or 1 depending if users u and u2 share one or more common channels
1372 * (used by QUIT, NICK etc which arent channel specific notices)
1374 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1375 * the first users channels then the second users channels within the outer loop,
1376 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1377 * all possible iterations). However this new function instead checks against the
1378 * channel's userlist in the inner loop which is a std::map<User*,User*>
1379 * and saves us time as we already know what pointer value we are after.
1380 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1381 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1383 bool User::SharesChannelWith(User *other)
1385 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1389 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1391 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1392 * by replacing it with a map::find which *should* be more efficient
1394 if ((*i)->HasUser(other))
1400 bool User::ChangeName(const char* gecos)
1402 if (!this->fullname.compare(gecos))
1407 ModResult MOD_RESULT;
1408 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (this,gecos));
1409 if (MOD_RESULT == MOD_RES_DENY)
1411 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1413 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1418 void User::DoHostCycle(const std::string &quitline)
1420 char buffer[MAXBUF];
1422 ModResult result = MOD_RES_PASSTHRU;
1423 FIRST_MOD_RESULT(OnHostCycle, result, (this));
1425 if (result == MOD_RES_DENY)
1427 if (result == MOD_RES_PASSTHRU && !ServerInstance->Config->CycleHosts)
1433 InitializeAlreadySent(ServerInstance->SE);
1435 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1438 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1439 std::string joinline(buffer);
1440 std::string modeline = ServerInstance->Modes->ModeString(this, c);
1441 if (modeline.length() > 0)
1443 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1447 const UserMembList *ulist = c->GetUsers();
1448 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1451 if (u == this || !IS_LOCAL(u))
1454 if (already_sent[i->first->fd] != uniq_id)
1457 already_sent[i->first->fd] = uniq_id;
1460 if (modeline.length() > 0)
1466 bool User::ChangeDisplayedHost(const char* shost)
1473 ModResult MOD_RESULT;
1474 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (this,shost));
1475 if (MOD_RESULT == MOD_RES_DENY)
1479 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1481 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1483 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1484 this->dhost.assign(shost, 0, 64);
1486 this->InvalidateCache();
1488 this->DoHostCycle(quitstr);
1491 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1496 bool User::ChangeIdent(const char* newident)
1498 if (this->ident == newident)
1501 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1503 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1505 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1507 this->InvalidateCache();
1509 this->DoHostCycle(quitstr);
1514 void User::SendAll(const char* command, const char* text, ...)
1516 char textbuffer[MAXBUF];
1517 char formatbuffer[MAXBUF];
1520 va_start(argsPtr, text);
1521 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1524 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1525 std::string fmt = formatbuffer;
1527 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1534 std::string User::ChannelList(User* source, bool spy)
1538 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1541 /* If the target is the sender, neither +p nor +s is set, or
1542 * the channel contains the user, it is not a spy channel
1544 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1545 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1551 void User::SplitChanList(User* dest, const std::string &cl)
1554 std::ostringstream prefix;
1555 std::string::size_type start, pos, length;
1557 prefix << this->nick << " " << dest->nick << " :";
1558 line = prefix.str();
1559 int namelen = ServerInstance->Config->ServerName.length() + 6;
1561 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1563 length = (pos == std::string::npos) ? cl.length() : pos;
1565 if (line.length() + namelen + length - start > 510)
1567 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1568 line = prefix.str();
1571 if(pos == std::string::npos)
1573 line.append(cl.substr(start, length - start));
1578 line.append(cl.substr(start, length - start + 1));
1584 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1589 * Sets a user's connection class.
1590 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1591 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1592 * then their ip will be taken as 'priority' anyway, so for example,
1593 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1595 ConnectClass* User::SetClass(const std::string &explicit_name)
1597 ConnectClass *found = NULL;
1599 if (!IS_LOCAL(this))
1602 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1604 if (!explicit_name.empty())
1606 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1608 ConnectClass* c = *i;
1610 if (explicit_name == c->name)
1612 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1619 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1621 ConnectClass* c = *i;
1623 if (c->type == CC_ALLOW)
1625 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1629 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1632 /* check if host matches.. */
1633 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1634 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1636 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1641 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1642 * because we should attempt to find another class if this one doesn't match us. -- w00t
1644 if (c->limit && (c->GetReferenceCount() >= c->limit))
1646 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1650 /* if it requires a port ... */
1653 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1655 /* and our port doesn't match, fail. */
1656 if (this->GetServerPort() != c->GetPort())
1658 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1663 /* we stop at the first class that meets ALL critera. */
1670 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1677 return this->MyClass;
1680 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1681 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1682 * then their ip will be taken as 'priority' anyway, so for example,
1683 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1685 ConnectClass* User::GetClass()
1687 return this->MyClass;
1690 void User::PurgeEmptyChannels()
1692 std::vector<Channel*> to_delete;
1694 // firstly decrement the count on each channel
1695 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1698 c->RemoveAllPrefixes(this);
1699 if (c->DelUser(this) == 0)
1701 /* No users left in here, mark it for deletion */
1704 to_delete.push_back(c);
1708 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1713 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1715 Channel* thischan = *n;
1716 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1717 if (i2 != ServerInstance->chanlist->end())
1719 ModResult MOD_RESULT;
1720 FIRST_MOD_RESULT(OnChannelPreDelete, MOD_RESULT, (i2->second));
1721 if (MOD_RESULT == MOD_RES_DENY)
1722 continue; // delete halted by module
1723 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1725 ServerInstance->chanlist->erase(i2);
1726 this->chans.erase(*n);
1733 void User::ShowMOTD()
1735 if (!ServerInstance->Config->MOTD.size())
1737 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1740 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1742 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1743 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1745 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1748 void User::ShowRULES()
1750 if (!ServerInstance->Config->RULES.size())
1752 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1756 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1758 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1759 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1761 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1764 void User::IncreasePenalty(int increase)
1766 this->Penalty += increase;
1769 void User::DecreasePenalty(int decrease)
1771 this->Penalty -= decrease;
1774 void FakeUser::SetFakeServer(std::string name)
1777 this->server = name;
1780 const std::string FakeUser::GetFullHost()
1782 if (ServerInstance->Config->HideWhoisServer.empty())
1783 return ServerInstance->Config->HideWhoisServer;
1787 const std::string FakeUser::GetFullRealHost()
1789 if (!ServerInstance->Config->HideWhoisServer.empty())
1790 return ServerInstance->Config->HideWhoisServer;
1794 ConnectClass::ConnectClass(char t, const std::string& mask)
1795 : type(t), name("unnamed"), registration_timeout(0), host(mask),
1796 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1797 recvqmax(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1801 ConnectClass::ConnectClass(char t, const std::string& mask, const ConnectClass& parent)
1802 : type(t), name("unnamed"),
1803 registration_timeout(parent.registration_timeout), host(mask),
1804 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1805 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1806 recvqmax(parent.recvqmax), maxlocal(parent.maxlocal),
1807 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1808 port(parent.port), limit(parent.limit)
1812 void ConnectClass::Update(const ConnectClass* src)
1815 registration_timeout = src->registration_timeout;
1817 pingtime = src->pingtime;
1820 softsendqmax = src->softsendqmax;
1821 hardsendqmax = src->hardsendqmax;
1822 recvqmax = src->recvqmax;
1823 maxlocal = src->maxlocal;
1824 maxglobal = src->maxglobal;