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