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