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