2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
6 * Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
8 * This file is part of InspIRCd. InspIRCd is free software: you can
9 * redistribute it and/or modify it under the terms of the GNU General Public
10 * License as published by the Free Software Foundation, version 2.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
32 class CommandStats : public Command
34 void DoStats(char statschar, User* user, string_list &results);
36 /** Constructor for stats.
38 CommandStats ( Module* parent) : Command(parent,"STATS",1,2) { syntax = "<stats-symbol> [<servername>]"; }
40 * @param parameters The parameters to the command
41 * @param user The user issuing the command
42 * @return A value from CmdResult to indicate command success or failure.
44 CmdResult Handle(const std::vector<std::string>& parameters, User *user);
45 RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
47 if (parameters.size() > 1)
48 return ROUTE_UNICAST(parameters[1]);
49 return ROUTE_LOCALONLY;
53 void CommandStats::DoStats(char statschar, User* user, string_list &results)
55 bool isPublic = ServerInstance->Config->UserStats.find(statschar) != std::string::npos;
56 bool isRemoteOper = IS_REMOTE(user) && (user->IsOper());
57 bool isLocalOperWithPrivs = IS_LOCAL(user) && user->HasPrivPermission("servers/auspex");
59 if (!isPublic && !isRemoteOper && !isLocalOperWithPrivs)
61 ServerInstance->SNO->WriteToSnoMask('t',
62 "%s '%c' denied for %s (%s@%s)",
63 (IS_LOCAL(user) ? "Stats" : "Remote stats"),
64 statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
65 results.push_back("481 " + user->nick + " :Permission Denied - STATS " + statschar + " requires the servers/auspex priv.");
70 FIRST_MOD_RESULT(OnStats, MOD_RESULT, (statschar, user, results));
71 if (MOD_RESULT == MOD_RES_DENY)
73 results.push_back("219 "+user->nick+" "+statschar+" :End of /STATS report");
74 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
75 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
81 /* stats p (show listening ports) */
84 for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i)
86 ListenSocket* ls = *i;
87 std::string ip = ls->bind_addr;
90 std::string type = ls->bind_tag->getString("type", "clients");
91 std::string hook = ls->bind_tag->getString("ssl", "plaintext");
93 results.push_back("249 "+user->nick+" :"+ ip + ":"+ConvToStr(ls->bind_port)+
94 " (" + type + ", " + hook + ")");
99 /* These stats symbols must be handled by a linking module */
106 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
108 ConnectClass* c = *i;
109 std::stringstream res;
110 res << "215 " << user->nick << " I " << c->name << ' ';
111 if (c->type == CC_ALLOW)
113 if (c->type == CC_DENY)
116 if (c->type == CC_NAMED)
121 res << ' ' << c->config->getString("port", "*") << ' ';
123 res << c->GetRecvqMax() << ' ' << c->GetSendqSoftMax() << ' ' << c->GetSendqHardMax()
124 << ' ' << c->GetCommandRate() << ' ' << c->GetPenaltyThreshold();
127 results.push_back(res.str());
135 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
137 ConnectClass* c = *i;
138 results.push_back("215 "+user->nick+" i NOMATCH * "+c->GetHost()+" "+ConvToStr(c->limit ? c->limit : SocketEngine::GetMaxFds())+" "+ConvToStr(idx)+" "+ServerInstance->Config->ServerName+" *");
139 results.push_back("218 "+user->nick+" Y "+ConvToStr(idx)+" "+ConvToStr(c->GetPingTime())+" 0 "+ConvToStr(c->GetSendqHardMax())+" :"+
140 ConvToStr(c->GetRecvqMax())+" "+ConvToStr(c->GetRegTimeout()));
148 unsigned int idx = 0;
149 const UserManager::OperList& opers = ServerInstance->Users->all_opers;
150 for (UserManager::OperList::const_iterator i = opers.begin(); i != opers.end(); ++i)
153 if (!oper->server->IsULine())
155 LocalUser* lu = IS_LOCAL(oper);
156 results.push_back("249 " + user->nick + " :" + oper->nick + " (" + oper->ident + "@" + oper->dhost + ") Idle: " +
157 (lu ? ConvToStr(ServerInstance->Time() - lu->idle_lastmsg) + " secs" : "unavailable"));
161 results.push_back("249 "+user->nick+" :"+ConvToStr(idx)+" OPER(s)");
166 ServerInstance->XLines->InvokeStats("K",216,user,results);
169 ServerInstance->XLines->InvokeStats("G",223,user,results);
172 ServerInstance->XLines->InvokeStats("Q",217,user,results);
175 ServerInstance->XLines->InvokeStats("Z",223,user,results);
178 ServerInstance->XLines->InvokeStats("E",223,user,results);
182 const SocketEngine::Statistics& stats = SocketEngine::GetStats();
183 results.push_back("249 "+user->nick+" :Total events: "+ConvToStr(stats.TotalEvents));
184 results.push_back("249 "+user->nick+" :Read events: "+ConvToStr(stats.ReadEvents));
185 results.push_back("249 "+user->nick+" :Write events: "+ConvToStr(stats.WriteEvents));
186 results.push_back("249 "+user->nick+" :Error events: "+ConvToStr(stats.ErrorEvents));
190 /* stats m (list number of times each command has been used, plus bytecount) */
192 for (Commandtable::iterator i = ServerInstance->Parser->cmdlist.begin(); i != ServerInstance->Parser->cmdlist.end(); i++)
194 if (i->second->use_count)
196 /* RPL_STATSCOMMANDS */
197 results.push_back("212 "+user->nick+" "+i->second->name+" "+ConvToStr(i->second->use_count));
202 /* stats z (debug and memory info) */
205 results.push_back("249 "+user->nick+" :Users: "+ConvToStr(ServerInstance->Users->GetUsers().size()));
206 results.push_back("249 "+user->nick+" :Channels: "+ConvToStr(ServerInstance->GetChans().size()));
207 results.push_back("249 "+user->nick+" :Commands: "+ConvToStr(ServerInstance->Parser->cmdlist.size()));
209 float kbitpersec_in, kbitpersec_out, kbitpersec_total;
210 char kbitpersec_in_s[30], kbitpersec_out_s[30], kbitpersec_total_s[30];
212 SocketEngine::GetStats().GetBandwidth(kbitpersec_in, kbitpersec_out, kbitpersec_total);
214 snprintf(kbitpersec_total_s, 30, "%03.5f", kbitpersec_total);
215 snprintf(kbitpersec_out_s, 30, "%03.5f", kbitpersec_out);
216 snprintf(kbitpersec_in_s, 30, "%03.5f", kbitpersec_in);
218 results.push_back("249 "+user->nick+" :Bandwidth total: "+ConvToStr(kbitpersec_total_s)+" kilobits/sec");
219 results.push_back("249 "+user->nick+" :Bandwidth out: "+ConvToStr(kbitpersec_out_s)+" kilobits/sec");
220 results.push_back("249 "+user->nick+" :Bandwidth in: "+ConvToStr(kbitpersec_in_s)+" kilobits/sec");
223 /* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
224 * Also cuts out some identical code in both branches of the ifndef. -- Om
228 /* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
229 if (!getrusage(RUSAGE_SELF,&R)) /* RUSAGE_SELF */
231 results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
232 results.push_back("249 "+user->nick+" :Signals: "+ConvToStr(R.ru_nsignals));
233 results.push_back("249 "+user->nick+" :Page faults: "+ConvToStr(R.ru_majflt));
234 results.push_back("249 "+user->nick+" :Swaps: "+ConvToStr(R.ru_nswap));
235 results.push_back("249 "+user->nick+" :Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));
239 float n_elapsed = (ServerInstance->Time() - ServerInstance->stats->LastSampled.tv_sec) * 1000000
240 + (ServerInstance->Time_ns() - ServerInstance->stats->LastSampled.tv_nsec) / 1000;
241 float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats->LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats->LastCPU.tv_usec);
242 float per = (n_eaten / n_elapsed) * 100;
244 snprintf(percent, 30, "%03.5f%%", per);
245 results.push_back("249 "+user->nick+" :CPU Use (now): "+percent);
247 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
248 n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
249 per = (n_eaten / n_elapsed) * 100;
250 snprintf(percent, 30, "%03.5f%%", per);
251 results.push_back("249 "+user->nick+" :CPU Use (total): "+percent);
254 PROCESS_MEMORY_COUNTERS MemCounters;
255 if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
257 results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
258 results.push_back("249 "+user->nick+" :Pagefile usage: "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
259 results.push_back("249 "+user->nick+" :Page faults: "+ConvToStr(MemCounters.PageFaultCount));
262 FILETIME CreationTime;
266 LARGE_INTEGER ThisSample;
267 if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
268 QueryPerformanceCounter(&ThisSample))
270 KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
271 KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
272 double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats->LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats->LastCPU.dwLowDateTime) )/100000;
273 double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats->LastSampled.QuadPart) / ServerInstance->stats->QPFrequency.QuadPart;
274 double per = (n_eaten/n_elapsed);
278 snprintf(percent, 30, "%03.5f%%", per);
279 results.push_back("249 "+user->nick+" :CPU Use (now): "+percent);
281 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
282 n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
283 per = (n_eaten / n_elapsed);
284 snprintf(percent, 30, "%03.5f%%", per);
285 results.push_back("249 "+user->nick+" :CPU Use (total): "+percent);
293 results.push_back("249 "+user->nick+" :accepts "+ConvToStr(ServerInstance->stats->statsAccept)+" refused "+ConvToStr(ServerInstance->stats->statsRefused));
294 results.push_back("249 "+user->nick+" :unknown commands "+ConvToStr(ServerInstance->stats->statsUnknown));
295 results.push_back("249 "+user->nick+" :nick collisions "+ConvToStr(ServerInstance->stats->statsCollisions));
296 results.push_back("249 "+user->nick+" :dns requests "+ConvToStr(ServerInstance->stats->statsDnsGood+ServerInstance->stats->statsDnsBad)+" succeeded "+ConvToStr(ServerInstance->stats->statsDnsGood)+" failed "+ConvToStr(ServerInstance->stats->statsDnsBad));
297 results.push_back("249 "+user->nick+" :connection count "+ConvToStr(ServerInstance->stats->statsConnects));
298 results.push_back(InspIRCd::Format("249 %s :bytes sent %5.2fK recv %5.2fK", user->nick.c_str(),
299 ServerInstance->stats->statsSent / 1024.0, ServerInstance->stats->statsRecv / 1024.0));
306 ConfigTagList tags = ServerInstance->Config->ConfTags("oper");
307 for(ConfigIter i = tags.first; i != tags.second; ++i)
309 ConfigTag* tag = i->second;
310 results.push_back("243 "+user->nick+" O "+tag->getString("host")+" * "+
311 tag->getString("name") + " " + tag->getString("type")+" 0");
317 for (OperIndex::const_iterator i = ServerInstance->Config->OperTypes.begin(); i != ServerInstance->Config->OperTypes.end(); ++i)
319 OperInfo* tag = i->second;
323 for(char c='A'; c < 'z'; c++)
325 ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
326 if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
328 mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
329 if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
332 results.push_back("243 "+user->nick+" O "+tag->name.c_str() + " " + umodes + " " + cmodes);
337 /* stats l (show user I/O stats) */
339 results.push_back("211 "+user->nick+" :nick[ident@host] sendq cmds_out bytes_out cmds_in bytes_in time_open");
340 for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
343 results.push_back("211 "+user->nick+" "+i->nick+"["+i->ident+"@"+i->dhost+"] "+ConvToStr(i->eh.getSendQSize())+" "+ConvToStr(i->cmds_out)+" "+ConvToStr(i->bytes_out)+" "+ConvToStr(i->cmds_in)+" "+ConvToStr(i->bytes_in)+" "+ConvToStr(ServerInstance->Time() - i->age));
347 /* stats L (show user I/O stats with IP addresses) */
349 results.push_back("211 "+user->nick+" :nick[ident@ip] sendq cmds_out bytes_out cmds_in bytes_in time_open");
350 for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
353 results.push_back("211 "+user->nick+" "+i->nick+"["+i->ident+"@"+i->GetIPString()+"] "+ConvToStr(i->eh.getSendQSize())+" "+ConvToStr(i->cmds_out)+" "+ConvToStr(i->bytes_out)+" "+ConvToStr(i->cmds_in)+" "+ConvToStr(i->bytes_in)+" "+ConvToStr(ServerInstance->Time() - i->age));
357 /* stats u (show server uptime) */
360 time_t current_time = 0;
361 current_time = ServerInstance->Time();
362 time_t server_uptime = current_time - ServerInstance->startup_time;
364 stime = gmtime(&server_uptime);
365 /* i dont know who the hell would have an ircd running for over a year nonstop, but
366 * Craig suggested this, and it seemed a good idea so in it went */
367 if (stime->tm_year > 70)
369 results.push_back(InspIRCd::Format("242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",
370 user->nick.c_str(), stime->tm_year - 70, stime->tm_yday, stime->tm_hour,
371 stime->tm_min, stime->tm_sec));
375 results.push_back(InspIRCd::Format("242 %s :Server up %d days, %.2d:%.2d:%.2d",
376 user->nick.c_str(), stime->tm_yday, stime->tm_hour, stime->tm_min,
386 results.push_back("219 "+user->nick+" "+statschar+" :End of /STATS report");
387 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
388 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
392 CmdResult CommandStats::Handle (const std::vector<std::string>& parameters, User *user)
394 if (parameters.size() > 1 && parameters[1] != ServerInstance->Config->ServerName)
397 char search = parameters[0][0];
398 DoStats(search, user, values);
400 const std::string p = ":" + ServerInstance->Config->ServerName + " ";
401 for (size_t i = 0; i < values.size(); i++)
402 user->SendText(p + values[i]);
407 COMMAND_INIT(CommandStats)