1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDusers */
18 #include "socketengine.h"
22 #include "commands/cmd_whowas.h"
24 /* XXX: Used for speeding up WriteCommon operations */
25 unsigned long uniq_id = 1;
27 static unsigned long* already_sent = NULL;
30 void InitializeAlreadySent(SocketEngine* SE)
32 already_sent = new unsigned long[SE->GetMaxFds()];
33 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(501, "%s %c :is unknown snomask char to me", this->nick, *c);
97 void User::StartDNSLookup()
102 const char* sip = this->GetIPString(false);
104 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
105 if (!strncmp(sip, "0::ffff:", 8))
106 res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
108 res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
110 this->ServerInstance->AddResolver(res_reverse, cached);
112 catch (CoreException& e)
114 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
118 bool User::IsNoticeMaskSet(unsigned char sm)
120 return (snomasks[sm-65]);
123 void User::SetNoticeMask(unsigned char sm, bool value)
125 snomasks[sm-65] = value;
128 const char* User::FormatNoticeMasks()
130 static char data[MAXBUF];
133 for (int n = 0; n < 64; n++)
136 data[offset++] = n+65;
145 bool User::IsModeSet(unsigned char m)
147 return (modes[m-65]);
150 void User::SetMode(unsigned char m, bool value)
155 const char* User::FormatModes()
157 static char data[MAXBUF];
159 for (int n = 0; n < 64; n++)
162 data[offset++] = n+65;
168 void User::DecrementModes()
170 ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
171 for (unsigned char n = 'A'; n <= 'z'; n++)
175 ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
176 ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
179 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
186 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
188 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = *uuid = 0;
189 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
190 reset_due = ServerInstance->Time();
191 age = ServerInstance->Time();
193 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
194 ChannelCount = timeout = bytes_in = bytes_out = cmds_in = cmds_out = 0;
195 quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
200 res_forward = res_reverse = NULL;
205 AllowedUserModes = NULL;
206 AllowedChanModes = NULL;
207 AllowedOperCommands = NULL;
210 memset(modes,0,sizeof(modes));
211 memset(snomasks,0,sizeof(snomasks));
212 /* Invalidate cache */
213 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
216 strlcpy(uuid, Instance->GetUID().c_str(), UUID_LENGTH);
218 strlcpy(uuid, uid.c_str(), UUID_LENGTH);
220 ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid, uid.empty() ? "allocated new" : "used remote");
222 user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
223 if (finduuid == Instance->Users->uuidlist->end())
224 (*Instance->Users->uuidlist)[uuid] = this;
226 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
231 /* NULL for remote users :) */
234 this->MyClass->RefCount--;
235 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
237 if (this->AllowedOperCommands)
239 delete AllowedOperCommands;
240 AllowedOperCommands = NULL;
243 if (this->AllowedUserModes)
245 delete[] AllowedUserModes;
246 AllowedUserModes = NULL;
249 if (this->AllowedChanModes)
251 delete[] AllowedChanModes;
252 AllowedChanModes = NULL;
255 this->InvalidateCache();
256 this->DecrementModes();
260 ServerInstance->Users->RemoveCloneCounts(this);
262 if (this->GetProtocolFamily() == AF_INET)
264 delete (sockaddr_in*)ip;
266 #ifdef SUPPORT_IP6LINKS
269 delete (sockaddr_in6*)ip;
274 ServerInstance->Users->uuidlist->erase(uuid);
277 char* User::MakeHost()
279 if (this->cached_makehost)
280 return this->cached_makehost;
283 /* This is much faster than snprintf */
285 for(char* n = ident; *n; n++)
288 for(char* n = host; *n; n++)
292 this->cached_makehost = strdup(nhost);
294 return this->cached_makehost;
297 char* User::MakeHostIP()
299 if (this->cached_hostip)
300 return this->cached_hostip;
303 /* This is much faster than snprintf */
305 for(char* n = ident; *n; n++)
308 for(const char* n = this->GetIPString(); *n; n++)
312 this->cached_hostip = strdup(ihost);
314 return this->cached_hostip;
317 void User::CloseSocket()
321 ServerInstance->SE->Shutdown(this, 2);
322 ServerInstance->SE->Close(this);
326 char* User::GetFullHost()
328 if (this->cached_fullhost)
329 return this->cached_fullhost;
333 for(char* n = nick; *n; n++)
336 for(char* n = ident; *n; n++)
339 for(char* n = dhost; *n; n++)
343 this->cached_fullhost = strdup(result);
345 return this->cached_fullhost;
348 char* User::MakeWildHost()
350 static char nresult[MAXBUF];
352 *t++ = '*'; *t++ = '!';
353 *t++ = '*'; *t++ = '@';
354 for(char* n = dhost; *n; n++)
360 int User::ReadData(void* buffer, size_t size)
365 return read(this->fd, buffer, size);
367 return recv(this->fd, (char*)buffer, size, 0);
375 char* User::GetFullRealHost()
377 if (this->cached_fullrealhost)
378 return this->cached_fullrealhost;
380 char fresult[MAXBUF];
382 for(char* n = nick; *n; n++)
385 for(char* n = ident; *n; n++)
388 for(char* n = host; *n; n++)
392 this->cached_fullrealhost = strdup(fresult);
394 return this->cached_fullrealhost;
397 bool User::IsInvited(const irc::string &channel)
399 time_t now = time(NULL);
400 InvitedList::iterator safei;
401 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
403 if (channel == i->first)
405 if (i->second != 0 && now > i->second)
407 /* Expired invite, remove it. */
410 invites.erase(safei);
419 InvitedList* User::GetInviteList()
421 time_t now = time(NULL);
422 /* Weed out expired invites here. */
423 InvitedList::iterator safei;
424 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
426 if (i->second != 0 && now > i->second)
428 /* Expired invite, remove it. */
431 invites.erase(safei);
437 void User::InviteTo(const irc::string &channel, time_t invtimeout)
439 time_t now = time(NULL);
440 if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
441 for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
443 if (channel == i->first)
445 if (i->second != 0 && invtimeout > i->second)
447 i->second = invtimeout;
451 invites.push_back(std::make_pair(channel, invtimeout));
454 void User::RemoveInvite(const irc::string &channel)
456 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
458 if (channel == i->first)
466 bool User::HasModePermission(unsigned char mode, ModeType type)
474 if (!AllowedUserModes || !AllowedChanModes)
477 return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
481 bool User::HasPermission(const std::string &command)
484 * users on remote servers can completely bypass all permissions based checks.
485 * This prevents desyncs when one server has different type/class tags to another.
486 * That having been said, this does open things up to the possibility of source changes
487 * allowing remote kills, etc - but if they have access to the src, they most likely have
488 * access to the conf - so it's an end to a means either way.
493 // are they even an oper at all?
499 if (!AllowedOperCommands)
502 if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
504 else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
510 bool User::AddBuffer(const std::string &a)
512 std::string::size_type start = 0;
513 std::string::size_type i = a.find('\r');
516 * The old implementation here took a copy, and rfind() on \r, removing as it found them, before
517 * copying a second time onto the recvq. That's ok, but involves three copies minimum (recv() to buffer,
518 * buffer to here, here to recvq) - The new method now copies twice (recv() to buffer, buffer to recvq).
520 * We use find() instead of rfind() for clarity, however unlike the old code, our scanning of the string is
521 * contiguous: as we specify a startpoint, we never see characters we have scanned previously, making this
522 * marginally faster in cases with a number of \r hidden early on in the buffer.
525 * Start at first pos of string, find first \r, append everything in the chunk (excluding \r) to recvq. Set
526 * i ahead of the \r, search for next \r, add next chunk to buffer... repeat.
527 * -- w00t (7 may, 2008)
529 if (i == std::string::npos)
531 // no \r that we need to dance around, just add to buffer
536 ServerInstance->Logs->Log("recvqdebug", DEBUG, "Current recvq size is %d and I got called with a string of %d\n(%s)", recvq.length(), a.length(), a.c_str());
538 // While we can find the end of a chunk to add
539 while (i != std::string::npos)
541 // Append the chunk that we have
542 recvq.append(a, start, (i - start));
543 ServerInstance->Logs->Log("recvqdebug", DEBUG, "Appended a chunk, length is now %d", recvq.length());
545 // Start looking for the next one
547 i = a.find('\r', start);
550 if (start != a.length())
553 * This is here to catch a corner case when we get something like:
557 * in successive calls to us.
559 * Without this conditional, the 'U' on the second case will be dropped,
560 * which is most *certainly* not the behaviour we want!
563 ServerInstance->Logs->Log("recvqdebug", DEBUG, "*** ALERT *** start != a.length, we should probably add more");
564 recvq.append(a, start, (a.length() - start));
567 ServerInstance->Logs->Log("recvqdebug", DEBUG, "Final recvq length is %d\n(%s)", recvq.length(), recvq.c_str());
570 if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
572 this->SetWriteError("RecvQ exceeded");
573 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)recvq.length(),this->MyClass->GetRecvqMax());
580 bool User::BufferIsReady()
582 return (recvq.find('\n') != std::string::npos);
585 void User::ClearBuffer()
590 std::string User::GetBuffer()
597 /* Strip any leading \r or \n off the string.
598 * Usually there are only one or two of these,
599 * so its is computationally cheap to do.
601 std::string::iterator t = recvq.begin();
602 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
608 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
610 /* Find the first complete line, return it as the
611 * result, and leave the recvq as whats left
615 std::string ret = std::string(recvq.begin(), x);
616 recvq.erase(recvq.begin(), x + 1);
625 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
630 void User::AddWriteBuf(const std::string &data)
632 if (*this->GetWriteError())
635 if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
638 * Fix by brain - Set the error text BEFORE calling, because
639 * if we dont it'll recursively call here over and over again trying
640 * to repeatedly add the text to the sendq!
642 this->SetWriteError("SendQ exceeded");
643 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %lu exceeds connect class maximum of %lu",this->nick,(unsigned long int)sendq.length() + data.length(),this->MyClass->GetSendqMax());
647 if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
648 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
653 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
654 void User::FlushWriteBuf()
658 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
662 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
664 int old_sendq_length = sendq.length();
665 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
671 /* The socket buffer is full. This isnt fatal,
674 this->ServerInstance->SE->WantWrite(this);
678 /* Fatal error, set write error and bail
680 this->SetWriteError(errno ? strerror(errno) : "EOF from client");
686 /* advance the queue */
688 this->sendq = this->sendq.substr(n_sent);
689 /* update the user's stats counters */
690 this->bytes_out += n_sent;
692 if (n_sent != old_sendq_length)
693 this->ServerInstance->SE->WantWrite(this);
700 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::FlushWriteBuf()");
703 if (this->sendq.empty())
705 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
709 void User::SetWriteError(const std::string &error)
711 // don't try to set the error twice, its already set take the first string.
712 if (this->WriteError.empty())
713 this->WriteError = error;
716 const char* User::GetWriteError()
718 return this->WriteError.c_str();
721 void User::Oper(const std::string &opertype, const std::string &opername)
729 this->modes[UM_OPERATOR] = 1;
730 this->WriteServ("MODE %s :+o", this->nick);
731 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
732 ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
733 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
734 ServerInstance->Users->all_opers.push_back(this);
736 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
737 if (iter_opertype != ServerInstance->Config->opertypes.end())
740 if (AllowedOperCommands)
741 AllowedOperCommands->clear();
743 AllowedOperCommands = new std::map<std::string, bool>;
745 if (!AllowedChanModes)
746 AllowedChanModes = new bool[64];
748 if (!AllowedUserModes)
749 AllowedUserModes = new bool[64];
751 memset(AllowedUserModes, 0, 64);
752 memset(AllowedChanModes, 0, 64);
754 char* Classes = strdup(iter_opertype->second);
755 char* myclass = strtok_r(Classes," ",&savept);
758 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
759 if (iter_operclass != ServerInstance->Config->operclass.end())
761 char* CommandList = strdup(iter_operclass->second.commandlist);
762 mycmd = strtok_r(CommandList," ",&savept2);
765 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
766 mycmd = strtok_r(NULL," ",&savept2);
769 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
770 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
774 memset(this->AllowedUserModes, (int)(true), 64);
778 this->AllowedUserModes[*c - 'A'] = true;
781 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
785 memset(this->AllowedChanModes, (int)(true), 64);
789 this->AllowedChanModes[*c - 'A'] = true;
793 myclass = strtok_r(NULL," ",&savept);
798 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
803 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
811 /* Remove all oper only modes from the user when the deoper - Bug #466*/
812 std::string moderemove("-");
814 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
818 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
819 if (mh && mh->NeedsOper())
820 moderemove += letter;
824 std::vector<std::string> parameters;
825 parameters.push_back(this->nick);
826 parameters.push_back(moderemove);
828 ServerInstance->Parser->CallHandler("MODE", parameters, this);
830 /* unset their oper type (what IS_OPER checks), and remove +o */
832 this->modes[UM_OPERATOR] = 0;
834 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
835 ServerInstance->Users->all_opers.remove(this);
837 if (AllowedOperCommands)
839 delete AllowedOperCommands;
840 AllowedOperCommands = NULL;
842 if (AllowedUserModes)
844 delete[] AllowedUserModes;
845 AllowedUserModes = NULL;
847 if (AllowedChanModes)
849 delete[] AllowedChanModes;
850 AllowedChanModes = NULL;
856 /* adds or updates an entry in the whowas list */
857 void User::AddToWhoWas()
859 Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
862 std::deque<classbase*> params;
863 params.push_back(this);
864 whowas_command->HandleInternal(WHOWAS_ADD, params);
869 * Check class restrictions
871 void User::CheckClass()
873 ConnectClass* a = this->MyClass;
875 if ((!a) || (a->GetType() == CC_DENY))
877 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
880 else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
882 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
883 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
886 else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
888 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
889 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
893 this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
894 this->timeout = ServerInstance->Time() + a->GetRegTimeout();
895 this->MaxChans = a->GetMaxChans();
898 void User::CheckLines()
900 const char* check[] = { "G" , "K", NULL };
904 for (int n = 0; check[n]; ++n)
906 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
917 void User::FullConnect()
919 ServerInstance->stats->statsConnects++;
920 this->idle_lastmsg = ServerInstance->Time();
923 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
924 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
925 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
926 * Don't remove this! -- w00t
930 /* Check the password, if one is required by the user's connect class.
931 * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
933 if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
935 ServerInstance->Users->QuitUser(this, "Invalid password");
941 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
942 this->WriteNumeric(001, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
943 this->WriteNumeric(002, "%s :Your host is %s, running version InspIRCd-1.2",this->nick,ServerInstance->Config->ServerName);
944 this->WriteNumeric(003, "%s :This server was created %s %s", this->nick, __TIME__, __DATE__);
945 this->WriteNumeric(004, "%s %s InspIRCd-1.2 %s %s %s", this->nick, ServerInstance->Config->ServerName, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
947 ServerInstance->Config->Send005(this);
948 this->WriteNumeric(42, "%s %s :your unique ID", this->nick, this->uuid);
954 if (ServerInstance->Users->unregistered_count)
955 ServerInstance->Users->unregistered_count--;
957 /* Trigger LUSERS output, give modules a chance too */
959 FOREACH_RESULT(I_OnPreCommand, OnPreCommand("LUSERS", std::vector<std::string>(), this, true, "LUSERS"));
961 ServerInstance->CallCommandHandler("LUSERS", std::vector<std::string>(), this);
964 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
965 * for a user that doesn't exist yet.
967 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
969 this->registered = REG_ALL;
971 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
973 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString(), this->fullname);
974 ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
975 ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
978 /** User::UpdateNick()
979 * re-allocates a nick in the user_hash after they change nicknames,
980 * returns a pointer to the new user as it may have moved
982 User* User::UpdateNickHash(const char* New)
984 //user_hash::iterator newnick;
985 user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
987 if (!strcasecmp(this->nick,New))
988 return oldnick->second;
990 if (oldnick == ServerInstance->Users->clientlist->end())
991 return NULL; /* doesnt exist */
993 User* olduser = oldnick->second;
994 (*(ServerInstance->Users->clientlist))[New] = olduser;
995 ServerInstance->Users->clientlist->erase(oldnick);
999 void User::InvalidateCache()
1001 /* Invalidate cache */
1002 if (cached_fullhost)
1003 free(cached_fullhost);
1005 free(cached_hostip);
1006 if (cached_makehost)
1007 free(cached_makehost);
1008 if (cached_fullrealhost)
1009 free(cached_fullrealhost);
1010 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1013 bool User::ForceNickChange(const char* newnick)
1017 this->InvalidateCache();
1019 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1023 ServerInstance->stats->statsCollisions++;
1027 std::deque<classbase*> dummy;
1028 Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1029 if (nickhandler) // wtfbbq, when would this not be here
1031 std::vector<std::string> parameters;
1032 nickhandler->HandleInternal(1, dummy);
1033 parameters.push_back(newnick);
1034 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
1035 nickhandler->HandleInternal(0, dummy);
1039 // Unreachable, we hope
1043 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1045 this->cachedip = "";
1047 switch (protocol_family)
1049 #ifdef SUPPORT_IP6LINKS
1052 sockaddr_in6* sin = new sockaddr_in6;
1053 sin->sin6_family = AF_INET6;
1054 sin->sin6_port = port;
1055 inet_pton(AF_INET6, sip, &sin->sin6_addr);
1056 this->ip = (sockaddr*)sin;
1062 sockaddr_in* sin = new sockaddr_in;
1063 sin->sin_family = AF_INET;
1064 sin->sin_port = port;
1065 inet_pton(AF_INET, sip, &sin->sin_addr);
1066 this->ip = (sockaddr*)sin;
1070 ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1077 if (this->ip == NULL)
1080 switch (this->GetProtocolFamily())
1082 #ifdef SUPPORT_IP6LINKS
1085 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1086 return sin->sin6_port;
1092 sockaddr_in* sin = (sockaddr_in*)this->ip;
1093 return sin->sin_port;
1102 int User::GetProtocolFamily()
1104 if (this->ip == NULL)
1107 sockaddr_in* sin = (sockaddr_in*)this->ip;
1108 return sin->sin_family;
1112 * XXX the duplication here is horrid..
1113 * do we really need two methods doing essentially the same thing?
1115 const char* User::GetIPString(bool translate4in6)
1117 static char buf[1024];
1119 if (this->ip == NULL)
1122 if (!this->cachedip.empty())
1123 return this->cachedip.c_str();
1125 switch (this->GetProtocolFamily())
1127 #ifdef SUPPORT_IP6LINKS
1130 static char temp[1024];
1132 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1133 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1134 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1137 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1139 if (translate4in6 && !strncmp(temp, "0::ffff:", 8))
1141 this->cachedip = temp + 8;
1145 this->cachedip = temp;
1149 this->cachedip = buf;
1156 sockaddr_in* sin = (sockaddr_in*)this->ip;
1157 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1158 this->cachedip = buf;
1166 // Unreachable, probably
1170 /** NOTE: We cannot pass a const reference to this method.
1171 * The string is changed by the workings of the method,
1172 * so that if we pass const ref, we end up copying it to
1173 * something we can change anyway. Makes sense to just let
1174 * the compiler do that copy for us.
1176 void User::Write(std::string text)
1178 if (!ServerInstance->SE->BoundsCheckFd(this))
1183 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1184 text.append("\r\n");
1188 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1194 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1195 * implement their own buffering mechanisms
1199 this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1201 catch (CoreException& modexcept)
1203 ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1208 this->AddWriteBuf(text);
1210 ServerInstance->stats->statsSent += text.length();
1211 this->ServerInstance->SE->WantWrite(this);
1216 void User::Write(const char *text, ...)
1219 char textbuffer[MAXBUF];
1221 va_start(argsPtr, text);
1222 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1225 this->Write(std::string(textbuffer));
1228 void User::WriteServ(const std::string& text)
1230 char textbuffer[MAXBUF];
1232 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1233 this->Write(std::string(textbuffer));
1237 * Same as Write(), except `text' is prefixed with `:server.name '.
1239 void User::WriteServ(const char* text, ...)
1242 char textbuffer[MAXBUF];
1244 va_start(argsPtr, text);
1245 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1248 this->WriteServ(std::string(textbuffer));
1252 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1255 char textbuffer[MAXBUF];
1257 va_start(argsPtr, text);
1258 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1261 this->WriteNumeric(numeric, std::string(textbuffer));
1264 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1266 char textbuffer[MAXBUF];
1269 FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1274 snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1275 this->Write(std::string(textbuffer));
1278 void User::WriteFrom(User *user, const std::string &text)
1282 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1284 this->Write(std::string(tb));
1288 /* write text from an originating user to originating user */
1290 void User::WriteFrom(User *user, const char* text, ...)
1293 char textbuffer[MAXBUF];
1295 va_start(argsPtr, text);
1296 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1299 this->WriteFrom(user, std::string(textbuffer));
1303 /* write text to an destination user from a source user (e.g. user privmsg) */
1305 void User::WriteTo(User *dest, const char *data, ...)
1307 char textbuffer[MAXBUF];
1310 va_start(argsPtr, data);
1311 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1314 this->WriteTo(dest, std::string(textbuffer));
1317 void User::WriteTo(User *dest, const std::string &data)
1319 dest->WriteFrom(this, data);
1323 void User::WriteCommon(const char* text, ...)
1325 char textbuffer[MAXBUF];
1328 if (this->registered != REG_ALL)
1331 va_start(argsPtr, text);
1332 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1335 this->WriteCommon(std::string(textbuffer));
1338 void User::WriteCommon(const std::string &text)
1340 bool sent_to_at_least_one = false;
1343 if (this->registered != REG_ALL)
1349 InitializeAlreadySent(ServerInstance->SE);
1351 /* We dont want to be doing this n times, just once */
1352 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1353 std::string out = tb;
1355 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1357 CUList* ulist = v->first->GetUsers();
1358 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1360 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1362 already_sent[i->first->fd] = uniq_id;
1363 i->first->Write(out);
1364 sent_to_at_least_one = true;
1370 * if the user was not in any channels, no users will receive the text. Make sure the user
1371 * receives their OWN message for WriteCommon
1373 if (!sent_to_at_least_one)
1375 this->Write(std::string(tb));
1380 /* write a formatted string to all users who share at least one common
1381 * channel, NOT including the source user e.g. for use in QUIT
1384 void User::WriteCommonExcept(const char* text, ...)
1386 char textbuffer[MAXBUF];
1389 va_start(argsPtr, text);
1390 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1393 this->WriteCommonExcept(std::string(textbuffer));
1396 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1401 if (this->registered != REG_ALL)
1407 InitializeAlreadySent(ServerInstance->SE);
1409 snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost(),normal_text.c_str());
1410 snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost(),oper_text.c_str());
1411 std::string out1 = tb1;
1412 std::string out2 = tb2;
1414 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1416 CUList *ulist = v->first->GetUsers();
1417 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1419 if (this != i->first)
1421 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1423 already_sent[i->first->fd] = uniq_id;
1424 i->first->Write(IS_OPER(i->first) ? out2 : out1);
1431 void User::WriteCommonExcept(const std::string &text)
1436 if (this->registered != REG_ALL)
1442 InitializeAlreadySent(ServerInstance->SE);
1444 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1447 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1449 CUList *ulist = v->first->GetUsers();
1450 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1452 if (this != i->first)
1454 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1456 already_sent[i->first->fd] = uniq_id;
1457 i->first->Write(out1);
1465 void User::WriteWallOps(const std::string &text)
1467 if (!IS_LOCAL(this))
1470 std::string wallop("WALLOPS :");
1471 wallop.append(text);
1473 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1476 if (t->IsModeSet('w'))
1477 this->WriteTo(t,wallop);
1481 void User::WriteWallOps(const char* text, ...)
1483 if (!IS_LOCAL(this))
1486 char textbuffer[MAXBUF];
1489 va_start(argsPtr, text);
1490 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1493 this->WriteWallOps(std::string(textbuffer));
1496 /* return 0 or 1 depending if users u and u2 share one or more common channels
1497 * (used by QUIT, NICK etc which arent channel specific notices)
1499 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1500 * the first users channels then the second users channels within the outer loop,
1501 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1502 * all possible iterations). However this new function instead checks against the
1503 * channel's userlist in the inner loop which is a std::map<User*,User*>
1504 * and saves us time as we already know what pointer value we are after.
1505 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1506 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1508 bool User::SharesChannelWith(User *other)
1510 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1514 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1516 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1517 * by replacing it with a map::find which *should* be more efficient
1519 if (i->first->HasUser(other))
1525 bool User::ChangeName(const char* gecos)
1527 if (!strcmp(gecos, this->fullname))
1533 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1536 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1538 strlcpy(this->fullname,gecos,MAXGECOS+1);
1543 bool User::ChangeDisplayedHost(const char* shost)
1545 if (!strcmp(shost, this->dhost))
1551 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1554 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1557 if (this->ServerInstance->Config->CycleHosts)
1558 this->WriteCommonExcept("QUIT :Changing hosts");
1560 /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1561 strlcpy(this->dhost,shost,64);
1563 this->InvalidateCache();
1565 if (this->ServerInstance->Config->CycleHosts)
1567 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1569 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1570 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1572 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1577 this->WriteNumeric(396, "%s %s :is now your displayed host",this->nick,this->dhost);
1582 bool User::ChangeIdent(const char* newident)
1584 if (!strcmp(newident, this->ident))
1587 if (this->ServerInstance->Config->CycleHosts)
1588 this->WriteCommonExcept("%s","QUIT :Changing ident");
1590 strlcpy(this->ident, newident, IDENTMAX+1);
1592 this->InvalidateCache();
1594 if (this->ServerInstance->Config->CycleHosts)
1596 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1598 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1599 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1601 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1608 void User::SendAll(const char* command, const char* text, ...)
1610 char textbuffer[MAXBUF];
1611 char formatbuffer[MAXBUF];
1614 va_start(argsPtr, text);
1615 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1618 snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost(), command, textbuffer);
1619 std::string fmt = formatbuffer;
1621 for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1628 std::string User::ChannelList(User* source)
1632 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1634 /* If the target is the same as the sender, let them see all their channels.
1635 * If the channel is NOT private/secret OR the user shares a common channel
1636 * If the user is an oper, and the <options:operspywhois> option is set.
1638 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1640 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1647 void User::SplitChanList(User* dest, const std::string &cl)
1650 std::ostringstream prefix;
1651 std::string::size_type start, pos, length;
1653 prefix << this->nick << " " << dest->nick << " :";
1654 line = prefix.str();
1655 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1657 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1659 length = (pos == std::string::npos) ? cl.length() : pos;
1661 if (line.length() + namelen + length - start > 510)
1663 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1664 line = prefix.str();
1667 if(pos == std::string::npos)
1669 line.append(cl.substr(start, length - start));
1674 line.append(cl.substr(start, length - start + 1));
1680 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1684 unsigned int User::GetMaxChans()
1686 return this->MaxChans;
1691 * Sets a user's connection class.
1692 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1693 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1694 * then their ip will be taken as 'priority' anyway, so for example,
1695 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1697 ConnectClass* User::SetClass(const std::string &explicit_name)
1699 ConnectClass *found = NULL;
1701 if (!IS_LOCAL(this))
1704 if (!explicit_name.empty())
1706 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1708 ConnectClass* c = *i;
1710 if (explicit_name == c->GetName() && !c->GetDisabled())
1718 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1720 ConnectClass* c = *i;
1722 if (((match(this->GetIPString(),c->GetHost().c_str(),true)) || (match(this->host,c->GetHost().c_str()))))
1726 if (this->GetPort() == c->GetPort() && !c->GetDisabled())
1735 if (!c->GetDisabled())
1742 /* ensure we don't fuck things up refcount wise, only remove them from a class if we find a new one :P */
1745 /* deny change if change will take class over the limit */
1746 if (found->limit && (found->RefCount + 1 >= found->limit))
1748 ServerInstance->Logs->Log("USERS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", found->limit);
1749 return this->MyClass;
1752 /* should always be valid, but just in case .. */
1755 if (found == this->MyClass) // no point changing this shit :P
1756 return this->MyClass;
1757 this->MyClass->RefCount--;
1758 ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1761 this->MyClass = found;
1762 this->MyClass->RefCount++;
1763 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1766 return this->MyClass;
1769 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1770 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1771 * then their ip will be taken as 'priority' anyway, so for example,
1772 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1774 ConnectClass* User::GetClass()
1776 return this->MyClass;
1779 void User::PurgeEmptyChannels()
1781 std::vector<Channel*> to_delete;
1783 // firstly decrement the count on each channel
1784 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1786 f->first->RemoveAllPrefixes(this);
1787 if (f->first->DelUser(this) == 0)
1789 /* No users left in here, mark it for deletion */
1792 to_delete.push_back(f->first);
1796 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1801 for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1803 Channel* thischan = *n;
1804 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1805 if (i2 != ServerInstance->chanlist->end())
1807 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1809 ServerInstance->chanlist->erase(i2);
1810 this->chans.erase(*n);
1817 void User::ShowMOTD()
1819 if (!ServerInstance->Config->MOTD.size())
1821 this->WriteNumeric(422, "%s :Message of the day file is missing.",this->nick);
1824 this->WriteNumeric(375, "%s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1826 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1827 this->WriteNumeric(372, "%s :- %s",this->nick,i->c_str());
1829 this->WriteNumeric(376, "%s :End of message of the day.", this->nick);
1832 void User::ShowRULES()
1834 if (!ServerInstance->Config->RULES.size())
1836 this->WriteNumeric(434, "%s :RULES File is missing",this->nick);
1840 this->WriteNumeric(308, "%s :- %s Server Rules -",this->nick,ServerInstance->Config->ServerName);
1842 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1843 this->WriteNumeric(232, "%s :- %s",this->nick,i->c_str());
1845 this->WriteNumeric(309, "%s :End of RULES command.",this->nick);
1848 void User::HandleEvent(EventType et, int errornum)
1850 if (this->quitting) // drop everything, user is due to be quit
1853 /* WARNING: May delete this user! */
1854 int thisfd = this->GetFd();
1861 ServerInstance->ProcessUser(this);
1864 this->FlushWriteBuf();
1867 /** This should be safe, but dont DARE do anything after it -- Brain */
1868 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1874 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::HandleEvent intercepted");
1877 /* If the user has raised an error whilst being processed, quit them now we're safe to */
1878 if ((ServerInstance->SE->GetRef(thisfd) == this))
1880 if (!WriteError.empty())
1882 ServerInstance->Users->QuitUser(this, GetWriteError());
1887 void User::SetOperQuit(const std::string &oquit)
1889 operquitmsg = oquit;
1892 const char* User::GetOperQuit()
1894 return operquitmsg.c_str();
1897 void User::IncreasePenalty(int increase)
1899 this->Penalty += increase;
1902 void User::DecreasePenalty(int decrease)
1904 this->Penalty -= decrease;
1915 bool VisData::VisibleTo(User* user)