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