1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 #include "configreader.h"
19 #include "socketengine.h"
22 #include "cull_list.h"
24 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
26 /* XXX: Used for speeding up WriteCommon operations */
27 unsigned long uniq_id = 0;
29 bool InitTypes(ServerConfig* conf, const char* tag)
31 if (conf->opertypes.size())
33 conf->GetInstance()->Log(DEBUG,"Currently %d items to clear",conf->opertypes.size());
34 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
36 conf->GetInstance()->Log(DEBUG,"Clear item");
42 conf->opertypes.clear();
46 bool InitClasses(ServerConfig* conf, const char* tag)
48 if (conf->operclass.size())
50 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
57 conf->operclass.clear();
61 bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
63 const char* TypeName = values[0].GetString();
64 const char* Classes = values[1].GetString();
66 conf->opertypes[TypeName] = strdup(Classes);
67 conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
71 bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
73 const char* ClassName = values[0].GetString();
74 const char* CommandList = values[1].GetString();
76 conf->operclass[ClassName] = strdup(CommandList);
77 conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
81 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
86 std::string userrec::ProcessNoticeMasks(const char *sm)
88 bool adding = true, oldadding = false;
92 ServerInstance->Log(DEBUG,"Process notice masks");
96 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
107 for (unsigned char d = 'A'; d <= 'z'; d++)
109 if (ServerInstance->SNO->IsEnabled(d))
111 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
113 if ((oldadding != adding) || (!output.length()))
114 output += (adding ? '+' : '-');
116 this->SetNoticeMask(d, adding);
125 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
127 if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
129 if ((oldadding != adding) || (!output.length()))
130 output += (adding ? '+' : '-');
132 this->SetNoticeMask(*c, adding);
147 void userrec::StartDNSLookup()
149 ServerInstance->Log(DEBUG,"Commencing reverse lookup");
152 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
153 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE);
154 this->ServerInstance->AddResolver(res_reverse);
156 catch (CoreException& e)
158 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
162 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt) :
163 Resolver(Instance, to_resolve, qt), bound_user(user)
165 this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
166 this->bound_fd = user->GetFd();
169 void UserResolver::OnLookupComplete(const std::string &result)
171 if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
173 ServerInstance->Log(DEBUG,"Commencing forward lookup");
174 this->bound_user->stored_host = result;
177 /* Check we didnt time out */
178 if (this->bound_user->registered != REG_ALL)
181 const char *ip = this->bound_user->GetIPString();
182 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA));
184 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, DNS_QUERY_A);
186 this->ServerInstance->AddResolver(bound_user->res_forward);
189 catch (CoreException& e)
191 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
194 else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
196 /* Both lookups completed */
197 std::string result2 = "0::ffff:";
198 result2.append(result);
199 if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
201 std::string hostname = this->bound_user->stored_host;
202 if (hostname.length() < 65)
204 /* Check we didnt time out */
205 if (this->bound_user->registered != REG_ALL)
207 /* Hostnames starting with : are not a good thing (tm) */
208 if (*(hostname.c_str()) == ':')
209 hostname = "0" + hostname;
211 this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
212 this->bound_user->dns_done = true;
213 strlcpy(this->bound_user->dhost, hostname.c_str(),64);
214 strlcpy(this->bound_user->host, hostname.c_str(),64);
215 /* Invalidate cache */
216 this->bound_user->InvalidateCache();
221 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
226 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
231 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
233 if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
235 /* Error message here */
236 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname: %s; using your IP address (%s) instead.", errormessage.c_str(), this->bound_user->GetIPString());
237 this->bound_user->dns_done = true;
242 bool userrec::IsNoticeMaskSet(unsigned char sm)
244 return (snomasks[sm-65]);
247 void userrec::SetNoticeMask(unsigned char sm, bool value)
249 snomasks[sm-65] = value;
252 const char* userrec::FormatNoticeMasks()
254 static char data[MAXBUF];
257 for (int n = 0; n < 64; n++)
260 data[offset++] = n+65;
269 bool userrec::IsModeSet(unsigned char m)
271 return (modes[m-65]);
274 void userrec::SetMode(unsigned char m, bool value)
279 const char* userrec::FormatModes()
281 static char data[MAXBUF];
283 for (int n = 0; n < 64; n++)
286 data[offset++] = n+65;
292 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
294 ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
295 // the PROPER way to do it, AVOID bzero at *ALL* costs
296 *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
297 server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
298 reset_due = ServerInstance->Time();
299 age = ServerInstance->Time(true);
300 lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
301 ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
302 exempt = haspassed = dns_done = false;
307 res_forward = res_reverse = NULL;
311 memset(modes,0,sizeof(modes));
312 memset(snomasks,0,sizeof(snomasks));
313 /* Invalidate cache */
314 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
319 this->InvalidateCache();
323 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
324 if (x != ServerInstance->local_clones.end())
329 ServerInstance->local_clones.erase(x);
333 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
334 if (y != ServerInstance->global_clones.end())
339 ServerInstance->global_clones.erase(y);
343 if (this->GetProtocolFamily() == AF_INET)
345 delete (sockaddr_in*)ip;
347 #ifdef SUPPORT_IP6LINKS
350 delete (sockaddr_in6*)ip;
356 char* userrec::MakeHost()
358 if (this->cached_makehost)
359 return this->cached_makehost;
362 /* This is much faster than snprintf */
364 for(char* n = ident; *n; n++)
367 for(char* n = host; *n; n++)
371 this->cached_makehost = strdup(nhost);
373 return this->cached_makehost;
376 char* userrec::MakeHostIP()
378 if (this->cached_hostip)
379 return this->cached_hostip;
382 /* This is much faster than snprintf */
384 for(char* n = ident; *n; n++)
387 for(const char* n = this->GetIPString(); *n; n++)
391 this->cached_hostip = strdup(ihost);
393 return this->cached_hostip;
396 void userrec::CloseSocket()
398 shutdown(this->fd,2);
402 char* userrec::GetFullHost()
404 if (this->cached_fullhost)
405 return this->cached_fullhost;
409 for(char* n = nick; *n; n++)
412 for(char* n = ident; *n; n++)
415 for(char* n = dhost; *n; n++)
419 this->cached_fullhost = strdup(result);
421 return this->cached_fullhost;
424 char* userrec::MakeWildHost()
426 static char nresult[MAXBUF];
428 *t++ = '*'; *t++ = '!';
429 *t++ = '*'; *t++ = '@';
430 for(char* n = dhost; *n; n++)
436 int userrec::ReadData(void* buffer, size_t size)
440 return read(this->fd, buffer, size);
447 char* userrec::GetFullRealHost()
449 if (this->cached_fullrealhost)
450 return this->cached_fullrealhost;
452 char fresult[MAXBUF];
454 for(char* n = nick; *n; n++)
457 for(char* n = ident; *n; n++)
460 for(char* n = host; *n; n++)
464 this->cached_fullrealhost = strdup(fresult);
466 return this->cached_fullrealhost;
469 bool userrec::IsInvited(const irc::string &channel)
471 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
481 InvitedList* userrec::GetInviteList()
486 void userrec::InviteTo(const irc::string &channel)
488 invites.push_back(channel);
491 void userrec::RemoveInvite(const irc::string &channel)
493 ServerInstance->Log(DEBUG,"Removing invites");
494 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
504 bool userrec::HasPermission(const std::string &command)
511 * users on remote servers can completely bypass all permissions based checks.
512 * This prevents desyncs when one server has different type/class tags to another.
513 * That having been said, this does open things up to the possibility of source changes
514 * allowing remote kills, etc - but if they have access to the src, they most likely have
515 * access to the conf - so it's an end to a means either way.
520 // are they even an oper at all?
523 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
524 if (iter_opertype != ServerInstance->Config->opertypes.end())
526 char* Classes = strdup(iter_opertype->second);
527 char* myclass = strtok_r(Classes," ",&savept);
530 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
531 if (iter_operclass != ServerInstance->Config->operclass.end())
533 char* CommandList = strdup(iter_operclass->second);
534 mycmd = strtok_r(CommandList," ",&savept2);
537 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
543 mycmd = strtok_r(NULL," ",&savept2);
547 myclass = strtok_r(NULL," ",&savept);
555 /** NOTE: We cannot pass a const reference to this method.
556 * The string is changed by the workings of the method,
557 * so that if we pass const ref, we end up copying it to
558 * something we can change anyway. Makes sense to just let
559 * the compiler do that copy for us.
561 bool userrec::AddBuffer(std::string a)
565 std::string::size_type i = a.rfind('\r');
567 while (i != std::string::npos)
576 if (recvq.length() > (unsigned)this->recvqmax)
578 this->SetWriteError("RecvQ exceeded");
579 ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
588 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
593 bool userrec::BufferIsReady()
595 return (recvq.find('\n') != std::string::npos);
598 void userrec::ClearBuffer()
603 std::string userrec::GetBuffer()
610 /* Strip any leading \r or \n off the string.
611 * Usually there are only one or two of these,
612 * so its is computationally cheap to do.
614 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
615 recvq.erase(recvq.begin());
617 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
619 /* Find the first complete line, return it as the
620 * result, and leave the recvq as whats left
624 std::string ret = std::string(recvq.begin(), x);
625 recvq.erase(recvq.begin(), x + 1);
634 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
639 void userrec::AddWriteBuf(const std::string &data)
641 if (*this->GetWriteError())
644 if (sendq.length() + data.length() > (unsigned)this->sendqmax)
647 * Fix by brain - Set the error text BEFORE calling writeopers, because
648 * if we dont it'll recursively call here over and over again trying
649 * to repeatedly add the text to the sendq!
651 this->SetWriteError("SendQ exceeded");
652 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
658 if (data.length() > 512)
659 sendq.append(data.substr(0,510)).append("\r\n");
665 this->SetWriteError("SendQ exceeded");
666 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
670 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
671 void userrec::FlushWriteBuf()
675 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
679 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
681 int old_sendq_length = sendq.length();
682 int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
687 /* The socket buffer is full. This isnt fatal,
690 ServerInstance->Log(DEBUG,"EAGAIN, want write");
691 this->ServerInstance->SE->WantWrite(this);
695 /* Fatal error, set write error and bail
697 this->SetWriteError(strerror(errno));
703 /* advance the queue */
705 this->sendq = this->sendq.substr(n_sent);
706 /* update the user's stats counters */
707 this->bytes_out += n_sent;
709 if (n_sent != old_sendq_length)
711 ServerInstance->Log(DEBUG,"Not all written, want write");
712 this->ServerInstance->SE->WantWrite(this);
720 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
724 void userrec::SetWriteError(const std::string &error)
728 // don't try to set the error twice, its already set take the first string.
729 if (this->WriteError.empty())
731 ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
732 this->WriteError = error;
738 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
742 const char* userrec::GetWriteError()
744 return this->WriteError.c_str();
747 void userrec::Oper(const std::string &opertype)
751 this->modes[UM_OPERATOR] = 1;
752 this->WriteServ("MODE %s :+o", this->nick);
753 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
754 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
755 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
756 ServerInstance->all_opers.push_back(this);
757 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
762 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
766 void userrec::UnOper()
773 this->modes[UM_OPERATOR] = 0;
774 for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
778 ServerInstance->Log(DEBUG,"Oper removed from optimization list");
779 ServerInstance->all_opers.erase(a);
788 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
792 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
794 user_hash::iterator iter = Instance->clientlist->find(user->nick);
795 std::string reason = quitreason;
797 if (reason.length() > MAXQUIT - 1)
798 reason.resize(MAXQUIT - 1);
800 if (user->registered != REG_ALL)
801 if (Instance->unregistered_count)
802 Instance->unregistered_count--;
806 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
807 if ((!user->sendq.empty()) && (!(*user->GetWriteError())))
808 user->FlushWriteBuf();
811 if (user->registered == REG_ALL)
813 user->PurgeEmptyChannels();
814 user->WriteCommonExcept("QUIT :%s",reason.c_str());
815 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
818 FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
822 if (Instance->Config->GetIOHook(user->GetPort()))
826 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
828 catch (CoreException& modexcept)
830 Instance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
834 Instance->SE->DelFd(user);
839 * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
840 * if they were an oper with +sn +qQ.
842 if (user->registered == REG_ALL)
845 Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
847 Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
851 if (iter != Instance->clientlist->end())
853 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
856 std::vector<userrec*>::iterator x = find(Instance->local_users.begin(),Instance->local_users.end(),user);
857 if (x != Instance->local_users.end())
858 Instance->local_users.erase(x);
860 Instance->clientlist->erase(iter);
870 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
872 this->host = strdup(user->host);
873 this->dhost = strdup(user->dhost);
874 this->ident = strdup(user->ident);
875 this->server = user->server;
876 this->gecos = strdup(user->fullname);
879 WhoWasGroup::~WhoWasGroup()
891 /* every hour, run this function which removes all entries older than Config->WhoWasMaxKeep */
892 void MaintainWhoWas(InspIRCd* ServerInstance, time_t t)
894 for (whowas_users::iterator iter = ServerInstance->whowas.begin(); iter != ServerInstance->whowas.end(); iter++)
896 whowas_set* n = (whowas_set*)iter->second;
899 while ((n->begin() != n->end()) && ((*n->begin())->signon < t - ServerInstance->Config->WhoWasMaxKeep))
901 WhoWasGroup *a = *(n->begin());
903 n->erase(n->begin());
908 /* on rehash, refactor maps according to new conf values */
909 void PruneWhoWas(InspIRCd* ServerInstance, time_t t)
912 int groupsize = ServerInstance->Config->WhoWasGroupSize;
913 int maxgroups = ServerInstance->Config->WhoWasMaxGroups;
914 int maxkeep = ServerInstance->Config->WhoWasMaxKeep;
916 int groupcount = ServerInstance->whowas.size();
917 /* iterate whowas_fifo oldest first */
918 whowas_users_fifo::iterator iter, safeiter;
919 for (iter = ServerInstance->whowas_fifo.begin(); iter != ServerInstance->whowas_fifo.end(); iter++)
921 /** prune all groups that has expired due to new maxkeep time and
922 * also any group number higher than new maxgroups. The oldest are
923 * removed first due to iteration over whowas_fifo
925 if (groupcount > maxgroups || iter->first < t - maxkeep)
927 whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
930 while (n->begin() != n->end())
932 WhoWasGroup *a = *(n->begin());
934 n->erase(n->begin());
937 ServerInstance->whowas.erase(iter->second);
938 /* use a safe iter copy for erase and set the orig iter old valid ref by decrementing it */
941 ServerInstance->whowas_fifo.erase(safeiter);
944 /* also trim individual groupsizes in case groupsize should have been lowered */
945 whowas_set* n = (whowas_set*)ServerInstance->whowas.find(iter->second)->second;
948 int nickcount = n->size();
949 while (n->begin() != n->end() && nickcount > groupsize)
951 WhoWasGroup *a = *(n->begin());
953 n->erase(n->begin());
964 /* adds or updates an entry in the whowas list */
965 void userrec::AddToWhoWas()
967 /* if whowas disabled */
968 if (ServerInstance->Config->WhoWasGroupSize == 0 || ServerInstance->Config->WhoWasMaxGroups == 0)
973 irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
975 ServerInstance->Log(DEBUG,"Add to whowas lists");
977 if (iter == ServerInstance->whowas.end())
979 ServerInstance->Log(DEBUG,"Adding new whowas set for %s",this->nick);
980 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
981 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
983 ServerInstance->whowas[this->nick] = n;
984 ServerInstance->whowas_fifo.push_back(std::make_pair(ServerInstance->Time(),this->nick));
985 if ((int)(ServerInstance->whowas.size()) > ServerInstance->Config->WhoWasMaxGroups)
987 ServerInstance->Log(DEBUG,"Maxgroups of %d reached deleting oldest group '%s'",ServerInstance->Config->WhoWasMaxGroups, ServerInstance->whowas_fifo.begin()->second.c_str());
988 ServerInstance->whowas.erase(ServerInstance->whowas_fifo.begin()->second);
989 ServerInstance->whowas_fifo.pop_front();
994 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
996 ServerInstance->Log(DEBUG,"Using existing whowas group for %s",this->nick);
998 if ((int)(group->size()) >= ServerInstance->Config->WhoWasGroupSize)
1000 ServerInstance->Log(DEBUG,"Trimming existing group '%s' to %d entries",this->nick, ServerInstance->Config->WhoWasGroupSize);
1001 irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
1006 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
1007 group->push_back(a);
1011 /* add a client connection to the sockets list */
1012 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
1014 std::string tempnick = ConvToStr(socket) + "-unknown";
1015 user_hash::iterator iter = Instance->clientlist->find(tempnick);
1016 const char *ipaddr = insp_ntoa(ip);
1020 Instance->unregistered_count++;
1024 * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1025 * using one as a registered connection. As they are per fd, we can also safely assume
1026 * that we wont have collisions. Therefore, if the nick exists in the list, its only
1027 * used by a dead socket, erase the iterator so that the new client may reclaim it.
1028 * this was probably the cause of 'server ignores me when i hammer it with reconnects'
1029 * issue in earlier alphas/betas
1031 if (iter != Instance->clientlist->end())
1033 userrec* goner = iter->second;
1035 Instance->clientlist->erase(iter);
1038 Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
1040 New = new userrec(Instance);
1041 (*(Instance->clientlist))[tempnick] = New;
1043 strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
1045 New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
1046 /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
1047 strcpy(New->ident, "unknown");
1049 New->registered = REG_NONE;
1050 New->signon = Instance->Time() + Instance->Config->dns_timeout;
1053 New->SetSockAddr(AF_FAMILY, ipaddr, port);
1055 /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
1056 for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
1057 New->dhost[j] = New->host[j] = *temp;
1058 New->dhost[j] = New->host[j] = 0;
1060 Instance->AddLocalClone(New);
1061 Instance->AddGlobalClone(New);
1063 ConnectClass* i = New->GetClass();
1065 if ((!i) || (i->GetType() == CC_DENY))
1067 userrec::QuitUser(Instance, New,"Unauthorised connection");
1071 New->pingmax = i->GetPingTime();
1072 New->nping = Instance->Time() + i->GetPingTime() + Instance->Config->dns_timeout;
1073 New->timeout = Instance->Time() + i->GetRegTimeout();
1074 New->flood = i->GetFlood();
1075 New->threshold = i->GetThreshold();
1076 New->sendqmax = i->GetSendqMax();
1077 New->recvqmax = i->GetRecvqMax();
1079 Instance->local_users.push_back(New);
1081 if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
1083 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
1084 userrec::QuitUser(Instance, New,"No more connections allowed");
1090 * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1091 * its a pretty big but for the moment valid assumption:
1092 * file descriptors are handed out starting at 0, and are recycled as theyre freed.
1093 * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1094 * irc server at once (or the irc server otherwise initiating this many connections, files etc)
1095 * which for the time being is a physical impossibility (even the largest networks dont have more
1096 * than about 10,000 users on ONE server!)
1098 if ((unsigned int)socket >= MAX_DESCRIPTORS)
1100 userrec::QuitUser(Instance, New, "Server is full");
1104 New->exempt = (Instance->XLines->matches_exception(New) != NULL);
1107 ZLine* r = Instance->XLines->matches_zline(ipaddr);
1110 char reason[MAXBUF];
1111 snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
1112 userrec::QuitUser(Instance, New, reason);
1119 if (!Instance->SE->AddFd(New))
1121 userrec::QuitUser(Instance, New, "Internal error handling connection");
1126 /* NOTE: even if dns lookups are *off*, we still need to display this.
1127 * BOPM and other stuff requires it.
1129 New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
1132 unsigned long userrec::GlobalCloneCount()
1134 clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
1135 if (x != ServerInstance->global_clones.end())
1141 unsigned long userrec::LocalCloneCount()
1143 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
1144 if (x != ServerInstance->local_clones.end())
1150 void userrec::FullConnect(CullList* Goners)
1152 ServerInstance->stats->statsConnects++;
1153 this->idle_lastmsg = ServerInstance->Time();
1155 ConnectClass* a = this->GetClass();
1157 if ((!a) || (a->GetType() == CC_DENY))
1159 Goners->AddItem(this,"Unauthorised connection");
1163 if ((!a->GetPass().empty()) && (!this->haspassed))
1165 Goners->AddItem(this,"Invalid password");
1169 if (this->LocalCloneCount() > a->GetMaxLocal())
1171 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1172 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
1175 else if (this->GlobalCloneCount() > a->GetMaxGlobal())
1177 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1178 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a->GetMaxGlobal(), this->GetIPString());
1184 GLine* r = ServerInstance->XLines->matches_gline(this);
1188 char reason[MAXBUF];
1189 snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1190 Goners->AddItem(this, reason);
1194 KLine* n = ServerInstance->XLines->matches_kline(this);
1198 char reason[MAXBUF];
1199 snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1200 Goners->AddItem(this, reason);
1206 this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1207 this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1208 this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1209 this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1210 this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
1212 ServerInstance->Config->Send005(this);
1216 /* Now registered */
1217 if (ServerInstance->unregistered_count)
1218 ServerInstance->unregistered_count--;
1221 * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1222 * changes dont go out onto the network and produce 'fake direction'.
1224 FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1226 this->registered = REG_ALL;
1228 FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1230 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1233 /** userrec::UpdateNick()
1234 * re-allocates a nick in the user_hash after they change nicknames,
1235 * returns a pointer to the new user as it may have moved
1237 userrec* userrec::UpdateNickHash(const char* New)
1241 //user_hash::iterator newnick;
1242 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1244 if (!strcasecmp(this->nick,New))
1245 return oldnick->second;
1247 if (oldnick == ServerInstance->clientlist->end())
1248 return NULL; /* doesnt exist */
1250 userrec* olduser = oldnick->second;
1251 (*(ServerInstance->clientlist))[New] = olduser;
1252 ServerInstance->clientlist->erase(oldnick);
1258 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1263 void userrec::InvalidateCache()
1265 /* Invalidate cache */
1266 if (cached_fullhost)
1267 free(cached_fullhost);
1269 free(cached_hostip);
1270 if (cached_makehost)
1271 free(cached_makehost);
1272 if (cached_fullrealhost)
1273 free(cached_fullrealhost);
1274 cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1277 bool userrec::ForceNickChange(const char* newnick)
1283 this->InvalidateCache();
1285 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1289 ServerInstance->stats->statsCollisions++;
1293 if (ServerInstance->XLines->matches_qline(newnick))
1295 ServerInstance->stats->statsCollisions++;
1299 if (this->registered == REG_ALL)
1301 const char* pars[1];
1303 std::string cmd = "NICK";
1304 return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1311 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1316 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1318 switch (protocol_family)
1320 #ifdef SUPPORT_IP6LINKS
1323 ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1324 sockaddr_in6* sin = new sockaddr_in6;
1325 sin->sin6_family = AF_INET6;
1326 sin->sin6_port = port;
1327 inet_pton(AF_INET6, ip, &sin->sin6_addr);
1328 this->ip = (sockaddr*)sin;
1334 ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1335 sockaddr_in* sin = new sockaddr_in;
1336 sin->sin_family = AF_INET;
1337 sin->sin_port = port;
1338 inet_pton(AF_INET, ip, &sin->sin_addr);
1339 this->ip = (sockaddr*)sin;
1343 ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1348 int userrec::GetPort()
1350 if (this->ip == NULL)
1353 switch (this->GetProtocolFamily())
1355 #ifdef SUPPORT_IP6LINKS
1358 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1359 return sin->sin6_port;
1365 sockaddr_in* sin = (sockaddr_in*)this->ip;
1366 return sin->sin_port;
1375 int userrec::GetProtocolFamily()
1377 if (this->ip == NULL)
1380 sockaddr_in* sin = (sockaddr_in*)this->ip;
1381 return sin->sin_family;
1384 const char* userrec::GetIPString()
1386 static char buf[1024];
1388 if (this->ip == NULL)
1391 switch (this->GetProtocolFamily())
1393 #ifdef SUPPORT_IP6LINKS
1396 static char temp[1024];
1398 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1399 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1400 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1403 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1413 sockaddr_in* sin = (sockaddr_in*)this->ip;
1414 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1424 const char* userrec::GetIPString(char* buf)
1426 if (this->ip == NULL)
1432 switch (this->GetProtocolFamily())
1434 #ifdef SUPPORT_IP6LINKS
1437 static char temp[1024];
1439 sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1440 inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1441 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1444 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1446 strlcpy(buf, temp, sizeof(temp));
1454 sockaddr_in* sin = (sockaddr_in*)this->ip;
1455 inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1466 /** NOTE: We cannot pass a const reference to this method.
1467 * The string is changed by the workings of the method,
1468 * so that if we pass const ref, we end up copying it to
1469 * something we can change anyway. Makes sense to just let
1470 * the compiler do that copy for us.
1472 void userrec::Write(std::string text)
1474 if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1479 text.append("\r\n");
1483 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1487 if (ServerInstance->Config->GetIOHook(this->GetPort()))
1491 ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1493 catch (CoreException& modexcept)
1495 ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1500 this->AddWriteBuf(text);
1502 ServerInstance->stats->statsSent += text.length();
1503 this->ServerInstance->SE->WantWrite(this);
1508 void userrec::Write(const char *text, ...)
1511 char textbuffer[MAXBUF];
1513 va_start(argsPtr, text);
1514 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1517 this->Write(std::string(textbuffer));
1520 void userrec::WriteServ(const std::string& text)
1522 char textbuffer[MAXBUF];
1524 snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1525 this->Write(std::string(textbuffer));
1529 * Same as Write(), except `text' is prefixed with `:server.name '.
1531 void userrec::WriteServ(const char* text, ...)
1534 char textbuffer[MAXBUF];
1536 va_start(argsPtr, text);
1537 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1540 this->WriteServ(std::string(textbuffer));
1544 void userrec::WriteFrom(userrec *user, const std::string &text)
1548 snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1550 this->Write(std::string(tb));
1554 /* write text from an originating user to originating user */
1556 void userrec::WriteFrom(userrec *user, const char* text, ...)
1559 char textbuffer[MAXBUF];
1561 va_start(argsPtr, text);
1562 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1565 this->WriteFrom(user, std::string(textbuffer));
1569 /* write text to an destination user from a source user (e.g. user privmsg) */
1571 void userrec::WriteTo(userrec *dest, const char *data, ...)
1573 char textbuffer[MAXBUF];
1576 va_start(argsPtr, data);
1577 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1580 this->WriteTo(dest, std::string(textbuffer));
1583 void userrec::WriteTo(userrec *dest, const std::string &data)
1585 dest->WriteFrom(this, data);
1589 void userrec::WriteCommon(const char* text, ...)
1591 char textbuffer[MAXBUF];
1594 if (this->registered != REG_ALL)
1597 va_start(argsPtr, text);
1598 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1601 this->WriteCommon(std::string(textbuffer));
1604 void userrec::WriteCommon(const std::string &text)
1608 bool sent_to_at_least_one = false;
1611 if (this->registered != REG_ALL)
1616 /* We dont want to be doing this n times, just once */
1617 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1618 std::string out = tb;
1620 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1622 CUList* ulist = v->first->GetUsers();
1623 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1625 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1627 already_sent[i->second->fd] = uniq_id;
1628 i->second->Write(out);
1629 sent_to_at_least_one = true;
1635 * if the user was not in any channels, no users will receive the text. Make sure the user
1636 * receives their OWN message for WriteCommon
1638 if (!sent_to_at_least_one)
1640 this->WriteFrom(this,std::string(tb));
1646 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1651 /* write a formatted string to all users who share at least one common
1652 * channel, NOT including the source user e.g. for use in QUIT
1655 void userrec::WriteCommonExcept(const char* text, ...)
1657 char textbuffer[MAXBUF];
1660 va_start(argsPtr, text);
1661 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1664 this->WriteCommonExcept(std::string(textbuffer));
1667 void userrec::WriteCommonExcept(const std::string &text)
1669 bool quit_munge = false;
1670 char oper_quit[MAXBUF];
1671 char textbuffer[MAXBUF];
1677 strlcpy(textbuffer, text.c_str(), MAXBUF);
1679 if (this->registered != REG_ALL)
1684 snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),textbuffer);
1686 /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1687 * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1690 if (ServerInstance->Config->HideSplits)
1692 char* check = textbuffer + 6;
1694 if (!strncasecmp(textbuffer, "QUIT :",6))
1696 std::stringstream split(check);
1697 std::string server_one;
1698 std::string server_two;
1700 split >> server_one;
1701 split >> server_two;
1703 if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1705 strlcpy(oper_quit,textbuffer,MAXQUIT);
1706 strlcpy(check,"*.net *.split",MAXQUIT);
1708 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1714 if ((ServerInstance->Config->HideBans) && (!quit_munge))
1716 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1717 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1719 char* check = textbuffer + 13;
1720 strlcpy(oper_quit,textbuffer,MAXQUIT);
1721 *check = 0; // We don't need to strlcpy, we just chop it from the :
1723 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1730 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1732 CUList *ulist = v->first->GetUsers();
1733 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1735 if (this != i->second)
1737 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1739 already_sent[i->second->fd] = uniq_id;
1741 i->second->Write(*i->second->oper ? out2 : out1);
1743 i->second->Write(out1);
1751 void userrec::WriteWallOps(const std::string &text)
1753 /* Does nothing if theyre not opered */
1754 if ((!*this->oper) && (IS_LOCAL(this)))
1757 std::string wallop = "WALLOPS :";
1761 wallop.append(text);
1765 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1769 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1772 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1773 this->WriteTo(t,wallop);
1777 void userrec::WriteWallOps(const char* text, ...)
1779 char textbuffer[MAXBUF];
1782 va_start(argsPtr, text);
1783 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1786 this->WriteWallOps(std::string(textbuffer));
1789 /* return 0 or 1 depending if users u and u2 share one or more common channels
1790 * (used by QUIT, NICK etc which arent channel specific notices)
1792 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1793 * the first users channels then the second users channels within the outer loop,
1794 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1795 * all possible iterations). However this new function instead checks against the
1796 * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1797 * and saves us time as we already know what pointer value we are after.
1798 * Don't quote me on the maths as i am not a mathematician or computer scientist,
1799 * but i believe this algorithm is now x+(log y) maximum iterations instead.
1801 bool userrec::SharesChannelWith(userrec *other)
1803 if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1807 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1809 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1810 * by replacing it with a map::find which *should* be more efficient
1812 if (i->first->HasUser(other))
1818 bool userrec::ChangeName(const char* gecos)
1820 if (!strcmp(gecos, this->fullname))
1826 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1829 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1831 strlcpy(this->fullname,gecos,MAXGECOS+1);
1836 bool userrec::ChangeDisplayedHost(const char* host)
1838 if (!strcmp(host, this->dhost))
1844 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1847 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1849 if (this->ServerInstance->Config->CycleHosts)
1850 this->WriteCommonExcept("QUIT :Changing hosts");
1852 /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1853 strlcpy(this->dhost,host,64);
1855 this->InvalidateCache();
1857 if (this->ServerInstance->Config->CycleHosts)
1859 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1861 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1862 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1864 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1869 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1874 bool userrec::ChangeIdent(const char* newident)
1876 if (!strcmp(newident, this->ident))
1879 if (this->ServerInstance->Config->CycleHosts)
1880 this->WriteCommonExcept("%s","QUIT :Changing ident");
1882 strlcpy(this->ident, newident, IDENTMAX+2);
1884 this->InvalidateCache();
1886 if (this->ServerInstance->Config->CycleHosts)
1888 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1890 i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1891 std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1893 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1900 void userrec::NoticeAll(char* text, ...)
1902 char textbuffer[MAXBUF];
1903 char formatbuffer[MAXBUF];
1906 va_start(argsPtr, text);
1907 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1910 snprintf(formatbuffer,MAXBUF,":%s NOTICE $* :%s", this->GetFullHost(), textbuffer);
1911 std::string fmt = formatbuffer;
1913 for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1920 std::string userrec::ChannelList(userrec* source)
1925 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1927 /* If the target is the same as the sender, let them see all their channels.
1928 * If the channel is NOT private/secret OR the user shares a common channel
1929 * If the user is an oper, and the <options:operspywhois> option is set.
1931 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1933 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1940 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1945 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1948 std::ostringstream prefix;
1949 std::string::size_type start, pos, length;
1953 prefix << this->nick << " " << dest->nick << " :";
1954 line = prefix.str();
1955 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1957 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1959 length = (pos == std::string::npos) ? cl.length() : pos;
1961 if (line.length() + namelen + length - start > 510)
1963 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1964 line = prefix.str();
1967 if(pos == std::string::npos)
1969 line.append(cl.substr(start, length - start));
1974 line.append(cl.substr(start, length - start + 1));
1980 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1986 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1991 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1992 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1993 * then their ip will be taken as 'priority' anyway, so for example,
1994 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1996 ConnectClass* userrec::GetClass()
1998 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
2000 if ((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str())))
2006 void userrec::PurgeEmptyChannels()
2008 std::vector<chanrec*> to_delete;
2010 // firstly decrement the count on each channel
2011 for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
2013 f->first->RemoveAllPrefixes(this);
2014 if (f->first->DelUser(this) == 0)
2016 /* No users left in here, mark it for deletion */
2019 to_delete.push_back(f->first);
2023 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
2028 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
2030 chanrec* thischan = *n;
2031 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
2032 if (i2 != ServerInstance->chanlist->end())
2034 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
2036 ServerInstance->chanlist->erase(i2);
2037 this->chans.erase(*n);
2044 void userrec::ShowMOTD()
2046 if (!ServerInstance->Config->MOTD.size())
2048 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
2051 this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
2053 for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
2054 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
2056 this->WriteServ("376 %s :End of message of the day.", this->nick);
2059 void userrec::ShowRULES()
2061 if (!ServerInstance->Config->RULES.size())
2063 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
2066 this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
2068 for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
2069 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
2071 this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
2074 void userrec::HandleEvent(EventType et, int errornum)
2076 /* WARNING: May delete this user! */
2077 int thisfd = this->GetFd();
2084 ServerInstance->ProcessUser(this);
2087 this->FlushWriteBuf();
2090 /** This should be safe, but dont DARE do anything after it -- Brain */
2091 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
2097 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
2100 /* If the user has raised an error whilst being processed, quit them now we're safe to */
2101 if ((ServerInstance->SE->GetRef(thisfd) == this))
2103 if (!WriteError.empty())
2105 userrec::QuitUser(ServerInstance, this, GetWriteError());