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 LocalIntExt User::NICKForced("NICKForced", NULL);
28 LocalStringExt User::OperQuit("OperQuit", NULL);
30 void InitializeAlreadySent(SocketEngine* SE)
32 already_sent = new unsigned long[SE->GetMaxFds()];
33 memset(already_sent, 0, SE->GetMaxFds() * sizeof(unsigned long));
36 std::string User::ProcessNoticeMasks(const char *sm)
38 bool adding = true, oldadding = false;
53 for (unsigned char d = 'A'; d <= 'z'; d++)
55 if (ServerInstance->SNO->IsEnabled(d))
57 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
59 if ((oldadding != adding) || (!output.length()))
60 output += (adding ? '+' : '-');
62 this->SetNoticeMask(d, adding);
71 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
73 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
75 if ((oldadding != adding) || (!output.length()))
76 output += (adding ? '+' : '-');
78 this->SetNoticeMask(*c, adding);
84 this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
93 std::string s = this->FormatNoticeMasks();
96 this->modes[UM_SNOMASK] = false;
102 void User::StartDNSLookup()
107 const char* sip = this->GetIPString();
108 UserResolver *res_reverse;
110 QueryType resolvtype = this->client_sa.sa.sa_family == AF_INET6 ? DNS_QUERY_PTR6 : DNS_QUERY_PTR4;
111 res_reverse = new UserResolver(this, sip, resolvtype, cached);
113 ServerInstance->AddResolver(res_reverse, cached);
115 catch (CoreException& e)
117 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
121 bool User::IsNoticeMaskSet(unsigned char sm)
125 return (snomasks[sm-65]);
128 void User::SetNoticeMask(unsigned char sm, bool value)
132 snomasks[sm-65] = value;
135 const char* User::FormatNoticeMasks()
137 static char data[MAXBUF];
140 for (int n = 0; n < 64; n++)
143 data[offset++] = n+65;
150 bool User::IsModeSet(unsigned char m)
154 return (modes[m-65]);
157 void User::SetMode(unsigned char m, bool value)
164 const char* User::FormatModes(bool showparameters)
166 static char data[MAXBUF];
170 for (unsigned char n = 0; n < 64; n++)
174 data[offset++] = n + 65;
175 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
176 if (showparameters && mh && mh->GetNumParams(true))
178 std::string p = mh->GetUserParameter(this);
180 params.append(" ").append(p);
185 strlcat(data, params.c_str(), MAXBUF);
189 void User::DecrementModes()
191 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
192 for (unsigned char n = 'A'; n <= 'z'; n++)
196 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
197 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
200 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
207 User::User(const std::string &uid)
209 server = ServerInstance->Config->ServerName;
210 age = ServerInstance->Time();
212 lastping = signon = idle_lastmsg = nping = registered = 0;
213 bytes_in = bytes_out = cmds_in = cmds_out = 0;
214 quietquit = quitting = exempt = haspassed = dns_done = false;
216 server_sa.sa.sa_family = AF_UNSPEC;
217 client_sa.sa.sa_family = AF_UNSPEC;
219 AllowedPrivs = AllowedOperCommands = NULL;
222 uuid.assign(ServerInstance->GetUID(), 0, UUID_LENGTH - 1);
224 uuid.assign(uid, 0, UUID_LENGTH - 1);
226 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid.c_str(), uid.empty() ? "allocated new" : "used remote");
228 user_hash::iterator finduuid = ServerInstance->Users->uuidlist->find(uuid);
229 if (finduuid == ServerInstance->Users->uuidlist->end())
230 (*ServerInstance->Users->uuidlist)[uuid] = this;
232 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
238 ServerInstance->Logs->Log("USERS", ERROR, "User destructor for %s called without cull", uuid.c_str());
241 const std::string& User::MakeHost()
243 if (!this->cached_makehost.empty())
244 return this->cached_makehost;
247 /* This is much faster than snprintf */
249 for(const char* n = ident.c_str(); *n; n++)
252 for(const char* n = host.c_str(); *n; n++)
256 this->cached_makehost.assign(nhost);
258 return this->cached_makehost;
261 const std::string& User::MakeHostIP()
263 if (!this->cached_hostip.empty())
264 return this->cached_hostip;
267 /* This is much faster than snprintf */
269 for(const char* n = ident.c_str(); *n; n++)
272 for(const char* n = this->GetIPString(); *n; n++)
276 this->cached_hostip = ihost;
278 return this->cached_hostip;
281 const std::string User::GetFullHost()
283 if (!this->cached_fullhost.empty())
284 return this->cached_fullhost;
288 for(const char* n = nick.c_str(); *n; n++)
291 for(const char* n = ident.c_str(); *n; n++)
294 for(const char* n = dhost.c_str(); *n; n++)
298 this->cached_fullhost = result;
300 return this->cached_fullhost;
303 char* User::MakeWildHost()
305 static char nresult[MAXBUF];
307 *t++ = '*'; *t++ = '!';
308 *t++ = '*'; *t++ = '@';
309 for(const char* n = dhost.c_str(); *n; n++)
315 const std::string User::GetFullRealHost()
317 if (!this->cached_fullrealhost.empty())
318 return this->cached_fullrealhost;
320 char fresult[MAXBUF];
322 for(const char* n = nick.c_str(); *n; n++)
325 for(const char* n = ident.c_str(); *n; n++)
328 for(const char* n = host.c_str(); *n; n++)
332 this->cached_fullrealhost = fresult;
334 return this->cached_fullrealhost;
337 bool User::IsInvited(const irc::string &channel)
339 time_t now = ServerInstance->Time();
340 InvitedList::iterator safei;
341 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
343 if (channel == i->first)
345 if (i->second != 0 && now > i->second)
347 /* Expired invite, remove it. */
350 invites.erase(safei);
359 InvitedList* User::GetInviteList()
361 time_t now = ServerInstance->Time();
362 /* Weed out expired invites here. */
363 InvitedList::iterator safei;
364 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
366 if (i->second != 0 && now > i->second)
368 /* Expired invite, remove it. */
371 invites.erase(safei);
377 void User::InviteTo(const irc::string &channel, time_t invtimeout)
379 time_t now = ServerInstance->Time();
380 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
381 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
383 if (channel == i->first)
385 if (i->second != 0 && invtimeout > i->second)
387 i->second = invtimeout;
393 invites.push_back(std::make_pair(channel, invtimeout));
396 void User::RemoveInvite(const irc::string &channel)
398 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
400 if (channel == i->first)
408 bool User::HasModePermission(unsigned char mode, ModeType type)
416 if (mode < 'A' || mode > ('A' + 64)) return false;
418 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
422 bool User::HasPermission(const std::string &command)
425 * users on remote servers can completely bypass all permissions based checks.
426 * This prevents desyncs when one server has different type/class tags to another.
427 * That having been said, this does open things up to the possibility of source changes
428 * allowing remote kills, etc - but if they have access to the src, they most likely have
429 * access to the conf - so it's an end to a means either way.
434 // are they even an oper at all?
440 if (!AllowedOperCommands)
443 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
445 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
452 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
456 ServerInstance->Logs->Log("PRIVS", DEBUG, "Remote (yes)");
463 this->WriteServ("NOTICE %s :You are not an oper", this->nick.c_str());
470 this->WriteServ("NOTICE %s :Privset empty(!?)", this->nick.c_str());
474 if (AllowedPrivs->find(privstr) != AllowedPrivs->end())
478 else if (AllowedPrivs->find("*") != AllowedPrivs->end())
484 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());
488 void User::OnDataReady()
493 if (MyClass && recvq.length() > MyClass->GetRecvqMax() && !HasPrivPermission("users/flood/increased-buffers"))
495 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
496 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
497 nick.c_str(), (unsigned long)recvq.length(), MyClass->GetRecvqMax());
499 unsigned long sendqmax = ULONG_MAX;
500 if (MyClass && !HasPrivPermission("users/flood/increased-buffers"))
501 sendqmax = MyClass->GetSendqSoftMax();
503 while (Penalty < 10 && getSendQSize() < sendqmax)
506 line.reserve(MAXBUF);
507 std::string::size_type qpos = 0;
508 while (qpos < recvq.length())
510 char c = recvq[qpos++];
521 if (line.length() < MAXBUF - 2)
524 // if we got here, the recvq ran out before we found a newline
527 // just found a newline. Terminate the string, and pull it out of recvq
528 recvq = recvq.substr(qpos);
530 // TODO should this be moved to when it was inserted in recvq?
531 ServerInstance->stats->statsRecv += qpos;
532 this->bytes_in += qpos;
535 ServerInstance->Parser->ProcessBuffer(line, this);
537 // Add pseudo-penalty so that we continue processing after sendq recedes
538 if (Penalty == 0 && getSendQSize() >= sendqmax)
542 void User::AddWriteBuf(const std::string &data)
544 // Don't bother sending text to remote users!
547 if (!quitting && MyClass && getSendQSize() + data.length() > MyClass->GetSendqHardMax() && !HasPrivPermission("users/flood/increased-buffers"))
550 * Quit the user FIRST, because otherwise we could recurse
551 * here and hit the same limit.
553 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
554 ServerInstance->SNO->WriteToSnoMask('a', "User %s SendQ exceeds connect class maximum of %lu",
555 nick.c_str(), MyClass->GetSendqHardMax());
559 // We still want to append data to the sendq of a quitting user,
560 // e.g. their ERROR message that says 'closing link'
565 void User::OnError(BufferedSocketError)
567 ServerInstance->Users->QuitUser(this, getError());
573 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
576 ServerInstance->Logs->Log("USERS", DEBUG, "User culled twice? UUID empty");
579 PurgeEmptyChannels();
585 std::vector<User*>::iterator x = find(ServerInstance->Users->local_users.begin(),ServerInstance->Users->local_users.end(),this);
586 if (x != ServerInstance->Users->local_users.end())
587 ServerInstance->Users->local_users.erase(x);
589 ServerInstance->Logs->Log("USERS", DEBUG, "Failed to remove user from vector");
592 if (this->AllowedOperCommands)
594 delete AllowedOperCommands;
595 AllowedOperCommands = NULL;
598 if (this->AllowedPrivs)
604 this->InvalidateCache();
605 this->DecrementModes();
607 if (client_sa.sa.sa_family != AF_UNSPEC)
608 ServerInstance->Users->RemoveCloneCounts(this);
610 ServerInstance->Users->uuidlist->erase(uuid);
615 void User::Oper(const std::string &opertype, const std::string &opername)
617 if (this->IsModeSet('o'))
620 this->modes[UM_OPERATOR] = 1;
621 this->WriteServ("MODE %s :+o", this->nick.c_str());
622 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
624 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());
625 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()));
627 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());
628 this->oper.assign(opertype, 0, 512);
629 ServerInstance->Users->all_opers.push_back(this);
632 * This might look like it's in the wrong place.
635 * 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.
638 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
639 if (iter_opertype != ServerInstance->Config->opertypes.end())
641 if (AllowedOperCommands)
642 AllowedOperCommands->clear();
644 AllowedOperCommands = new std::set<std::string>;
647 AllowedPrivs->clear();
649 AllowedPrivs = new std::set<std::string>;
651 AllowedUserModes.reset();
652 AllowedChanModes.reset();
653 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
655 std::string myclass, mycmd, mypriv;
656 irc::spacesepstream Classes(iter_opertype->second.c_str());
657 while (Classes.GetToken(myclass))
659 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass.c_str());
660 if (iter_operclass != ServerInstance->Config->operclass.end())
662 /* Process commands */
663 irc::spacesepstream CommandList(iter_operclass->second.commandlist);
664 while (CommandList.GetToken(mycmd))
666 this->AllowedOperCommands->insert(mycmd);
669 irc::spacesepstream PrivList(iter_operclass->second.privs);
670 while (PrivList.GetToken(mypriv))
672 this->AllowedPrivs->insert(mypriv);
675 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist.c_str(); *c; ++c)
679 this->AllowedUserModes.set();
683 this->AllowedUserModes[*c - 'A'] = true;
687 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist.c_str(); *c; ++c)
691 this->AllowedChanModes.set();
695 this->AllowedChanModes[*c - 'A'] = true;
702 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
710 * unset their oper type (what IS_OPER checks).
711 * note, order is important - this must come before modes as -o attempts
712 * to call UnOper. -- w00t
717 /* Remove all oper only modes from the user when the deoper - Bug #466*/
718 std::string moderemove("-");
720 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
722 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
723 if (mh && mh->NeedsOper())
724 moderemove += letter;
728 std::vector<std::string> parameters;
729 parameters.push_back(this->nick);
730 parameters.push_back(moderemove);
732 ServerInstance->Parser->CallHandler("MODE", parameters, this);
734 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
735 ServerInstance->Users->all_opers.remove(this);
737 if (AllowedOperCommands)
739 delete AllowedOperCommands;
740 AllowedOperCommands = NULL;
749 AllowedUserModes.reset();
750 AllowedChanModes.reset();
751 this->modes[UM_OPERATOR] = 0;
755 /* adds or updates an entry in the whowas list */
756 void User::AddToWhoWas()
758 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
761 WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_ADD);
768 * Check class restrictions
770 void User::CheckClass()
772 ConnectClass* a = this->MyClass;
774 if ((!a) || (a->type == CC_DENY))
776 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
779 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
781 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
782 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
785 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
787 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
788 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
792 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
795 bool User::CheckLines(bool doZline)
797 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
801 for (int n = 0; check[n]; ++n)
803 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
816 void User::FullConnect()
818 ServerInstance->stats->statsConnects++;
819 this->idle_lastmsg = ServerInstance->Time();
822 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
823 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
824 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
825 * Don't remove this! -- w00t
829 /* Check the password, if one is required by the user's connect class.
830 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
832 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
834 ServerInstance->Users->QuitUser(this, "Invalid password");
838 if (this->CheckLines())
841 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network.c_str());
842 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());
843 this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-2.0",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
844 this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
845 this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-2.0 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName.c_str(), ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
847 ServerInstance->Config->Send005(this);
848 this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
854 if (ServerInstance->Users->unregistered_count)
855 ServerInstance->Users->unregistered_count--;
857 /* Trigger LUSERS output, give modules a chance too */
858 ModResult MOD_RESULT;
859 std::string command("LUSERS");
860 std::vector<std::string> parameters;
861 FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (command, parameters, this, true, "LUSERS"));
863 ServerInstance->CallCommandHandler(command, parameters, this);
866 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
867 * for a user that doesn't exist yet.
869 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
871 this->registered = REG_ALL;
873 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
875 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]",
876 this->GetServerPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
877 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
878 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
881 /** User::UpdateNick()
882 * re-allocates a nick in the user_hash after they change nicknames,
883 * returns a pointer to the new user as it may have moved
885 User* User::UpdateNickHash(const char* New)
887 //user_hash::iterator newnick;
888 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
890 if (!irc::string(this->nick.c_str()).compare(New))
891 return oldnick->second;
893 if (oldnick == ServerInstance->Users->clientlist->end())
894 return NULL; /* doesnt exist */
896 User* olduser = oldnick->second;
897 ServerInstance->Users->clientlist->erase(oldnick);
898 (*(ServerInstance->Users->clientlist))[New] = olduser;
902 void User::InvalidateCache()
904 /* Invalidate cache */
905 cached_fullhost.clear();
906 cached_hostip.clear();
907 cached_makehost.clear();
908 cached_fullrealhost.clear();
911 bool User::ForceNickChange(const char* newnick)
913 ModResult MOD_RESULT;
915 this->InvalidateCache();
917 NICKForced.set(this, 1);
918 FIRST_MOD_RESULT(OnUserPreNick, MOD_RESULT, (this, newnick));
919 NICKForced.set(this, 0);
921 if (MOD_RESULT == MOD_RES_DENY)
923 ServerInstance->stats->statsCollisions++;
927 std::deque<classbase*> dummy;
928 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
929 if (nickhandler) // wtfbbq, when would this not be here
931 std::vector<std::string> parameters;
932 parameters.push_back(newnick);
933 NICKForced.set(this, 1);
934 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
935 NICKForced.set(this, 0);
939 // Unreachable, we hope
943 int User::GetServerPort()
945 switch (this->server_sa.sa.sa_family)
948 return htons(this->server_sa.in6.sin6_port);
950 return htons(this->server_sa.in4.sin_port);
955 const char* User::GetCIDRMask(int range)
960 throw "Negative range, sorry, no.";
963 * Original code written by Oliver Lupton (Om).
964 * Integrated by me. Thanks. :) -- w00t
966 switch (this->client_sa.sa.sa_family)
970 /* unsigned char s6_addr[16]; */
972 int i, bytestozero, extrabits;
976 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
978 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
979 * to zero. This means the last (128 - range) bits of the address must be set to zero.
980 * Hence this number divided by 8 is the number of whole bytes from the end of the address
981 * which must be set to zero.
983 bytestozero = (128 - range) / 8;
985 /* Some of the least significant bits of the next most significant byte may also have to
986 * be zeroed. The number of bits is the remainder of the above division.
988 extrabits = (128 - range) % 8;
990 /* Populate our working struct with the parts of the user's IP which are required in the
991 * final CIDR mask. Set all the subsequent bytes to zero.
992 * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
994 for(i = 0; i < (16 - bytestozero); i++)
996 v6.s6_addr[i] = client_sa.in6.sin6_addr.s6_addr[i];
999 /* And zero all the remaining bytes in the IP. */
1005 /* And finally, zero the extra bits required. */
1006 v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1008 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1018 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1020 /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1021 v4.s_addr = client_sa.in4.sin_addr.s_addr;
1023 /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1024 * to zero. This means the last (32 - range) bits of the address must be set to zero.
1025 * This is done by shifting the value right and then back left by (32 - range) bits.
1029 v4.s_addr = ntohl(v4.s_addr);
1030 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1031 v4.s_addr = htonl(v4.s_addr);
1035 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1036 * this has undefined behaviour, but for CIDR purposes the resulting mask
1037 * from a.b.c.d/0 is 0.0.0.0/0
1042 snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1048 return ""; // unused, but oh well
1051 const char* User::GetIPString()
1054 if (cachedip.empty())
1056 irc::sockets::satoap(&client_sa, cachedip, port);
1057 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1058 if (cachedip.c_str()[0] == ':')
1059 cachedip.insert(0,1,'0');
1062 return cachedip.c_str();
1065 bool User::SetClientIP(const char* sip)
1067 this->cachedip = "";
1068 return irc::sockets::aptosa(sip, 0, &client_sa);
1071 static std::string wide_newline("\r\n");
1073 void User::Write(const std::string& text)
1075 if (!ServerInstance->SE->BoundsCheckFd(this))
1078 if (text.length() > MAXBUF - 2)
1080 // this should happen rarely or never. Crop the string at 512 and try again.
1081 std::string try_again = text.substr(0, MAXBUF - 2);
1086 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1088 this->AddWriteBuf(text);
1089 this->AddWriteBuf(wide_newline);
1091 ServerInstance->stats->statsSent += text.length() + 2;
1092 this->bytes_out += text.length() + 2;
1098 void User::Write(const char *text, ...)
1101 char textbuffer[MAXBUF];
1103 va_start(argsPtr, text);
1104 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1107 this->Write(std::string(textbuffer));
1110 void User::WriteServ(const std::string& text)
1112 this->Write(":%s %s",ServerInstance->Config->ServerName.c_str(),text.c_str());
1116 * Same as Write(), except `text' is prefixed with `:server.name '.
1118 void User::WriteServ(const char* text, ...)
1121 char textbuffer[MAXBUF];
1123 va_start(argsPtr, text);
1124 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1127 this->WriteServ(std::string(textbuffer));
1131 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1134 char textbuffer[MAXBUF];
1136 va_start(argsPtr, text);
1137 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1140 this->WriteNumeric(numeric, std::string(textbuffer));
1143 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1145 char textbuffer[MAXBUF];
1146 ModResult MOD_RESULT;
1148 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric, text));
1150 if (MOD_RESULT == MOD_RES_DENY)
1153 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName.c_str(), numeric, text.c_str());
1154 this->Write(std::string(textbuffer));
1157 void User::WriteFrom(User *user, const std::string &text)
1161 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1163 this->Write(std::string(tb));
1167 /* write text from an originating user to originating user */
1169 void User::WriteFrom(User *user, const char* text, ...)
1172 char textbuffer[MAXBUF];
1174 va_start(argsPtr, text);
1175 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1178 this->WriteFrom(user, std::string(textbuffer));
1182 /* write text to an destination user from a source user (e.g. user privmsg) */
1184 void User::WriteTo(User *dest, const char *data, ...)
1186 char textbuffer[MAXBUF];
1189 va_start(argsPtr, data);
1190 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1193 this->WriteTo(dest, std::string(textbuffer));
1196 void User::WriteTo(User *dest, const std::string &data)
1198 dest->WriteFrom(this, data);
1201 void User::WriteCommon(const char* text, ...)
1203 char textbuffer[MAXBUF];
1206 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1209 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1211 va_start(argsPtr, text);
1212 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1215 this->WriteCommonRaw(std::string(textbuffer), true);
1218 void User::WriteCommonExcept(const char* text, ...)
1220 char textbuffer[MAXBUF];
1223 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1226 int len = snprintf(textbuffer,MAXBUF,":%s ",this->GetFullHost().c_str());
1228 va_start(argsPtr, text);
1229 vsnprintf(textbuffer + len, MAXBUF - len, text, argsPtr);
1232 this->WriteCommonRaw(std::string(textbuffer), false);
1235 void User::WriteCommonRaw(const std::string &line, bool include_self)
1237 if (this->registered != REG_ALL || !IS_LOCAL(this) || quitting)
1241 InitializeAlreadySent(ServerInstance->SE);
1244 UserChanList include_c(chans);
1245 std::map<User*,bool> exceptions;
1247 exceptions[this] = include_self;
1249 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1251 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1254 if (IS_LOCAL(u) && !u->quitting)
1256 already_sent[u->fd] = uniq_id;
1261 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1264 const UserMembList* ulist = c->GetUsers();
1265 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1268 if (IS_LOCAL(u) && !u->quitting && already_sent[u->fd] != uniq_id)
1270 already_sent[u->fd] = uniq_id;
1277 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1282 if (this->registered != REG_ALL)
1288 InitializeAlreadySent(ServerInstance->SE);
1290 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1291 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1292 std::string out1 = tb1;
1293 std::string out2 = tb2;
1295 UserChanList include_c(chans);
1296 std::map<User*,bool> exceptions;
1298 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1300 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1303 if (IS_LOCAL(u) && !u->quitting)
1305 already_sent[u->fd] = uniq_id;
1307 u->Write(IS_OPER(u) ? out2 : out1);
1310 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1312 const UserMembList* ulist = (*v)->GetUsers();
1313 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1316 if (IS_LOCAL(u) && !u->quitting && (already_sent[u->fd] != uniq_id))
1318 already_sent[u->fd] = uniq_id;
1319 u->Write(IS_OPER(u) ? out2 : out1);
1325 void User::WriteWallOps(const std::string &text)
1327 std::string wallop("WALLOPS :");
1328 wallop.append(text);
1330 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1333 if (t->IsModeSet('w'))
1334 this->WriteTo(t,wallop);
1338 void User::WriteWallOps(const char* text, ...)
1340 if (!IS_LOCAL(this))
1343 char textbuffer[MAXBUF];
1346 va_start(argsPtr, text);
1347 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1350 this->WriteWallOps(std::string(textbuffer));
1353 /* return 0 or 1 depending if users u and u2 share one or more common channels
1354 * (used by QUIT, NICK etc which arent channel specific notices)
1356 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1357 * the first users channels then the second users channels within the outer loop,
1358 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1359 * all possible iterations). However this new function instead checks against the
1360 * channel's userlist in the inner loop which is a std::map<User*,User*>
1361 * and saves us time as we already know what pointer value we are after.
1362 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1363 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1365 bool User::SharesChannelWith(User *other)
1367 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1371 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1373 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1374 * by replacing it with a map::find which *should* be more efficient
1376 if ((*i)->HasUser(other))
1382 bool User::ChangeName(const char* gecos)
1384 if (!this->fullname.compare(gecos))
1389 ModResult MOD_RESULT;
1390 FIRST_MOD_RESULT(OnChangeLocalUserGECOS, MOD_RESULT, (this,gecos));
1391 if (MOD_RESULT == MOD_RES_DENY)
1393 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1395 this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1400 void User::DoHostCycle(const std::string &quitline)
1402 char buffer[MAXBUF];
1404 if (!ServerInstance->Config->CycleHosts)
1410 InitializeAlreadySent(ServerInstance->SE);
1412 UserChanList include_c(chans);
1413 std::map<User*,bool> exceptions;
1415 FOREACH_MOD(I_OnBuildNeighborList,OnBuildNeighborList(this, include_c, exceptions));
1417 for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i)
1420 if (IS_LOCAL(u) && !u->quitting)
1422 already_sent[u->fd] = uniq_id;
1427 for (UCListIter v = include_c.begin(); v != include_c.end(); ++v)
1430 snprintf(buffer, MAXBUF, ":%s JOIN %s", GetFullHost().c_str(), c->name.c_str());
1431 std::string joinline(buffer);
1432 std::string modeline = ServerInstance->Modes->ModeString(this, c);
1433 if (modeline.length() > 0)
1435 snprintf(buffer, MAXBUF, ":%s MODE %s +%s", GetFullHost().c_str(), c->name.c_str(), modeline.c_str());
1439 const UserMembList *ulist = c->GetUsers();
1440 for (UserMembList::const_iterator i = ulist->begin(); i != ulist->end(); i++)
1443 if (u == this || !IS_LOCAL(u))
1446 if (already_sent[i->first->fd] != uniq_id)
1449 already_sent[i->first->fd] = uniq_id;
1452 if (modeline.length() > 0)
1458 bool User::ChangeDisplayedHost(const char* shost)
1465 ModResult MOD_RESULT;
1466 FIRST_MOD_RESULT(OnChangeLocalUserHost, MOD_RESULT, (this,shost));
1467 if (MOD_RESULT == MOD_RES_DENY)
1471 FOREACH_MOD(I_OnChangeHost, OnChangeHost(this,shost));
1473 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing host";
1475 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1476 this->dhost.assign(shost, 0, 64);
1478 this->InvalidateCache();
1480 this->DoHostCycle(quitstr);
1483 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1488 bool User::ChangeIdent(const char* newident)
1490 if (this->ident == newident)
1493 FOREACH_MOD(I_OnChangeIdent, OnChangeIdent(this,newident));
1495 std::string quitstr = ":" + GetFullHost() + " QUIT :Changing ident";
1497 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1499 this->InvalidateCache();
1501 this->DoHostCycle(quitstr);
1506 void User::SendAll(const char* command, const char* text, ...)
1508 char textbuffer[MAXBUF];
1509 char formatbuffer[MAXBUF];
1512 va_start(argsPtr, text);
1513 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1516 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1517 std::string fmt = formatbuffer;
1519 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1526 std::string User::ChannelList(User* source, bool spy)
1530 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1533 /* If the target is the sender, neither +p nor +s is set, or
1534 * the channel contains the user, it is not a spy channel
1536 if (spy != (source == this || !(c->IsModeSet('p') || c->IsModeSet('s')) || c->HasUser(source)))
1537 list.append(c->GetPrefixChar(this)).append(c->name).append(" ");
1543 void User::SplitChanList(User* dest, const std::string &cl)
1546 std::ostringstream prefix;
1547 std::string::size_type start, pos, length;
1549 prefix << this->nick << " " << dest->nick << " :";
1550 line = prefix.str();
1551 int namelen = ServerInstance->Config->ServerName.length() + 6;
1553 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1555 length = (pos == std::string::npos) ? cl.length() : pos;
1557 if (line.length() + namelen + length - start > 510)
1559 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1560 line = prefix.str();
1563 if(pos == std::string::npos)
1565 line.append(cl.substr(start, length - start));
1570 line.append(cl.substr(start, length - start + 1));
1576 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1581 * Sets a user's connection class.
1582 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1583 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1584 * then their ip will be taken as 'priority' anyway, so for example,
1585 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1587 ConnectClass* User::SetClass(const std::string &explicit_name)
1589 ConnectClass *found = NULL;
1591 if (!IS_LOCAL(this))
1594 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1596 if (!explicit_name.empty())
1598 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1600 ConnectClass* c = *i;
1602 if (explicit_name == c->name)
1604 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1611 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1613 ConnectClass* c = *i;
1615 if (c->type == CC_ALLOW)
1617 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->host.c_str(), c->GetPort(), c->GetName().c_str());
1621 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1624 /* check if host matches.. */
1625 if (c->GetHost().length() && !InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1626 !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1628 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1633 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1634 * because we should attempt to find another class if this one doesn't match us. -- w00t
1636 if (c->limit && (c->GetReferenceCount() >= c->limit))
1638 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1642 /* if it requires a port ... */
1645 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1647 /* and our port doesn't match, fail. */
1648 if (this->GetServerPort() != c->GetPort())
1650 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetServerPort());
1655 /* we stop at the first class that meets ALL critera. */
1662 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1669 return this->MyClass;
1672 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1673 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1674 * then their ip will be taken as 'priority' anyway, so for example,
1675 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1677 ConnectClass* User::GetClass()
1679 return this->MyClass;
1682 void User::PurgeEmptyChannels()
1684 std::vector<Channel*> to_delete;
1686 // firstly decrement the count on each channel
1687 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1690 c->RemoveAllPrefixes(this);
1691 if (c->DelUser(this) == 0)
1693 /* No users left in here, mark it for deletion */
1696 to_delete.push_back(c);
1700 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1705 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1707 Channel* thischan = *n;
1708 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1709 if (i2 != ServerInstance->chanlist->end())
1711 ModResult MOD_RESULT;
1712 FIRST_MOD_RESULT(OnChannelPreDelete, MOD_RESULT, (i2->second));
1713 if (MOD_RESULT == MOD_RES_DENY)
1714 continue; // delete halted by module
1715 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1717 ServerInstance->chanlist->erase(i2);
1718 this->chans.erase(*n);
1725 void User::ShowMOTD()
1727 if (!ServerInstance->Config->MOTD.size())
1729 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1732 this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName.c_str());
1734 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1735 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1737 this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1740 void User::ShowRULES()
1742 if (!ServerInstance->Config->RULES.size())
1744 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1748 this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName.c_str());
1750 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1751 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1753 this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1756 void User::IncreasePenalty(int increase)
1758 this->Penalty += increase;
1761 void User::DecreasePenalty(int decrease)
1763 this->Penalty -= decrease;
1766 void FakeUser::SetFakeServer(std::string name)
1769 this->server = name;
1772 const std::string FakeUser::GetFullHost()
1774 if (!ServerInstance->Config->HideWhoisServer.empty())
1775 return ServerInstance->Config->HideWhoisServer;
1779 const std::string FakeUser::GetFullRealHost()
1781 if (!ServerInstance->Config->HideWhoisServer.empty())
1782 return ServerInstance->Config->HideWhoisServer;
1786 ConnectClass::ConnectClass(char t, const std::string& mask)
1787 : type(t), name("unnamed"), registration_timeout(0), host(mask),
1788 pingtime(0), pass(""), hash(""), softsendqmax(0), hardsendqmax(0),
1789 recvqmax(0), maxlocal(0), maxglobal(0), maxchans(0), port(0), limit(0)
1793 ConnectClass::ConnectClass(char t, const std::string& mask, const ConnectClass& parent)
1794 : type(t), name("unnamed"),
1795 registration_timeout(parent.registration_timeout), host(mask),
1796 pingtime(parent.pingtime), pass(parent.pass), hash(parent.hash),
1797 softsendqmax(parent.softsendqmax), hardsendqmax(parent.hardsendqmax),
1798 recvqmax(parent.recvqmax), maxlocal(parent.maxlocal),
1799 maxglobal(parent.maxglobal), maxchans(parent.maxchans),
1800 port(parent.port), limit(parent.limit)
1804 void ConnectClass::Update(const ConnectClass* src)
1807 registration_timeout = src->registration_timeout;
1809 pingtime = src->pingtime;
1812 softsendqmax = src->softsendqmax;
1813 hardsendqmax = src->hardsendqmax;
1814 recvqmax = src->recvqmax;
1815 maxlocal = src->maxlocal;
1816 maxglobal = src->maxglobal;