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