]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_stats.cpp
Merge insp20
[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                         for (Commandtable::iterator i = ServerInstance->Parser->cmdlist.begin(); i != ServerInstance->Parser->cmdlist.end(); i++)
193                         {
194                                 if (i->second->use_count)
195                                 {
196                                         /* RPL_STATSCOMMANDS */
197                                         results.push_back("212 "+user->nick+" "+i->second->name+" "+ConvToStr(i->second->use_count));
198                                 }
199                         }
200                 break;
201
202                 /* stats z (debug and memory info) */
203                 case 'z':
204                 {
205                         results.push_back("249 "+user->nick+" :Users: "+ConvToStr(ServerInstance->Users->GetUsers().size()));
206                         results.push_back("249 "+user->nick+" :Channels: "+ConvToStr(ServerInstance->GetChans().size()));
207                         results.push_back("249 "+user->nick+" :Commands: "+ConvToStr(ServerInstance->Parser->cmdlist.size()));
208
209                         float kbitpersec_in, kbitpersec_out, kbitpersec_total;
210                         char kbitpersec_in_s[30], kbitpersec_out_s[30], kbitpersec_total_s[30];
211
212                         SocketEngine::GetStats().GetBandwidth(kbitpersec_in, kbitpersec_out, kbitpersec_total);
213
214                         snprintf(kbitpersec_total_s, 30, "%03.5f", kbitpersec_total);
215                         snprintf(kbitpersec_out_s, 30, "%03.5f", kbitpersec_out);
216                         snprintf(kbitpersec_in_s, 30, "%03.5f", kbitpersec_in);
217
218                         results.push_back("249 "+user->nick+" :Bandwidth total:  "+ConvToStr(kbitpersec_total_s)+" kilobits/sec");
219                         results.push_back("249 "+user->nick+" :Bandwidth out:    "+ConvToStr(kbitpersec_out_s)+" kilobits/sec");
220                         results.push_back("249 "+user->nick+" :Bandwidth in:     "+ConvToStr(kbitpersec_in_s)+" kilobits/sec");
221
222 #ifndef _WIN32
223                         /* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
224                          * Also cuts out some identical code in both branches of the ifndef. -- Om
225                          */
226                         rusage R;
227
228                         /* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
229                         if (!getrusage(RUSAGE_SELF,&R)) /* RUSAGE_SELF */
230                         {
231                                 results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
232                                 results.push_back("249 "+user->nick+" :Signals:          "+ConvToStr(R.ru_nsignals));
233                                 results.push_back("249 "+user->nick+" :Page faults:      "+ConvToStr(R.ru_majflt));
234                                 results.push_back("249 "+user->nick+" :Swaps:            "+ConvToStr(R.ru_nswap));
235                                 results.push_back("249 "+user->nick+" :Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));
236
237                                 char percent[30];
238
239                                 float n_elapsed = (ServerInstance->Time() - ServerInstance->stats->LastSampled.tv_sec) * 1000000
240                                         + (ServerInstance->Time_ns() - ServerInstance->stats->LastSampled.tv_nsec) / 1000;
241                                 float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats->LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats->LastCPU.tv_usec);
242                                 float per = (n_eaten / n_elapsed) * 100;
243
244                                 snprintf(percent, 30, "%03.5f%%", per);
245                                 results.push_back("249 "+user->nick+" :CPU Use (now):    "+percent);
246
247                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
248                                 n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
249                                 per = (n_eaten / n_elapsed) * 100;
250                                 snprintf(percent, 30, "%03.5f%%", per);
251                                 results.push_back("249 "+user->nick+" :CPU Use (total):  "+percent);
252                         }
253 #else
254                         PROCESS_MEMORY_COUNTERS MemCounters;
255                         if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
256                         {
257                                 results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
258                                 results.push_back("249 "+user->nick+" :Pagefile usage:   "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
259                                 results.push_back("249 "+user->nick+" :Page faults:      "+ConvToStr(MemCounters.PageFaultCount));
260                         }
261
262                         FILETIME CreationTime;
263                         FILETIME ExitTime;
264                         FILETIME KernelTime;
265                         FILETIME UserTime;
266                         LARGE_INTEGER ThisSample;
267                         if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
268                                 QueryPerformanceCounter(&ThisSample))
269                         {
270                                 KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
271                                 KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
272                                 double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats->LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats->LastCPU.dwLowDateTime) )/100000;
273                                 double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats->LastSampled.QuadPart) / ServerInstance->stats->QPFrequency.QuadPart;
274                                 double per = (n_eaten/n_elapsed);
275
276                                 char percent[30];
277
278                                 snprintf(percent, 30, "%03.5f%%", per);
279                                 results.push_back("249 "+user->nick+" :CPU Use (now):    "+percent);
280
281                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
282                                 n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
283                                 per = (n_eaten / n_elapsed);
284                                 snprintf(percent, 30, "%03.5f%%", per);
285                                 results.push_back("249 "+user->nick+" :CPU Use (total):  "+percent);
286                         }
287 #endif
288                 }
289                 break;
290
291                 case 'T':
292                 {
293                         results.push_back("249 "+user->nick+" :accepts "+ConvToStr(ServerInstance->stats->statsAccept)+" refused "+ConvToStr(ServerInstance->stats->statsRefused));
294                         results.push_back("249 "+user->nick+" :unknown commands "+ConvToStr(ServerInstance->stats->statsUnknown));
295                         results.push_back("249 "+user->nick+" :nick collisions "+ConvToStr(ServerInstance->stats->statsCollisions));
296                         results.push_back("249 "+user->nick+" :dns requests "+ConvToStr(ServerInstance->stats->statsDnsGood+ServerInstance->stats->statsDnsBad)+" succeeded "+ConvToStr(ServerInstance->stats->statsDnsGood)+" failed "+ConvToStr(ServerInstance->stats->statsDnsBad));
297                         results.push_back("249 "+user->nick+" :connection count "+ConvToStr(ServerInstance->stats->statsConnects));
298                         results.push_back(InspIRCd::Format("249 %s :bytes sent %5.2fK recv %5.2fK", user->nick.c_str(),
299                                 ServerInstance->stats->statsSent / 1024.0, ServerInstance->stats->statsRecv / 1024.0));
300                 }
301                 break;
302
303                 /* stats o */
304                 case 'o':
305                 {
306                         ConfigTagList tags = ServerInstance->Config->ConfTags("oper");
307                         for(ConfigIter i = tags.first; i != tags.second; ++i)
308                         {
309                                 ConfigTag* tag = i->second;
310                                 results.push_back("243 "+user->nick+" O "+tag->getString("host")+" * "+
311                                         tag->getString("name") + " " + tag->getString("type")+" 0");
312                         }
313                 }
314                 break;
315                 case 'O':
316                 {
317                         for (OperIndex::const_iterator i = ServerInstance->Config->OperTypes.begin(); i != ServerInstance->Config->OperTypes.end(); ++i)
318                         {
319                                 OperInfo* tag = i->second;
320                                 tag->init();
321                                 std::string umodes;
322                                 std::string cmodes;
323                                 for(char c='A'; c < 'z'; c++)
324                                 {
325                                         ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
326                                         if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
327                                                 umodes.push_back(c);
328                                         mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
329                                         if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
330                                                 cmodes.push_back(c);
331                                 }
332                                 results.push_back("243 "+user->nick+" O "+tag->name.c_str() + " " + umodes + " " + cmodes);
333                         }
334                 }
335                 break;
336
337                 /* stats l (show user I/O stats) */
338                 case 'l':
339                         results.push_back("211 "+user->nick+" :nick[ident@host] sendq cmds_out bytes_out cmds_in bytes_in time_open");
340                         for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
341                         {
342                                 LocalUser* i = *n;
343                                 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));
344                         }
345                 break;
346
347                 /* stats L (show user I/O stats with IP addresses) */
348                 case 'L':
349                         results.push_back("211 "+user->nick+" :nick[ident@ip] sendq cmds_out bytes_out cmds_in bytes_in time_open");
350                         for (LocalUserList::iterator n = ServerInstance->Users->local_users.begin(); n != ServerInstance->Users->local_users.end(); n++)
351                         {
352                                 LocalUser* i = *n;
353                                 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));
354                         }
355                 break;
356
357                 /* stats u (show server uptime) */
358                 case 'u':
359                 {
360                         time_t current_time = 0;
361                         current_time = ServerInstance->Time();
362                         time_t server_uptime = current_time - ServerInstance->startup_time;
363                         struct tm* stime;
364                         stime = gmtime(&server_uptime);
365                         /* i dont know who the hell would have an ircd running for over a year nonstop, but
366                          * Craig suggested this, and it seemed a good idea so in it went */
367                         if (stime->tm_year > 70)
368                         {
369                                 results.push_back(InspIRCd::Format("242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",
370                                         user->nick.c_str(), stime->tm_year - 70, stime->tm_yday, stime->tm_hour,
371                                         stime->tm_min, stime->tm_sec));
372                         }
373                         else
374                         {
375                                 results.push_back(InspIRCd::Format("242 %s :Server up %d days, %.2d:%.2d:%.2d",
376                                         user->nick.c_str(), stime->tm_yday, stime->tm_hour, stime->tm_min,
377                                         stime->tm_sec));
378                         }
379                 }
380                 break;
381
382                 default:
383                 break;
384         }
385
386         results.push_back("219 "+user->nick+" "+statschar+" :End of /STATS report");
387         ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
388                 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
389         return;
390 }
391
392 CmdResult CommandStats::Handle (const std::vector<std::string>& parameters, User *user)
393 {
394         if (parameters.size() > 1 && parameters[1] != ServerInstance->Config->ServerName)
395                 return CMD_SUCCESS;
396         string_list values;
397         char search = parameters[0][0];
398         DoStats(search, user, values);
399
400         const std::string p = ":" + ServerInstance->Config->ServerName + " ";
401         for (size_t i = 0; i < values.size(); i++)
402                 user->SendText(p + values[i]);
403
404         return CMD_SUCCESS;
405 }
406
407 COMMAND_INIT(CommandStats)