]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_httpd_stats.cpp
bb4080fd2d2491601a9b425cbe0fafd0553aee62
[user/henk/code/inspircd.git] / src / modules / m_httpd_stats.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "inspircd.h"
25 #include "modules/httpd.h"
26 #include "xline.h"
27
28 namespace Stats
29 {
30         struct Entities
31         {
32                 static const insp::flat_map<char, char const*>& entities;
33         };
34
35         static const insp::flat_map<char, char const*>& init_entities()
36         {
37                 static insp::flat_map<char, char const*> entities;
38                 entities['<'] = "lt";
39                 entities['>'] = "gt";
40                 entities['&'] = "amp";
41                 entities['"'] = "quot";
42                 return entities;
43         }
44
45         const insp::flat_map<char, char const*>& Entities::entities = init_entities();
46
47         std::string Sanitize(const std::string& str)
48         {
49                 std::string ret;
50                 ret.reserve(str.length() * 2);
51
52                 for (std::string::const_iterator x = str.begin(); x != str.end(); ++x)
53                 {
54                         insp::flat_map<char, char const*>::const_iterator it = Entities::entities.find(*x);
55
56                         if (it != Entities::entities.end())
57                         {
58                                 ret += '&';
59                                 ret += it->second;
60                                 ret += ';';
61                         }
62                         else if (*x == 0x09 || *x == 0x0A || *x == 0x0D || ((*x >= 0x20) && (*x <= 0x7e)))
63                         {
64                                 // The XML specification defines the following characters as valid inside an XML document:
65                                 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
66                                 ret += *x;
67                         }
68                         else
69                         {
70                                 // If we reached this point then the string contains characters which can
71                                 // not be represented in XML, even using a numeric escape. Therefore, we
72                                 // Base64 encode the entire string and wrap it in a CDATA.
73                                 ret.clear();
74                                 ret += "<![CDATA[";
75                                 ret += BinToBase64(str);
76                                 ret += "]]>";
77                                 break;
78                         }
79                 }
80                 return ret;
81         }
82
83         void DumpMeta(std::ostream& data, Extensible* ext)
84         {
85                 data << "<metadata>";
86                 for (Extensible::ExtensibleStore::const_iterator i = ext->GetExtList().begin(); i != ext->GetExtList().end(); i++)
87                 {
88                         ExtensionItem* item = i->first;
89                         std::string value = item->ToHuman(ext, i->second);
90                         if (!value.empty())
91                                 data << "<meta name=\"" << item->name << "\">" << Sanitize(value) << "</meta>";
92                         else if (!item->name.empty())
93                                 data << "<meta name=\"" << item->name << "\"/>";
94                 }
95                 data << "</metadata>";
96         }
97
98         std::ostream& ServerInfo(std::ostream& data)
99         {
100                 return data << "<server><name>" << ServerInstance->Config->ServerName << "</name><description>"
101                         << Sanitize(ServerInstance->Config->ServerDesc) << "</description><version>"
102                         << Sanitize(ServerInstance->GetVersionString(true)) << "</version></server>";
103         }
104
105         std::ostream& ISupport(std::ostream& data)
106         {
107                 data << "<isupport>";
108                 const std::vector<Numeric::Numeric>& isupport = ServerInstance->ISupport.GetLines();
109                 for (std::vector<Numeric::Numeric>::const_iterator i = isupport.begin(); i != isupport.end(); ++i)
110                 {
111                         const Numeric::Numeric& num = *i;
112                         for (std::vector<std::string>::const_iterator j = num.GetParams().begin(); j != num.GetParams().end() - 1; ++j)
113                                 data << "<token>" << Sanitize(*j) << "</token>";
114                 }
115                 return data << "</isupport>";
116         }
117
118         std::ostream& General(std::ostream& data)
119         {
120                 data << "<general>";
121                 data << "<usercount>" << ServerInstance->Users->GetUsers().size() << "</usercount>";
122                 data << "<localusercount>" << ServerInstance->Users->GetLocalUsers().size() << "</localusercount>";
123                 data << "<channelcount>" << ServerInstance->GetChans().size() << "</channelcount>";
124                 data << "<opercount>" << ServerInstance->Users->all_opers.size() << "</opercount>";
125                 data << "<socketcount>" << (SocketEngine::GetUsedFds()) << "</socketcount><socketmax>" << SocketEngine::GetMaxFds() << "</socketmax>";
126                 data << "<uptime><boot_time_t>" << ServerInstance->startup_time << "</boot_time_t></uptime>";
127                 data << "<currenttime>" << ServerInstance->Time() << "</currenttime>";
128
129                 data << ISupport;
130                 return data << "</general>";
131         }
132
133         std::ostream& XLines(std::ostream& data)
134         {
135                 data << "<xlines>";
136                 std::vector<std::string> xltypes = ServerInstance->XLines->GetAllTypes();
137                 for (std::vector<std::string>::iterator it = xltypes.begin(); it != xltypes.end(); ++it)
138                 {
139                         XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
140
141                         if (!lookup)
142                                 continue;
143                         for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
144                         {
145                                 data << "<xline type=\"" << it->c_str() << "\"><mask>"
146                                         << Sanitize(i->second->Displayable()) << "</mask><settime>"
147                                         << i->second->set_time << "</settime><duration>" << i->second->duration
148                                         << "</duration><reason>" << Sanitize(i->second->reason)
149                                         << "</reason></xline>";
150                         }
151                 }
152                 return data << "</xlines>";
153         }
154
155         std::ostream& Modules(std::ostream& data)
156         {
157                 data << "<modulelist>";
158                 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
159
160                 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
161                 {
162                         Version v = i->second->GetVersion();
163                         data << "<module><name>" << i->first << "</name><description>" << Sanitize(v.description) << "</description></module>";
164                 }
165                 return data << "</modulelist>";
166         }
167
168         std::ostream& Channels(std::ostream& data)
169         {
170                 data << "<channellist>";
171
172                 const chan_hash& chans = ServerInstance->GetChans();
173                 for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i)
174                 {
175                         Channel* c = i->second;
176
177                         data << "<channel>";
178                         data << "<usercount>" << c->GetUsers().size() << "</usercount><channelname>" << Sanitize(c->name) << "</channelname>";
179                         data << "<channeltopic>";
180                         data << "<topictext>" << Sanitize(c->topic) << "</topictext>";
181                         data << "<setby>" << Sanitize(c->setby) << "</setby>";
182                         data << "<settime>" << c->topicset << "</settime>";
183                         data << "</channeltopic>";
184                         data << "<channelmodes>" << Sanitize(c->ChanModes(true)) << "</channelmodes>";
185
186                         const Channel::MemberMap& ulist = c->GetUsers();
187                         for (Channel::MemberMap::const_iterator x = ulist.begin(); x != ulist.end(); ++x)
188                         {
189                                 Membership* memb = x->second;
190                                 data << "<channelmember><uid>" << memb->user->uuid << "</uid><privs>"
191                                         << Sanitize(memb->GetAllPrefixChars()) << "</privs><modes>"
192                                         << memb->modes << "</modes>";
193                                 DumpMeta(data, memb);
194                                 data << "</channelmember>";
195                         }
196
197                         DumpMeta(data, c);
198
199                         data << "</channel>";
200                 }
201
202                 return data << "</channellist>";
203         }
204
205         std::ostream& DumpUser(std::ostream& data, User* u)
206         {
207                 data << "<user>";
208                 data << "<nickname>" << u->nick << "</nickname><uuid>" << u->uuid << "</uuid><realhost>"
209                         << u->GetRealHost() << "</realhost><displayhost>" << u->GetDisplayedHost() << "</displayhost><realname>"
210                         << Sanitize(u->GetRealName()) << "</realname><server>" << u->server->GetName() << "</server><signon>"
211                         << u->signon << "</signon><age>" << u->age << "</age>";
212
213                 if (u->IsAway())
214                         data << "<away>" << Sanitize(u->awaymsg) << "</away><awaytime>" << u->awaytime << "</awaytime>";
215
216                 if (u->IsOper())
217                         data << "<opertype>" << Sanitize(u->oper->name) << "</opertype>";
218
219                 data << "<modes>" << u->GetModeLetters().substr(1) << "</modes><ident>" << Sanitize(u->ident) << "</ident>";
220
221                 LocalUser* lu = IS_LOCAL(u);
222                 if (lu)
223                         data << "<local/><port>" << lu->server_sa.port() << "</port><servaddr>"
224                                 << lu->server_sa.str() << "</servaddr><connectclass>"
225                                 << lu->GetClass()->GetName() << "</connectclass><lastmsg>"
226                                 << lu->idle_lastmsg << "</lastmsg>";
227
228                 data << "<ipaddress>" << u->GetIPString() << "</ipaddress>";
229
230                 DumpMeta(data, u);
231
232                 data << "</user>";
233                 return data;
234         }
235
236         std::ostream& Users(std::ostream& data)
237         {
238                 data << "<userlist>";
239                 const user_hash& users = ServerInstance->Users->GetUsers();
240                 for (user_hash::const_iterator i = users.begin(); i != users.end(); ++i)
241                 {
242                         User* u = i->second;
243
244                         if (u->registered != REG_ALL)
245                                 continue;
246
247                         DumpUser(data, u);
248                 }
249                 return data << "</userlist>";
250         }
251
252         std::ostream& Servers(std::ostream& data)
253         {
254                 data << "<serverlist>";
255
256                 ProtocolInterface::ServerList sl;
257                 ServerInstance->PI->GetServerList(sl);
258
259                 for (ProtocolInterface::ServerList::const_iterator b = sl.begin(); b != sl.end(); ++b)
260                 {
261                         data << "<server>";
262                         data << "<servername>" << b->servername << "</servername>";
263                         data << "<parentname>" << b->parentname << "</parentname>";
264                         data << "<description>" << Sanitize(b->description) << "</description>";
265                         data << "<usercount>" << b->usercount << "</usercount>";
266 // This is currently not implemented, so, commented out.
267 //                                      data << "<opercount>" << b->opercount << "</opercount>";
268                         data << "<lagmillisecs>" << b->latencyms << "</lagmillisecs>";
269                         data << "</server>";
270                 }
271
272                 return data << "</serverlist>";
273         }
274
275         std::ostream& Commands(std::ostream& data)
276         {
277                 data << "<commandlist>";
278
279                 const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
280                 for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
281                 {
282                         data << "<command><name>" << i->second->name << "</name><usecount>" << i->second->use_count << "</usecount></command>";
283                 }
284                 return data << "</commandlist>";
285         }
286
287         enum OrderBy
288         {
289                 OB_NICK,
290                 OB_LASTMSG,
291
292                 OB_NONE
293         };
294
295         struct UserSorter
296         {
297                 OrderBy order;
298                 bool desc;
299
300                 UserSorter(OrderBy Order, bool Desc = false) : order(Order), desc(Desc) {}
301
302                 template <typename T>
303                 inline bool Compare(const T& a, const T& b)
304                 {
305                         return desc ? a > b : a < b;
306                 }
307
308                 bool operator()(User* u1, User* u2)
309                 {
310                         switch (order) {
311                                 case OB_LASTMSG:
312                                         return Compare(IS_LOCAL(u1)->idle_lastmsg, IS_LOCAL(u2)->idle_lastmsg);
313                                         break;
314                                 case OB_NICK:
315                                         return Compare(u1->nick, u2->nick);
316                                         break;
317                                 default:
318                                 case OB_NONE:
319                                         return false;
320                                         break;
321                         }
322                 }
323         };
324
325         std::ostream& ListUsers(std::ostream& data, const HTTPQueryParameters& params)
326         {
327                 if (params.empty())
328                         return Users(data);
329
330                 data << "<userlist>";
331
332                 // Filters
333                 size_t limit = params.getNum<size_t>("limit");
334                 bool showunreg = params.getBool("showunreg");
335                 bool localonly = params.getBool("localonly");
336
337                 // Minimum time since a user's last message
338                 unsigned long min_idle = params.getDuration("minidle");
339                 time_t maxlastmsg = ServerInstance->Time() - min_idle;
340
341                 if (min_idle)
342                         // We can only check idle times on local users
343                         localonly = true;
344
345                 // Sorting
346                 const std::string& sortmethod = params.getString("sortby");
347                 bool desc = params.getBool("desc", false);
348
349                 OrderBy orderby;
350                 if (stdalgo::string::equalsci(sortmethod, "nick"))
351                         orderby = OB_NICK;
352                 else if (stdalgo::string::equalsci(sortmethod, "lastmsg"))
353                 {
354                         orderby = OB_LASTMSG;
355                         // We can only check idle times on local users
356                         localonly = true;
357                 }
358                 else
359                         orderby = OB_NONE;
360
361                 typedef std::list<User*> NewUserList;
362                 NewUserList user_list;
363                 user_hash users = ServerInstance->Users->GetUsers();
364                 for (user_hash::iterator i = users.begin(); i != users.end(); ++i)
365                 {
366                         User* u = i->second;
367                         if (!showunreg && u->registered != REG_ALL)
368                                 continue;
369
370                         LocalUser* lu = IS_LOCAL(u);
371                         if (localonly && !lu)
372                                 continue;
373
374                         if (min_idle && lu->idle_lastmsg > maxlastmsg)
375                                 continue;
376
377                         user_list.push_back(u);
378                 }
379
380                 UserSorter sorter(orderby, desc);
381                 if (sorter.order != OB_NONE && !(!localonly && sorter.order == OB_LASTMSG))
382                         user_list.sort(sorter);
383
384                 size_t count = 0;
385                 for (NewUserList::const_iterator i = user_list.begin(); i != user_list.end() && (!limit || count < limit); ++i, ++count)
386                         DumpUser(data, *i);
387
388                 data << "</userlist>";
389                 return data;
390         }
391 }
392
393 class ModuleHttpStats : public Module, public HTTPRequestEventListener
394 {
395         HTTPdAPI API;
396         bool enableparams;
397
398  public:
399         ModuleHttpStats()
400                 : HTTPRequestEventListener(this)
401                 , API(this)
402                 , enableparams(false)
403         {
404         }
405
406         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
407         {
408                 ConfigTag* conf = ServerInstance->Config->ConfValue("httpstats");
409
410                 // Parameterized queries may cause a performance issue
411                 // Due to the sheer volume of data
412                 // So default them to disabled
413                 enableparams = conf->getBool("enableparams");
414         }
415
416         ModResult HandleRequest(HTTPRequest* http)
417         {
418                 std::string path = http->GetPath();
419
420                 if (path != "/stats" && path.substr(0, 7) != "/stats/")
421                         return MOD_RES_PASSTHRU;
422
423                 if (path[path.size() - 1] == '/')
424                         path.erase(path.size() - 1, 1);
425
426                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd event");
427
428                 bool found = true;
429                 std::stringstream data;
430                 data << "<inspircdstats>";
431
432                 if (path == "/stats")
433                 {
434                         data << Stats::ServerInfo << Stats::General
435                                 << Stats::XLines << Stats::Modules
436                                 << Stats::Channels << Stats::Users
437                                 << Stats::Servers << Stats::Commands;
438                 }
439                 else if (path == "/stats/general")
440                 {
441                         data << Stats::General;
442                 }
443                 else if (path == "/stats/users")
444                 {
445                         if (enableparams)
446                                 Stats::ListUsers(data, http->GetParsedURI().query_params);
447                         else
448                                 data << Stats::Users;
449                 }
450                 else
451                 {
452                         found = false;
453                 }
454
455                 if (found)
456                 {
457                         data << "</inspircdstats>";
458                 }
459                 else
460                 {
461                         data.clear();
462                         data.str(std::string());
463                 }
464
465                 /* Send the document back to m_httpd */
466                 HTTPDocumentResponse response(this, *http, &data, found ? 200 : 404);
467                 response.headers.SetHeader("X-Powered-By", MODNAME);
468                 response.headers.SetHeader("Content-Type", "text/xml");
469                 API->SendResponse(response);
470                 return MOD_RES_DENY; // Handled
471         }
472
473         ModResult OnHTTPRequest(HTTPRequest& req) CXX11_OVERRIDE
474         {
475                 return HandleRequest(&req);
476         }
477
478         Version GetVersion() CXX11_OVERRIDE
479         {
480                 return Version("Provides statistics over HTTP via m_httpd", VF_VENDOR);
481         }
482 };
483
484 MODULE_INIT(ModuleHttpStats)