]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_stats.cpp
Use CommandBase::Params instead of std::vector<std::string>.
[user/henk/code/inspircd.git] / src / coremods / core_stats.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
7  *
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.
11  *
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
15  * details.
16  *
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/>.
19  */
20
21
22 #include "inspircd.h"
23 #include "xline.h"
24 #include "modules/stats.h"
25
26 #ifdef _WIN32
27 #include <psapi.h>
28 #pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
29 #endif
30
31 /** Handle /STATS.
32  */
33 class CommandStats : public Command
34 {
35         Events::ModuleEventProvider statsevprov;
36         void DoStats(Stats::Context& stats);
37
38  public:
39         /** Constructor for stats.
40          */
41         CommandStats(Module* Creator)
42                 : Command(Creator, "STATS", 1, 2)
43                 , statsevprov(Creator, "event/stats")
44         {
45                 allow_empty_last_param = false;
46                 syntax = "<stats-symbol> [<servername>]";
47         }
48
49         /** Handle command.
50          * @param parameters The parameters to the command
51          * @param user The user issuing the command
52          * @return A value from CmdResult to indicate command success or failure.
53          */
54         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE;
55         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
56         {
57                 if ((parameters.size() > 1) && (parameters[1].find('.') != std::string::npos))
58                         return ROUTE_UNICAST(parameters[1]);
59                 return ROUTE_LOCALONLY;
60         }
61 };
62
63 static void GenerateStatsLl(Stats::Context& stats)
64 {
65         stats.AddRow(211, InspIRCd::Format("nick[ident@%s] sendq cmds_out bytes_out cmds_in bytes_in time_open", (stats.GetSymbol() == 'l' ? "host" : "ip")));
66
67         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
68         for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
69         {
70                 LocalUser* u = *i;
71                 stats.AddRow(211, u->nick+"["+u->ident+"@"+(stats.GetSymbol() == 'l' ? u->GetDisplayedHost() : u->GetIPString())+"] "+ConvToStr(u->eh.getSendQSize())+" "+ConvToStr(u->cmds_out)+" "+ConvToStr(u->bytes_out)+" "+ConvToStr(u->cmds_in)+" "+ConvToStr(u->bytes_in)+" "+ConvToStr(ServerInstance->Time() - u->signon));
72         }
73 }
74
75 void CommandStats::DoStats(Stats::Context& stats)
76 {
77         User* const user = stats.GetSource();
78         const char statschar = stats.GetSymbol();
79
80         bool isPublic = ServerInstance->Config->UserStats.find(statschar) != std::string::npos;
81         bool isRemoteOper = IS_REMOTE(user) && (user->IsOper());
82         bool isLocalOperWithPrivs = IS_LOCAL(user) && user->HasPrivPermission("servers/auspex");
83
84         if (!isPublic && !isRemoteOper && !isLocalOperWithPrivs)
85         {
86                 ServerInstance->SNO->WriteToSnoMask('t',
87                                 "%s '%c' denied for %s (%s@%s)",
88                                 (IS_LOCAL(user) ? "Stats" : "Remote stats"),
89                                 statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
90                 stats.AddRow(481, (std::string("Permission Denied - STATS ") + statschar + " requires the servers/auspex priv."));
91                 return;
92         }
93
94         ModResult MOD_RESULT;
95         FIRST_MOD_RESULT_CUSTOM(statsevprov, Stats::EventListener, OnStats, MOD_RESULT, (stats));
96         if (MOD_RESULT == MOD_RES_DENY)
97         {
98                 stats.AddRow(219, statschar, "End of /STATS report");
99                 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
100                         (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
101                 return;
102         }
103
104         switch (statschar)
105         {
106                 /* stats p (show listening ports) */
107                 case 'p':
108                 {
109                         for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i)
110                         {
111                                 ListenSocket* ls = *i;
112                                 std::string type = ls->bind_tag->getString("type", "clients");
113                                 std::string hook = ls->bind_tag->getString("ssl", "plaintext");
114
115                                 stats.AddRow(249, ls->bind_sa.str() + " (" + type + ", " + hook + ")");
116                         }
117                 }
118                 break;
119
120                 /* These stats symbols must be handled by a linking module */
121                 case 'n':
122                 case 'c':
123                 break;
124
125                 case 'i':
126                 {
127                         for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
128                         {
129                                 ConnectClass* c = *i;
130                                 Stats::Row row(215);
131                                 row.push("I").push(c->name);
132
133                                 std::string param;
134                                 if (c->type == CC_ALLOW)
135                                         param.push_back('+');
136                                 if (c->type == CC_DENY)
137                                         param.push_back('-');
138
139                                 if (c->type == CC_NAMED)
140                                         param.push_back('*');
141                                 else
142                                         param.append(c->host);
143
144                                 row.push(param).push(c->config->getString("port", "*"));
145                                 row.push(ConvToStr(c->GetRecvqMax())).push(ConvToStr(c->GetSendqSoftMax())).push(ConvToStr(c->GetSendqHardMax())).push(ConvToStr(c->GetCommandRate()));
146
147                                 param = ConvToStr(c->GetPenaltyThreshold());
148                                 if (c->fakelag)
149                                         param.push_back('*');
150                                 row.push(param);
151
152                                 stats.AddRow(row);
153                         }
154                 }
155                 break;
156
157                 case 'Y':
158                 {
159                         int idx = 0;
160                         for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
161                         {
162                                 ConnectClass* c = *i;
163                                 stats.AddRow(215, 'i', "NOMATCH", '*', c->GetHost(), (c->limit ? c->limit : SocketEngine::GetMaxFds()), idx, ServerInstance->Config->ServerName, '*');
164                                 stats.AddRow(218, 'Y', idx, c->GetPingTime(), '0', c->GetSendqHardMax(), ConvToStr(c->GetRecvqMax())+" "+ConvToStr(c->GetRegTimeout()));
165                                 idx++;
166                         }
167                 }
168                 break;
169
170                 case 'P':
171                 {
172                         unsigned int idx = 0;
173                         const UserManager::OperList& opers = ServerInstance->Users->all_opers;
174                         for (UserManager::OperList::const_iterator i = opers.begin(); i != opers.end(); ++i)
175                         {
176                                 User* oper = *i;
177                                 if (!oper->server->IsULine())
178                                 {
179                                         LocalUser* lu = IS_LOCAL(oper);
180                                         stats.AddRow(249, oper->nick + " (" + oper->ident + "@" + oper->GetDisplayedHost() + ") Idle: " +
181                                                         (lu ? ConvToStr(ServerInstance->Time() - lu->idle_lastmsg) + " secs" : "unavailable"));
182                                         idx++;
183                                 }
184                         }
185                         stats.AddRow(249, ConvToStr(idx)+" OPER(s)");
186                 }
187                 break;
188
189                 case 'k':
190                         ServerInstance->XLines->InvokeStats("K",216,stats);
191                 break;
192                 case 'g':
193                         ServerInstance->XLines->InvokeStats("G",223,stats);
194                 break;
195                 case 'q':
196                         ServerInstance->XLines->InvokeStats("Q",217,stats);
197                 break;
198                 case 'Z':
199                         ServerInstance->XLines->InvokeStats("Z",223,stats);
200                 break;
201                 case 'e':
202                         ServerInstance->XLines->InvokeStats("E",223,stats);
203                 break;
204                 case 'E':
205                 {
206                         const SocketEngine::Statistics& sestats = SocketEngine::GetStats();
207                         stats.AddRow(249, "Total events: "+ConvToStr(sestats.TotalEvents));
208                         stats.AddRow(249, "Read events:  "+ConvToStr(sestats.ReadEvents));
209                         stats.AddRow(249, "Write events: "+ConvToStr(sestats.WriteEvents));
210                         stats.AddRow(249, "Error events: "+ConvToStr(sestats.ErrorEvents));
211                         break;
212                 }
213
214                 /* stats m (list number of times each command has been used, plus bytecount) */
215                 case 'm':
216                 {
217                         const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
218                         for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
219                         {
220                                 if (i->second->use_count)
221                                 {
222                                         /* RPL_STATSCOMMANDS */
223                                         stats.AddRow(212, i->second->name, i->second->use_count);
224                                 }
225                         }
226                 }
227                 break;
228
229                 /* stats z (debug and memory info) */
230                 case 'z':
231                 {
232                         stats.AddRow(249, "Users: "+ConvToStr(ServerInstance->Users->GetUsers().size()));
233                         stats.AddRow(249, "Channels: "+ConvToStr(ServerInstance->GetChans().size()));
234                         stats.AddRow(249, "Commands: "+ConvToStr(ServerInstance->Parser.GetCommands().size()));
235
236                         float kbitpersec_in, kbitpersec_out, kbitpersec_total;
237                         SocketEngine::GetStats().GetBandwidth(kbitpersec_in, kbitpersec_out, kbitpersec_total);
238
239                         stats.AddRow(249, InspIRCd::Format("Bandwidth total:  %03.5f kilobits/sec", kbitpersec_total));
240                         stats.AddRow(249, InspIRCd::Format("Bandwidth out:    %03.5f kilobits/sec", kbitpersec_out));
241                         stats.AddRow(249, InspIRCd::Format("Bandwidth in:     %03.5f kilobits/sec", kbitpersec_in));
242
243 #ifndef _WIN32
244                         /* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
245                          * Also cuts out some identical code in both branches of the ifndef. -- Om
246                          */
247                         rusage R;
248
249                         /* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
250                         if (!getrusage(RUSAGE_SELF,&R)) /* RUSAGE_SELF */
251                         {
252 #ifndef __HAIKU__
253                                 stats.AddRow(249, "Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
254                                 stats.AddRow(249, "Signals:          "+ConvToStr(R.ru_nsignals));
255                                 stats.AddRow(249, "Page faults:      "+ConvToStr(R.ru_majflt));
256                                 stats.AddRow(249, "Swaps:            "+ConvToStr(R.ru_nswap));
257                                 stats.AddRow(249, "Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));
258 #endif
259                                 float n_elapsed = (ServerInstance->Time() - ServerInstance->stats.LastSampled.tv_sec) * 1000000
260                                         + (ServerInstance->Time_ns() - ServerInstance->stats.LastSampled.tv_nsec) / 1000;
261                                 float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats.LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats.LastCPU.tv_usec);
262                                 float per = (n_eaten / n_elapsed) * 100;
263
264                                 stats.AddRow(249, InspIRCd::Format("CPU Use (now):    %03.5f%%", per));
265
266                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
267                                 n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
268                                 per = (n_eaten / n_elapsed) * 100;
269
270                                 stats.AddRow(249, InspIRCd::Format("CPU Use (total):  %03.5f%%", per));
271                         }
272 #else
273                         PROCESS_MEMORY_COUNTERS MemCounters;
274                         if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
275                         {
276                                 stats.AddRow(249, "Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
277                                 stats.AddRow(249, "Pagefile usage:   "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
278                                 stats.AddRow(249, "Page faults:      "+ConvToStr(MemCounters.PageFaultCount));
279                         }
280
281                         FILETIME CreationTime;
282                         FILETIME ExitTime;
283                         FILETIME KernelTime;
284                         FILETIME UserTime;
285                         LARGE_INTEGER ThisSample;
286                         if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
287                                 QueryPerformanceCounter(&ThisSample))
288                         {
289                                 KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
290                                 KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
291                                 double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats.LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats.LastCPU.dwLowDateTime) )/100000;
292                                 double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats.LastSampled.QuadPart) / ServerInstance->stats.QPFrequency.QuadPart;
293                                 double per = (n_eaten/n_elapsed);
294
295                                 stats.AddRow(249, InspIRCd::Format("CPU Use (now):    %03.5f%%", per));
296
297                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
298                                 n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
299                                 per = (n_eaten / n_elapsed);
300
301                                 stats.AddRow(249, InspIRCd::Format("CPU Use (total):  %03.5f%%", per));
302                         }
303 #endif
304                 }
305                 break;
306
307                 case 'T':
308                 {
309                         stats.AddRow(249, "accepts "+ConvToStr(ServerInstance->stats.Accept)+" refused "+ConvToStr(ServerInstance->stats.Refused));
310                         stats.AddRow(249, "unknown commands "+ConvToStr(ServerInstance->stats.Unknown));
311                         stats.AddRow(249, "nick collisions "+ConvToStr(ServerInstance->stats.Collisions));
312                         stats.AddRow(249, "dns requests "+ConvToStr(ServerInstance->stats.DnsGood+ServerInstance->stats.DnsBad)+" succeeded "+ConvToStr(ServerInstance->stats.DnsGood)+" failed "+ConvToStr(ServerInstance->stats.DnsBad));
313                         stats.AddRow(249, "connection count "+ConvToStr(ServerInstance->stats.Connects));
314                         stats.AddRow(249, InspIRCd::Format("bytes sent %5.2fK recv %5.2fK",
315                                 ServerInstance->stats.Sent / 1024.0, ServerInstance->stats.Recv / 1024.0));
316                 }
317                 break;
318
319                 /* stats o */
320                 case 'o':
321                 {
322                         for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->oper_blocks.begin(); i != ServerInstance->Config->oper_blocks.end(); ++i)
323                         {
324                                 OperInfo* ifo = i->second;
325                                 ConfigTag* tag = ifo->oper_block;
326                                 stats.AddRow(243, 'O', tag->getString("host"), '*', tag->getString("name"), tag->getString("type"), '0');
327                         }
328                 }
329                 break;
330                 case 'O':
331                 {
332                         for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->OperTypes.begin(); i != ServerInstance->Config->OperTypes.end(); ++i)
333                         {
334                                 OperInfo* tag = i->second;
335                                 tag->init();
336                                 std::string umodes;
337                                 std::string cmodes;
338                                 for(char c='A'; c <= 'z'; c++)
339                                 {
340                                         ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
341                                         if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
342                                                 umodes.push_back(c);
343                                         mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
344                                         if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
345                                                 cmodes.push_back(c);
346                                 }
347                                 stats.AddRow(243, 'O', tag->name, umodes, cmodes);
348                         }
349                 }
350                 break;
351
352                 /* stats l (show user I/O stats) */
353                 case 'l':
354                 /* stats L (show user I/O stats with IP addresses) */
355                 case 'L':
356                         GenerateStatsLl(stats);
357                 break;
358
359                 /* stats u (show server uptime) */
360                 case 'u':
361                 {
362                         unsigned int up = static_cast<unsigned int>(ServerInstance->Time() - ServerInstance->startup_time);
363                         stats.AddRow(242, InspIRCd::Format("Server up %u days, %.2u:%.2u:%.2u",
364                                 up / 86400, (up / 3600) % 24, (up / 60) % 60, up % 60));
365                 }
366                 break;
367
368                 default:
369                 break;
370         }
371
372         stats.AddRow(219, statschar, "End of /STATS report");
373         ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
374                 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
375         return;
376 }
377
378 CmdResult CommandStats::Handle(User* user, const Params& parameters)
379 {
380         if (parameters.size() > 1 && parameters[1] != ServerInstance->Config->ServerName)
381         {
382                 // Give extra penalty if a non-oper does /STATS <remoteserver>
383                 LocalUser* localuser = IS_LOCAL(user);
384                 if ((localuser) && (!user->IsOper()))
385                         localuser->CommandFloodPenalty += 2000;
386                 return CMD_SUCCESS;
387         }
388         Stats::Context stats(user, parameters[0][0]);
389         DoStats(stats);
390         const std::vector<Stats::Row>& rows = stats.GetRows();
391         for (std::vector<Stats::Row>::const_iterator i = rows.begin(); i != rows.end(); ++i)
392         {
393                 const Stats::Row& row = *i;
394                 user->WriteRemoteNumeric(row);
395         }
396
397         return CMD_SUCCESS;
398 }
399
400 COMMAND_INIT(CommandStats)