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