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