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 * ---------------------------------------------------
16 #include "socketengine.h"
19 #include "commands/cmd_whowas.h"
21 typedef unsigned int uniq_id_t;
29 array = new uniq_id_t[ServerInstance->SE->GetMaxFds()];
30 memset(array, 0, ServerInstance->SE->GetMaxFds() * sizeof(uniq_id_t));
34 sent() : uniq_id(static_cast<uniq_id_t>(-1)), array(NULL) {}
35 inline uniq_id_t operator++()
41 inline uniq_id_t& operator[](int i)
51 static sent already_sent;
53 std::string User::ProcessNoticeMasks(const char *sm)
55 bool adding = true, oldadding = false;
70 for (unsigned char d = 'A'; d <= 'z'; d++)
72 if (ServerInstance->SNO->IsEnabled(d))
74 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
76 if ((oldadding != adding) || (!output.length()))
77 output += (adding ? '+' : '-');
79 this->SetNoticeMask(d, adding);
88 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
90 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
92 if ((oldadding != adding) || (!output.length()))
93 output += (adding ? '+' : '-');
95 this->SetNoticeMask(*c, adding);
101 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
110 std::string s = this->FormatNoticeMasks();
113 this->modes[UM_SNOMASK] = false;
119 void LocalUser::StartDNSLookup()
124 const char* sip = this->GetIPString();
125 UserResolver *res_reverse;
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);
130 ServerInstance->AddResolver(res_reverse, cached);
132 catch (CoreException& e)
134 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
138 bool User::IsNoticeMaskSet(unsigned char sm)
142 return (snomasks[sm-65]);
145 void User::SetNoticeMask(unsigned char sm, bool value)
149 snomasks[sm-65] = value;
152 const char* User::FormatNoticeMasks()
154 static char data[MAXBUF];
157 for (int n = 0; n < 64; n++)
160 data[offset++] = n+65;
167 bool User::IsModeSet(unsigned char m)
171 return (modes[m-65]);
174 void User::SetMode(unsigned char m, bool value)
181 const char* User::FormatModes(bool showparameters)
183 static char data[MAXBUF];
187 for (unsigned char n = 0; n < 64; n++)
191 data[offset++] = n + 65;
192 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
193 if (showparameters && mh && mh->GetNumParams(true))
195 std::string p = mh->GetUserParameter(this);
197 params.append(" ").append(p);
202 strlcat(data, params.c_str(), MAXBUF);
206 void User::DecrementModes()
208 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
209 for (unsigned char n = 'A'; n <= 'z'; n++)
213 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
214 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
217 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
224 User::User(const std::string &uid)
226 server = ServerInstance->Config->ServerName;
227 age = ServerInstance->Time();
229 lastping = signon = idle_lastmsg = nping = registered = 0;
230 quietquit = quitting = exempt = dns_done = false;
232 AllowedPrivs = AllowedOperCommands = NULL;
234 client_sa.sa.sa_family = AF_UNSPEC;
236 ServerInstance->Logs->Log("USERS", DEBUG, "New UUID for user: %s", uuid.c_str());
238 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
239 if (finduuid == ServerInstance->Users->uuidlist->end())
240 (*ServerInstance->Users->uuidlist)[uuid] = this;
242 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
245 LocalUser::LocalUser() : User(ServerInstance->GetUID())
247 bytes_in = bytes_out = cmds_in = cmds_out = 0;
248 server_sa.sa.sa_family = AF_UNSPEC;
254 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
257 const std::string& User::MakeHost()
259 if (!this->cached_makehost.empty())
260 return this->cached_makehost;
263 /* This is much faster than snprintf */
265 for(const char* n = ident.c_str(); *n; n++)
268 for(const char* n = host.c_str(); *n; n++)
272 this->cached_makehost.assign(nhost);
274 return this->cached_makehost;
277 const std::string& User::MakeHostIP()
279 if (!this->cached_hostip.empty())
280 return this->cached_hostip;
283 /* This is much faster than snprintf */
285 for(const char* n = ident.c_str(); *n; n++)
288 for(const char* n = this->GetIPString(); *n; n++)
292 this->cached_hostip = ihost;
294 return this->cached_hostip;
297 const std::string User::GetFullHost()
299 if (!this->cached_fullhost.empty())
300 return this->cached_fullhost;
304 for(const char* n = nick.c_str(); *n; n++)
307 for(const char* n = ident.c_str(); *n; n++)
310 for(const char* n = dhost.c_str(); *n; n++)
314 this->cached_fullhost = result;
316 return this->cached_fullhost;
319 char* User::MakeWildHost()
321 static char nresult[MAXBUF];
323 *t++ = '*'; *t++ = '!';
324 *t++ = '*'; *t++ = '@';
325 for(const char* n = dhost.c_str(); *n; n++)
331 const std::string User::GetFullRealHost()
333 if (!this->cached_fullrealhost.empty())
334 return this->cached_fullrealhost;
336 char fresult[MAXBUF];
338 for(const char* n = nick.c_str(); *n; n++)
341 for(const char* n = ident.c_str(); *n; n++)
344 for(const char* n = host.c_str(); *n; n++)
348 this->cached_fullrealhost = fresult;
350 return this->cached_fullrealhost;
353 bool User::IsInvited(const irc::string &channel)
355 time_t now = ServerInstance->Time();
356 InvitedList::iterator safei;
357 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
359 if (channel == i->first)
361 if (i->second != 0 && now > i->second)
363 /* Expired invite, remove it. */
366 invites.erase(safei);
375 InvitedList* User::GetInviteList()
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)
382 if (i->second != 0 && now > i->second)
384 /* Expired invite, remove it. */
387 invites.erase(safei);
393 void User::InviteTo(const irc::string &channel, time_t invtimeout)
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)
399 if (channel == i->first)
401 if (i->second != 0 && invtimeout > i->second)
403 i->second = invtimeout;
409 invites.push_back(std::make_pair(channel, invtimeout));
412 void User::RemoveInvite(const irc::string &channel)
414 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
416 if (channel == i->first)
424 bool User::HasModePermission(unsigned char mode, ModeType type)
432 if (mode < 'A' || mode > ('A' + 64)) return false;
434 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
438 bool User::HasPermission(const std::string &command)
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.
450 // are they even an oper at all?
456 if (!AllowedOperCommands)
459 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
461 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
468 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
472 ServerInstance->Logs->Log("PRIVS", DEBUG, "Remote (yes)");
479 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
486 this->WriteServ("NOTICE %s :Privset empty(!?)", this->nick.c_str());
490 if (AllowedPrivs->find(privstr) != AllowedPrivs->end())
494 else if (AllowedPrivs->find("*") != AllowedPrivs->end())
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());
504 void User::OnDataReady()
508 void LocalUser::OnDataReady()
513 if (MyClass && recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
515 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
516 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
517 nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
519 unsigned long sendqmax = ULONG_MAX;
520 if (MyClass && !HasPrivPermission("users/flood/increased-buffers"))
521 sendqmax = MyClass->GetSendqSoftMax();
522 int penaltymax = MyClass->GetPenaltyThreshold();
523 if (penaltymax == 0 || HasPrivPermission("users/flood/no-fakelag"))
524 penaltymax = INT_MAX;
526 while (Penalty < penaltymax && getSendQSize() < sendqmax)
529 line.reserve(MAXBUF);
530 std::string::size_type qpos = 0;
531 while (qpos < recvq.length())
533 char c = recvq[qpos++];
544 if (line.length() < MAXBUF - 2)
547 // if we got here, the recvq ran out before we found a newline
550 // just found a newline. Terminate the string, and pull it out of recvq
551 recvq = recvq.substr(qpos);
553 // TODO should this be moved to when it was inserted in recvq?
554 ServerInstance->stats->statsRecv += qpos;
555 this->bytes_in += qpos;
558 ServerInstance->Parser->ProcessBuffer(line, this);
562 // Add pseudo-penalty so that we continue processing after sendq recedes
563 if (Penalty == 0 && getSendQSize() >= sendqmax)
567 void LocalUser::AddWriteBuf(const std::string &data)
569 if (!quitting && MyClass && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
572 * Quit the user FIRST, because otherwise we could recurse
573 * here and hit the same limit.
575 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
576 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
577 nick.c_str(), MyClass->GetSendqHardMax());
581 // We still want to append data to the sendq of a quitting user,
582 // e.g. their ERROR message that says 'closing link'
587 void User::OnError(BufferedSocketError)
589 ServerInstance->Users->QuitUser(this, getError());
592 CullResult User::cull()
595 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
598 ServerInstance->Logs->Log("USERS", DEBUG, "User culled twice? UUID empty");
599 return Extensible::cull();
601 PurgeEmptyChannels();
602 if (IS_LOCAL(this) && fd != INT_MAX)
605 if (this->AllowedOperCommands)
607 delete AllowedOperCommands;
608 AllowedOperCommands = NULL;
611 if (this->AllowedPrivs)
617 this->InvalidateCache();
618 this->DecrementModes();
620 ServerInstance->Users->uuidlist->erase(uuid);
622 return Extensible::cull();
625 CullResult LocalUser::cull()
627 std::vector<LocalUser*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
628 if (x != ServerInstance->Users->local_users.end())
629 ServerInstance->Users->local_users.erase(x);
631 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
633 if (client_sa.sa.sa_family != AF_UNSPEC)
634 ServerInstance->Users->RemoveCloneCounts(this);
638 void User::Oper(const std::string &opertype, const std::string &opername)
640 if (this->IsModeSet('o'))
643 this->modes[UM_OPERATOR] = 1;
644 this->WriteServ("MODE %s :+o", this->nick.c_str());
645 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
647 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());
648 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()));
650 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());
651 this->oper.assign(opertype, 0, 512);
652 ServerInstance->Users->all_opers.push_back(this);
655 * This might look like it's in the wrong place.
658 * 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.
661 TagIndex::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
662 if (iter_opertype != ServerInstance->Config->opertypes.end())
664 if (AllowedOperCommands)
665 AllowedOperCommands->clear();
667 AllowedOperCommands = new std::set<std::string>;
670 AllowedPrivs->clear();
672 AllowedPrivs = new std::set<std::string>;
674 AllowedUserModes.reset();
675 AllowedChanModes.reset();
676 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
678 std::string myclass, mycmd, mypriv;
679 irc::spacesepstream Classes(iter_opertype->second->getString("classes"));
680 while (Classes.GetToken(myclass))
682 TagIndex::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass.c_str());
683 if (iter_operclass != ServerInstance->Config->operclass.end())
685 /* Process commands */
686 irc::spacesepstream CommandList(iter_operclass->second->getString("commands"));
687 while (CommandList.GetToken(mycmd))
689 this->AllowedOperCommands->insert(mycmd);
692 irc::spacesepstream PrivList(iter_operclass->second->getString("privs"));
693 while (PrivList.GetToken(mypriv))
695 this->AllowedPrivs->insert(mypriv);
698 for (unsigned char* c = (unsigned char*)iter_operclass->second->getString("usermodes").c_str(); *c; ++c)
702 this->AllowedUserModes.set();
706 this->AllowedUserModes[*c - 'A'] = true;
710 for (unsigned char* c = (unsigned char*)iter_operclass->second->getString("chanmodes").c_str(); *c; ++c)
714 this->AllowedChanModes.set();
718 this->AllowedChanModes[*c - 'A'] = true;
725 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
733 * unset their oper type (what IS_OPER checks).
734 * note, order is important - this must come before modes as -o attempts
735 * to call UnOper. -- w00t
740 /* Remove all oper only modes from the user when the deoper - Bug #466*/
741 std::string moderemove("-");
743 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
745 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
746 if (mh && mh->NeedsOper())
747 moderemove += letter;
751 std::vector<std::string> parameters;
752 parameters.push_back(this->nick);
753 parameters.push_back(moderemove);
755 ServerInstance->Parser->CallHandler("MODE", parameters, this);
757 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
758 ServerInstance->Users->all_opers.remove(this);
760 if (AllowedOperCommands)
762 delete AllowedOperCommands;
763 AllowedOperCommands = NULL;
772 AllowedUserModes.reset();
773 AllowedChanModes.reset();
774 this->modes[UM_OPERATOR] = 0;
778 /* adds or updates an entry in the whowas list */
779 void User::AddToWhoWas()
781 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
784 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
791 * Check class restrictions
793 void User::CheckClass()
795 ConnectClass* a = this->MyClass;
797 if ((!a) || (a->type == CC_DENY))
799 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
802 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
804 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
805 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
808 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
810 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
811 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
815 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
818 bool User::CheckLines(bool doZline)
820 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
824 for (int n = 0; check[n]; ++n)
826 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
839 void LocalUser::FullConnect()
841 ServerInstance->stats->statsConnects++;
842 this->idle_lastmsg = ServerInstance->Time();
845 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
846 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
847 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
848 * Don't remove this! -- w00t
852 /* Check the password, if one is required by the user's connect class.
853 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
855 if (MyClass && !MyClass->pass.empty())
857 if (ServerInstance->PassCompare(this, MyClass->pass.c_str(), password.c_str(), MyClass->hash.c_str()))
859 ServerInstance->Users->QuitUser(this, "Invalid password");
864 if (this->CheckLines())
867 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
868 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());
869 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
870 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
871 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());
873 ServerInstance->Config->Send005(this);
874 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
880 if (ServerInstance->Users->unregistered_count)
881 ServerInstance->Users->unregistered_count--;
883 /* Trigger LUSERS output, give modules a chance too */
884 ModResult MOD_RESULT;
885 std::string command("LUSERS");
886 std::vector<std::string> parameters;
887 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
889 ServerInstance->CallCommandHandler(command, parameters, this);
892 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
893 * for a user that doesn't exist yet.
895 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
897 this->registered = REG_ALL;
899 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
901 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
902 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
903 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
904 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
907 /** User::UpdateNick()
908 * re-allocates a nick in the user_hash after they change nicknames,
909 * returns a pointer to the new user as it may have moved
911 User* User::UpdateNickHash(const char* New)
913 //user_hash::iterator newnick;
914 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
916 if (!irc::string(this->nick.c_str()).compare(New))
917 return oldnick->second;
919 if (oldnick == ServerInstance->Users->clientlist->end())
920 return NULL; /* doesnt exist */
922 User* olduser = oldnick->second;
923 ServerInstance->Users->clientlist->erase(oldnick);
924 (*(ServerInstance->Users->clientlist))[New] = olduser;
928 void User::InvalidateCache()
930 /* Invalidate cache */
931 cached_fullhost.clear();
932 cached_hostip.clear();
933 cached_makehost.clear();
934 cached_fullrealhost.clear();
937 bool User::ForceNickChange(const char* newnick)
939 ModResult MOD_RESULT;
941 this->InvalidateCache();
943 ServerInstance->NICKForced.set(this, 1);
944 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
945 ServerInstance->NICKForced.set(this, 0);
947 if (MOD_RESULT == MOD_RES_DENY)
949 ServerInstance->stats->statsCollisions++;
953 std::deque<classbase*> dummy;
954 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
955 if (nickhandler) // wtfbbq, when would this not be here
957 std::vector<std::string> parameters;
958 parameters.push_back(newnick);
959 ServerInstance->NICKForced.set(this, 1);
960 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
961 ServerInstance->NICKForced.set(this, 0);
965 // Unreachable, we hope
969 int LocalUser::GetServerPort()
971 switch (this->server_sa.sa.sa_family)
974 return htons(this->server_sa.in6.sin6_port);
976 return htons(this->server_sa.in4.sin_port);
981 const char* User::GetCIDRMask(int range)
986 throw "Negative range, sorry, no.";
989 * Original code written by Oliver Lupton (Om).
990 * Integrated by me. Thanks. :) -- w00t
992 switch (this->client_sa.sa.sa_family)
996 /* unsigned char s6_addr[16]; */
998 int i, bytestozero, extrabits;
1002 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
1004 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1005 * to zero. This means the last (128 - range) bits of the address must be set to zero.
1006 * Hence this number divided by 8 is the number of whole bytes from the end of the address
1007 * which must be set to zero.
1009 bytestozero = (128 - range) / 8;
1011 /* Some of the least significant bits of the next most significant byte may also have to
1012 * be zeroed. The number of bits is the remainder of the above division.
1014 extrabits = (128 - range) % 8;
1016 /* Populate our working struct with the parts of the user's IP which are required in the
1017 * final CIDR mask. Set all the subsequent bytes to zero.
1018 * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
1020 for(i = 0; i < (16 - bytestozero); i++)
1022 v6.s6_addr[i] = client_sa.in6.sin6_addr.s6_addr[i];
1025 /* And zero all the remaining bytes in the IP. */
1031 /* And finally, zero the extra bits required. */
1032 v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1034 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1044 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1046 /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1047 v4.s_addr = client_sa.in4.sin_addr.s_addr;
1049 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1050 * to zero. This means the last (32 - range) bits of the address must be set to zero.
1051 * This is done by shifting the value right and then back left by (32 - range) bits.
1055 v4.s_addr = ntohl(v4.s_addr);
1056 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1057 v4.s_addr = htonl(v4.s_addr);
1061 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1062 * this has undefined behaviour, but for CIDR purposes the resulting mask
1063 * from a.b.c.d/0 is 0.0.0.0/0
1068 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1074 return ""; // unused, but oh well
1077 const char* User::GetIPString()
1080 if (cachedip.empty())
1082 irc::sockets::satoap(&client_sa, cachedip, port);
1083 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1084 if (cachedip.c_str()[0] == ':')
1085 cachedip.insert(0,1,'0');
1088 return cachedip.c_str();
1091 bool User::SetClientIP(const char* sip)
1093 this->cachedip = "";
1094 return irc::sockets::aptosa(sip, 0, &client_sa);
1097 static std::string wide_newline("\r\n");
1099 void User::Write(const std::string& text)
1103 void User::Write(const char *text, ...)
1107 void LocalUser::Write(const std::string& text)
1109 if (!ServerInstance->SE->BoundsCheckFd(this))
1112 if (text.length() > MAXBUF - 2)
1114 // this should happen rarely or never. Crop the string at 512 and try again.
1115 std::string try_again = text.substr(0, MAXBUF - 2);
1120 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1122 this->AddWriteBuf(text);
1123 this->AddWriteBuf(wide_newline);
1125 ServerInstance->stats->statsSent += text.length() + 2;
1126 this->bytes_out += text.length() + 2;
1132 void LocalUser::Write(const char *text, ...)
1135 char textbuffer[MAXBUF];
1137 va_start(argsPtr, text);
1138 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1141 this->Write(std::string(textbuffer));
1144 void User::WriteServ(const std::string& text)
1146 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1150 * Same as Write(), except `text' is prefixed with `:server.name '.
1152 void User::WriteServ(const char* text, ...)
1155 char textbuffer[MAXBUF];
1157 va_start(argsPtr, text);
1158 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1161 this->WriteServ(std::string(textbuffer));
1165 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1168 char textbuffer[MAXBUF];
1170 va_start(argsPtr, text);
1171 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1174 this->WriteNumeric(numeric, std::string(textbuffer));
1177 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1179 char textbuffer[MAXBUF];
1180 ModResult MOD_RESULT;
1182 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1184 if (MOD_RESULT == MOD_RES_DENY)
1187 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1188 this->Write(std::string(textbuffer));
1191 void User::WriteFrom(User *user, const std::string &text)
1195 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1197 this->Write(std::string(tb));
1201 /* write text from an originating user to originating user */
1203 void User::WriteFrom(User *user, const char* text, ...)
1206 char textbuffer[MAXBUF];
1208 va_start(argsPtr, text);
1209 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1212 this->WriteFrom(user, std::string(textbuffer));
1216 /* write text to an destination user from a source user (e.g. user privmsg) */
1218 void User::WriteTo(User *dest, const char *data, ...)
1220 char textbuffer[MAXBUF];
1223 va_start(argsPtr, data);
1224 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1227 this->WriteTo(dest, std::string(textbuffer));
1230 void User::WriteTo(User *dest, const std::string &data)
1232 dest->WriteFrom(this, data);
1235 void User::WriteCommon(const char* text, ...)
1237 char textbuffer[MAXBUF];
1240 if (this->registered != REG_ALL || quitting)
1243 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1245 va_start(argsPtr, text);
1246 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1249 this->WriteCommonRaw(std::string(textbuffer), true);
1252 void User::WriteCommonExcept(const char* text, ...)
1254 char textbuffer[MAXBUF];
1257 if (this->registered != REG_ALL || quitting)
1260 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1262 va_start(argsPtr, text);
1263 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1266 this->WriteCommonRaw(std::string(textbuffer), false);
1269 void User::WriteCommonRaw(const std::string &line, bool include_self)
1271 if (this->registered != REG_ALL || quitting)
1274 uniq_id_t uniq_id = ++already_sent;
1276 UserChanList include_c(chans);
1277 std::map<User*,bool> exceptions;
1279 exceptions[this] = include_self;
1281 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1283 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1286 if (IS_LOCAL(u) && !u->quitting)
1288 already_sent[u->fd] = uniq_id;
1293 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1296 const UserMembList* ulist = c->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;
1309 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1314 if (this->registered != REG_ALL)
1317 uniq_id_t uniq_id = ++already_sent;
1319 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1320 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1321 std::string out1 = tb1;
1322 std::string out2 = tb2;
1324 UserChanList include_c(chans);
1325 std::map<User*,bool> exceptions;
1327 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1329 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1332 if (IS_LOCAL(u) && !u->quitting)
1334 already_sent[u->fd] = uniq_id;
1336 u->Write(IS_OPER(u) ? out2 : out1);
1339 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1341 const UserMembList* ulist = (*v)->GetUsers();
1342 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1345 if (IS_LOCAL(u) && !u->quitting && (already_sent[u->fd] != uniq_id))
1347 already_sent[u->fd] = uniq_id;
1348 u->Write(IS_OPER(u) ? out2 : out1);
1354 void LocalUser::SendText(const std::string& line)
1359 void RemoteUser::SendText(const std::string& line)
1361 ServerInstance->PI->PushToClient(this, line);
1364 void FakeUser::SendText(const std::string& line)
1368 void User::SendText(const char *text, ...)
1373 va_start(argsPtr, text);
1374 vsnprintf(line, MAXBUF, text, argsPtr);
1377 SendText(std::string(line));
1380 void User::SendText(const std::string &LinePrefix, std::stringstream &TextStream)
1383 int start_pos = LinePrefix.length();
1384 int pos = start_pos;
1385 memcpy(line, LinePrefix.data(), pos);
1387 while (TextStream >> Word)
1389 int len = Word.length();
1390 if (pos + len + 12 > MAXBUF)
1393 SendText(std::string(line));
1397 memcpy(line + pos + 1, Word.data(), len);
1401 SendText(std::string(line));
1404 /* return 0 or 1 depending if users u and u2 share one or more common channels
1405 * (used by QUIT, NICK etc which arent channel specific notices)
1407 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1408 * the first users channels then the second users channels within the outer loop,
1409 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1410 * all possible iterations). However this new function instead checks against the
1411 * channel's userlist in the inner loop which is a std::map<User*,User*>
1412 * and saves us time as we already know what pointer value we are after.
1413 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1414 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1416 bool User::SharesChannelWith(User *other)
1418 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1422 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1424 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1425 * by replacing it with a map::find which *should* be more efficient
1427 if ((*i)->HasUser(other))
1433 bool User::ChangeName(const char* gecos)
1435 if (!this->fullname.compare(gecos))
1440 ModResult MOD_RESULT;
1441 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (this,gecos));
1442 if (MOD_RESULT == MOD_RES_DENY)
1444 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1446 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1451 void User::DoHostCycle(const std::string &quitline)
1453 char buffer[MAXBUF];
1455 if (!ServerInstance->Config->CycleHosts)
1458 uniq_id_t silent_id = ++already_sent;
1459 uniq_id_t seen_id = ++already_sent;
1461 UserChanList include_c(chans);
1462 std::map<User*,bool> exceptions;
1464 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1466 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1469 if (IS_LOCAL(u) && !u->quitting)
1473 already_sent[u->fd] = seen_id;
1478 already_sent[u->fd] = silent_id;
1482 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1485 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1486 std::string joinline(buffer);
1487 std::string modeline = ServerInstance->Modes->ModeString(this, c);
1488 if (modeline.length() > 0)
1490 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1494 const UserMembList *ulist = c->GetUsers();
1495 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1498 if (u == this || !IS_LOCAL(u))
1500 if (already_sent[u->fd] == silent_id)
1503 if (already_sent[u->fd] != seen_id)
1506 already_sent[i->first->fd] = seen_id;
1509 if (modeline.length() > 0)
1515 bool User::ChangeDisplayedHost(const char* shost)
1522 ModResult MOD_RESULT;
1523 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (this,shost));
1524 if (MOD_RESULT == MOD_RES_DENY)
1528 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1530 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1532 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1533 this->dhost.assign(shost, 0, 64);
1535 this->InvalidateCache();
1537 this->DoHostCycle(quitstr);
1540 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1545 bool User::ChangeIdent(const char* newident)
1547 if (this->ident == newident)
1550 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1552 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1554 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1556 this->InvalidateCache();
1558 this->DoHostCycle(quitstr);
1563 void User::SendAll(const char* command, const char* text, ...)
1565 char textbuffer[MAXBUF];
1566 char formatbuffer[MAXBUF];
1569 va_start(argsPtr, text);
1570 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1573 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1574 std::string fmt = formatbuffer;
1576 for (std::vector<LocalUser*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1583 std::string User::ChannelList(User* source, bool spy)
1587 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1590 /* If the target is the sender, neither +p nor +s is set, or
1591 * the channel contains the user, it is not a spy channel
1593 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1594 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1600 void User::SplitChanList(User* dest, const std::string &cl)
1603 std::ostringstream prefix;
1604 std::string::size_type start, pos, length;
1606 prefix << this->nick << " " << dest->nick << " :";
1607 line = prefix.str();
1608 int namelen = ServerInstance->Config->ServerName.length() + 6;
1610 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1612 length = (pos == std::string::npos) ? cl.length() : pos;
1614 if (line.length() + namelen + length - start > 510)
1616 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1617 line = prefix.str();
1620 if(pos == std::string::npos)
1622 line.append(cl.substr(start, length - start));
1627 line.append(cl.substr(start, length - start + 1));
1633 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1638 * Sets a user's connection class.
1639 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1640 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1641 * then their ip will be taken as 'priority' anyway, so for example,
1642 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1644 ConnectClass* LocalUser::SetClass(const std::string &explicit_name)
1646 ConnectClass *found = NULL;
1648 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1650 if (!explicit_name.empty())
1652 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1654 ConnectClass* c = *i;
1656 if (explicit_name == c->name)
1658 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1665 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1667 ConnectClass* c = *i;
1669 if (c->type == CC_ALLOW)
1671 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1675 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1678 /* check if host matches.. */
1679 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1680 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1682 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1687 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1688 * because we should attempt to find another class if this one doesn't match us. -- w00t
1690 if (c->limit && (c->GetReferenceCount() >= c->limit))
1692 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1696 /* if it requires a port ... */
1699 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1701 /* and our port doesn't match, fail. */
1702 if (this->GetServerPort() != c->GetPort())
1704 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1709 /* we stop at the first class that meets ALL critera. */
1716 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1723 return this->MyClass;
1726 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1727 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1728 * then their ip will be taken as 'priority' anyway, so for example,
1729 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1731 ConnectClass* User::GetClass()
1733 return this->MyClass;
1736 void User::PurgeEmptyChannels()
1738 // firstly decrement the count on each channel
1739 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1748 void User::ShowMOTD()
1750 if (!ServerInstance->Config->MOTD.size())
1752 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1755 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1757 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1758 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1760 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1763 void User::ShowRULES()
1765 if (!ServerInstance->Config->RULES.size())
1767 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1771 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1773 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1774 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1776 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1779 void User::IncreasePenalty(int increase)
1781 this->Penalty += increase;
1784 void FakeUser::SetFakeServer(std::string name)
1787 this->server = name;
1790 const std::string FakeUser::GetFullHost()
1792 if (!ServerInstance->Config->HideWhoisServer.empty())
1793 return ServerInstance->Config->HideWhoisServer;
1797 const std::string FakeUser::GetFullRealHost()
1799 if (!ServerInstance->Config->HideWhoisServer.empty())
1800 return ServerInstance->Config->HideWhoisServer;
1804 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1805 : config(tag), type(t), name("unnamed"), registration_timeout(0), host(mask),
1806 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1807 recvqmax(0), penaltythreshold(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1811 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1812 : config(tag), type(t), name("unnamed"),
1813 registration_timeout(parent.registration_timeout), host(mask),
1814 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1815 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1816 recvqmax(parent.recvqmax), penaltythreshold(parent.penaltythreshold), maxlocal(parent.maxlocal),
1817 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1818 port(parent.port), limit(parent.limit)
1822 void ConnectClass::Update(const ConnectClass* src)
1825 registration_timeout = src->registration_timeout;
1827 pingtime = src->pingtime;
1830 softsendqmax = src->softsendqmax;
1831 hardsendqmax = src->hardsendqmax;
1832 recvqmax = src->recvqmax;
1833 penaltythreshold = src->penaltythreshold;
1834 maxlocal = src->maxlocal;
1835 maxglobal = src->maxglobal;