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