]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/commands/cmd_stats.cpp
d547635ed37968e1931e520fad687eba0de64a3b
[user/henk/code/inspircd.git] / src / commands / cmd_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 #include "commands/cmd_whowas.h"
25
26 #ifdef _WIN32
27 #include <psapi.h>
28 #pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
29 #endif
30
31 /** Handle /STATS. These command handlers can be reloaded by the core,
32  * and handle basic RFC1459 commands. Commands within modules work
33  * the same way, however, they can be fully unloaded, where these
34  * may not.
35  */
36 class CommandStats : public Command
37 {
38         void DoStats(char statschar, User* user, string_list &results);
39  public:
40         /** Constructor for stats.
41          */
42         CommandStats ( Module* parent) : Command(parent,"STATS",1,2) { syntax = "<stats-symbol> [<servername>]"; }
43         /** Handle command.
44          * @param parameters The parameters to the comamnd
45          * @param pcnt The number of parameters passed to teh command
46          * @param user The user issuing the command
47          * @return A value from CmdResult to indicate command success or failure.
48          */
49         CmdResult Handle(const std::vector<std::string>& parameters, User *user);
50         RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters)
51         {
52                 if (parameters.size() > 1)
53                         return ROUTE_UNICAST(parameters[1]);
54                 return ROUTE_LOCALONLY;
55         }
56 };
57
58 void CommandStats::DoStats(char statschar, User* user, string_list &results)
59 {
60         std::string sn(ServerInstance->Config->ServerName);
61
62         bool isPublic = ServerInstance->Config->UserStats.find(statschar) != std::string::npos;
63         bool isRemoteOper = IS_REMOTE(user) && IS_OPER(user);
64         bool isLocalOperWithPrivs = IS_LOCAL(user) && user->HasPrivPermission("servers/auspex");
65
66         if (!isPublic && !isRemoteOper && !isLocalOperWithPrivs)
67         {
68                 ServerInstance->SNO->WriteToSnoMask('t',
69                                 "%s '%c' denied for %s (%s@%s)",
70                                 (IS_LOCAL(user) ? "Stats" : "Remote stats"),
71                                 statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
72                 results.push_back(sn + " 481 " + user->nick + " :Permission denied - STATS " + statschar + " requires the servers/auspex priv.");
73                 return;
74         }
75
76         ModResult MOD_RESULT;
77         FIRST_MOD_RESULT(OnStats, MOD_RESULT, (statschar, user, results));
78         if (MOD_RESULT == MOD_RES_DENY)
79         {
80                 results.push_back(sn+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
81                 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
82                         (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
83                 return;
84         }
85
86         switch (statschar)
87         {
88                 /* stats p (show listening ports) */
89                 case 'p':
90                 {
91                         for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i)
92                         {
93                                 ListenSocket* ls = *i;
94                                 std::string ip = ls->bind_addr;
95                                 if (ip.empty())
96                                         ip.assign("*");
97                                 std::string type = ls->bind_tag->getString("type", "clients");
98                                 std::string hook = ls->bind_tag->getString("ssl", "plaintext");
99
100                                 results.push_back(sn+" 249 "+user->nick+" :"+ ip + ":"+ConvToStr(ls->bind_port)+
101                                         " (" + type + ", " + hook + ")");
102                         }
103                 }
104                 break;
105
106                 /* These stats symbols must be handled by a linking module */
107                 case 'n':
108                 case 'c':
109                 break;
110
111                 case 'i':
112                 {
113                         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
114                         {
115                                 ConnectClass* c = *i;
116                                 std::stringstream res;
117                                 res << sn << " 215 " << user->nick << " I " << c->name << ' ';
118                                 if (c->type == CC_ALLOW)
119                                         res << '+';
120                                 if (c->type == CC_DENY)
121                                         res << '-';
122
123                                 if (c->type == CC_NAMED)
124                                         res << '*';
125                                 else
126                                         res << c->host;
127
128                                 res << ' ' << c->config->getString("port", "*") << ' ';
129
130                                 res << c->GetRecvqMax() << ' ' << c->GetSendqSoftMax() << ' ' << c->GetSendqHardMax()
131                                         << ' ' << c->GetCommandRate() << ' ' << c->GetPenaltyThreshold();
132                                 if (c->fakelag)
133                                         res << '*';
134                                 results.push_back(res.str());
135                         }
136                 }
137                 break;
138
139                 case 'Y':
140                 {
141                         int idx = 0;
142                         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
143                         {
144                                 ConnectClass* c = *i;
145                                 results.push_back(sn+" 215 "+user->nick+" i NOMATCH * "+c->GetHost()+" "+ConvToStr(c->limit ? c->limit : ServerInstance->SE->GetMaxFds())+" "+ConvToStr(idx)+" "+ServerInstance->Config->ServerName+" *");
146                                 results.push_back(sn+" 218 "+user->nick+" Y "+ConvToStr(idx)+" "+ConvToStr(c->GetPingTime())+" 0 "+ConvToStr(c->GetSendqHardMax())+" :"+
147                                                 ConvToStr(c->GetRecvqMax())+" "+ConvToStr(c->GetRegTimeout()));
148                                 idx++;
149                         }
150                 }
151                 break;
152
153                 case 'U':
154                 {
155                         for(std::map<irc::string, bool>::iterator i = ServerInstance->Config->ulines.begin(); i != ServerInstance->Config->ulines.end(); ++i)
156                         {
157                                 results.push_back(sn+" 248 "+user->nick+" U "+std::string(i->first.c_str()));
158                         }
159                 }
160                 break;
161
162                 case 'P':
163                 {
164                         unsigned int idx = 0;
165                         for (std::list<User*>::const_iterator i = ServerInstance->Users->all_opers.begin(); i != ServerInstance->Users->all_opers.end(); ++i)
166                         {
167                                 User* oper = *i;
168                                 if (!ServerInstance->ULine(oper->server))
169                                 {
170                                         results.push_back(sn+" 249 " + user->nick + " :" + oper->nick + " (" + oper->ident + "@" + oper->dhost + ") Idle: " +
171                                                         (IS_LOCAL(oper) ? ConvToStr(ServerInstance->Time() - oper->idle_lastmsg) + " secs" : "unavailable"));
172                                         idx++;
173                                 }
174                         }
175                         results.push_back(sn+" 249 "+user->nick+" :"+ConvToStr(idx)+" OPER(s)");
176                 }
177                 break;
178
179                 case 'k':
180                         ServerInstance->XLines->InvokeStats("K",216,user,results);
181                 break;
182                 case 'g':
183                         ServerInstance->XLines->InvokeStats("G",223,user,results);
184                 break;
185                 case 'q':
186                         ServerInstance->XLines->InvokeStats("Q",217,user,results);
187                 break;
188                 case 'Z':
189                         ServerInstance->XLines->InvokeStats("Z",223,user,results);
190                 break;
191                 case 'e':
192                         ServerInstance->XLines->InvokeStats("E",223,user,results);
193                 break;
194                 case 'E':
195                         results.push_back(sn+" 249 "+user->nick+" :Total events: "+ConvToStr(ServerInstance->SE->TotalEvents));
196                         results.push_back(sn+" 249 "+user->nick+" :Read events:  "+ConvToStr(ServerInstance->SE->ReadEvents));
197                         results.push_back(sn+" 249 "+user->nick+" :Write events: "+ConvToStr(ServerInstance->SE->WriteEvents));
198                         results.push_back(sn+" 249 "+user->nick+" :Error events: "+ConvToStr(ServerInstance->SE->ErrorEvents));
199                 break;
200
201                 /* stats m (list number of times each command has been used, plus bytecount) */
202                 case 'm':
203                         for (Commandtable::iterator i = ServerInstance->Parser->cmdlist.begin(); i != ServerInstance->Parser->cmdlist.end(); i++)
204                         {
205                                 if (i->second->use_count)
206                                 {
207                                         /* RPL_STATSCOMMANDS */
208                                         results.push_back(sn+" 212 "+user->nick+" "+i->second->name+" "+ConvToStr(i->second->use_count)+" "+ConvToStr(i->second->total_bytes));
209                                 }
210                         }
211                 break;
212
213                 /* stats z (debug and memory info) */
214                 case 'z':
215                 {
216                         results.push_back(sn+" 249 "+user->nick+" :Users: "+ConvToStr(ServerInstance->Users->clientlist->size()));
217                         results.push_back(sn+" 249 "+user->nick+" :Channels: "+ConvToStr(ServerInstance->chanlist->size()));
218                         results.push_back(sn+" 249 "+user->nick+" :Commands: "+ConvToStr(ServerInstance->Parser->cmdlist.size()));
219
220                         if (ServerInstance->Config->WhoWasGroupSize && ServerInstance->Config->WhoWasMaxGroups)
221                         {
222                                 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
223                                 if (whowas)
224                                 {
225                                         WhowasRequest req(NULL, whowas, WhowasRequest::WHOWAS_STATS);
226                                         req.user = user;
227                                         req.Send();
228                                         results.push_back(sn+" 249 "+user->nick+" :"+req.value);
229                                 }
230                         }
231
232                         float kbitpersec_in, kbitpersec_out, kbitpersec_total;
233                         char kbitpersec_in_s[30], kbitpersec_out_s[30], kbitpersec_total_s[30];
234
235                         ServerInstance->SE->GetStats(kbitpersec_in, kbitpersec_out, kbitpersec_total);
236
237                         snprintf(kbitpersec_total_s, 30, "%03.5f", kbitpersec_total);
238                         snprintf(kbitpersec_out_s, 30, "%03.5f", kbitpersec_out);
239                         snprintf(kbitpersec_in_s, 30, "%03.5f", kbitpersec_in);
240
241                         results.push_back(sn+" 249 "+user->nick+" :Bandwidth total:  "+ConvToStr(kbitpersec_total_s)+" kilobits/sec");
242                         results.push_back(sn+" 249 "+user->nick+" :Bandwidth out:    "+ConvToStr(kbitpersec_out_s)+" kilobits/sec");
243                         results.push_back(sn+" 249 "+user->nick+" :Bandwidth in:     "+ConvToStr(kbitpersec_in_s)+" kilobits/sec");
244
245 #ifndef _WIN32
246                         /* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
247                          * Also cuts out some identical code in both branches of the ifndef. -- Om
248                          */
249                         rusage R;
250
251                         /* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
252                         if (!getrusage(RUSAGE_SELF,&R)) /* RUSAGE_SELF */
253                         {
254                                 results.push_back(sn+" 249 "+user->nick+" :Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
255                                 results.push_back(sn+" 249 "+user->nick+" :Signals:          "+ConvToStr(R.ru_nsignals));
256                                 results.push_back(sn+" 249 "+user->nick+" :Page faults:      "+ConvToStr(R.ru_majflt));
257                                 results.push_back(sn+" 249 "+user->nick+" :Swaps:            "+ConvToStr(R.ru_nswap));
258                                 results.push_back(sn+" 249 "+user->nick+" :Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));
259
260                                 char percent[30];
261
262                                 float n_elapsed = (ServerInstance->Time() - ServerInstance->stats->LastSampled.tv_sec) * 1000000
263                                         + (ServerInstance->Time_ns() - ServerInstance->stats->LastSampled.tv_nsec) / 1000;
264                                 float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats->LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats->LastCPU.tv_usec);
265                                 float per = (n_eaten / n_elapsed) * 100;
266
267                                 snprintf(percent, 30, "%03.5f%%", per);
268                                 results.push_back(sn+" 249 "+user->nick+" :CPU Use (now):    "+percent);
269
270                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
271                                 n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
272                                 per = (n_eaten / n_elapsed) * 100;
273                                 snprintf(percent, 30, "%03.5f%%", per);
274                                 results.push_back(sn+" 249 "+user->nick+" :CPU Use (total):  "+percent);
275                         }
276 #else
277                         PROCESS_MEMORY_COUNTERS MemCounters;
278                         if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
279                         {
280                                 results.push_back(sn+" 249 "+user->nick+" :Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
281                                 results.push_back(sn+" 249 "+user->nick+" :Pagefile usage:   "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
282                                 results.push_back(sn+" 249 "+user->nick+" :Page faults:      "+ConvToStr(MemCounters.PageFaultCount));
283                         }
284
285                         FILETIME CreationTime;
286                 FILETIME ExitTime;
287                 FILETIME KernelTime;
288                 FILETIME UserTime;
289                         LARGE_INTEGER ThisSample;
290                         if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
291                                 QueryPerformanceCounter(&ThisSample))
292                         {
293                                 KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
294                                 KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
295                                 double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats->LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats->LastCPU.dwLowDateTime) )/100000;
296                                 double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats->LastSampled.QuadPart) / ServerInstance->stats->QPFrequency.QuadPart;
297                                 double per = (n_eaten/n_elapsed);
298                                 
299                                 char percent[30];
300
301                                 snprintf(percent, 30, "%03.5f%%", per);
302                                 results.push_back(sn+" 249 "+user->nick+" :CPU Use (now):    "+percent);
303
304                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
305                                 n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
306                                 per = (n_eaten / n_elapsed);
307                                 snprintf(percent, 30, "%03.5f%%", per);
308                                 results.push_back(sn+" 249 "+user->nick+" :CPU Use (total):  "+percent);
309                         }
310 #endif
311                 }
312                 break;
313
314                 case 'T':
315                 {
316                         char buffer[MAXBUF];
317                         results.push_back(sn+" 249 "+user->nick+" :accepts "+ConvToStr(ServerInstance->stats->statsAccept)+" refused "+ConvToStr(ServerInstance->stats->statsRefused));
318                         results.push_back(sn+" 249 "+user->nick+" :unknown commands "+ConvToStr(ServerInstance->stats->statsUnknown));
319                         results.push_back(sn+" 249 "+user->nick+" :nick collisions "+ConvToStr(ServerInstance->stats->statsCollisions));
320                         results.push_back(sn+" 249 "+user->nick+" :dns requests "+ConvToStr(ServerInstance->stats->statsDnsGood+ServerInstance->stats->statsDnsBad)+" succeeded "+ConvToStr(ServerInstance->stats->statsDnsGood)+" failed "+ConvToStr(ServerInstance->stats->statsDnsBad));
321                         results.push_back(sn+" 249 "+user->nick+" :connection count "+ConvToStr(ServerInstance->stats->statsConnects));
322                         snprintf(buffer,MAXBUF," 249 %s :bytes sent %5.2fK recv %5.2fK",
323                                 user->nick.c_str(),ServerInstance->stats->statsSent / 1024.0,ServerInstance->stats->statsRecv / 1024.0);
324                         results.push_back(sn+buffer);
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                                 results.push_back(sn+" 243 "+user->nick+" O "+tag->getString("host")+" * "+
336                                         tag->getString("name") + " " + tag->getString("type")+" 0");
337                         }
338                 }
339                 break;
340                 case 'O':
341                 {
342                         for(OperIndex::iterator i = ServerInstance->Config->oper_blocks.begin(); i != ServerInstance->Config->oper_blocks.end(); i++)
343                         {
344                                 // just the types, not the actual oper blocks...
345                                 if (i->first[0] != ' ')
346                                         continue;
347                                 OperInfo* tag = i->second;
348                                 tag->init();
349                                 std::string umodes;
350                                 std::string cmodes;
351                                 for(char c='A'; c <= 'z'; c++)
352                                 {
353                                         ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
354                                         if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
355                                                 umodes.push_back(c);
356                                         mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
357                                         if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
358                                                 cmodes.push_back(c);
359                                 }
360                                 results.push_back(sn+" 243 "+user->nick+" O "+tag->NameStr() + " " + umodes + " " + cmodes);
361                         }
362                 }
363                 break;
364
365                 /* stats l (show user I/O stats) */
366                 case 'l':
367                         results.push_back(sn+" 211 "+user->nick+" :nick[ident@host] sendq cmds_out bytes_out cmds_in bytes_in time_open");
368                         for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
369                         {
370                                 LocalUser* i = *n;
371                                 results.push_back(sn+" 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->signon));
372                         }
373                 break;
374
375                 /* stats L (show user I/O stats with IP addresses) */
376                 case 'L':
377                         results.push_back(sn+" 211 "+user->nick+" :nick[ident@ip] sendq cmds_out bytes_out cmds_in bytes_in time_open");
378                         for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
379                         {
380                                 LocalUser* i = *n;
381                                 results.push_back(sn+" 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->signon));
382                         }
383                 break;
384
385                 /* stats u (show server uptime) */
386                 case 'u':
387                 {
388                         time_t current_time = 0;
389                         current_time = ServerInstance->Time();
390                         time_t server_uptime = current_time - ServerInstance->startup_time;
391                         struct tm* stime;
392                         stime = gmtime(&server_uptime);
393                         /* i dont know who the hell would have an ircd running for over a year nonstop, but
394                          * Craig suggested this, and it seemed a good idea so in it went */
395                         if (stime->tm_year > 70)
396                         {
397                                 char buffer[MAXBUF];
398                                 snprintf(buffer,MAXBUF," 242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick.c_str(),(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
399                                 results.push_back(sn+buffer);
400                         }
401                         else
402                         {
403                                 char buffer[MAXBUF];
404                                 snprintf(buffer,MAXBUF," 242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick.c_str(),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
405                                 results.push_back(sn+buffer);
406                         }
407                 }
408                 break;
409
410                 default:
411                 break;
412         }
413
414         results.push_back(sn+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
415         ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
416                 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
417         return;
418 }
419
420 CmdResult CommandStats::Handle (const std::vector<std::string>& parameters, User *user)
421 {
422         if (parameters.size() > 1 && parameters[1] != ServerInstance->Config->ServerName)
423         {
424                 // Give extra penalty if a non-oper does /STATS <remoteserver>
425                 LocalUser* localuser = IS_LOCAL(user);
426                 if ((localuser) && (!IS_OPER(user)))
427                         localuser->CommandFloodPenalty += 2000;
428                 return CMD_SUCCESS;
429         }
430         string_list values;
431         char search = parameters[0][0];
432         DoStats(search, user, values);
433         for (size_t i = 0; i < values.size(); i++)
434                 user->SendText(":%s", values[i].c_str());
435
436         return CMD_SUCCESS;
437 }
438
439 COMMAND_INIT(CommandStats)