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