]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_httpd_stats.cpp
Allow configuring whether SETNAME sends snotices and is oper-only.
[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->serialize(FORMAT_USER, 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()) << "</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
128                 data << ISupport;
129                 return data << "</general>";
130         }
131
132         std::ostream& XLines(std::ostream& data)
133         {
134                 data << "<xlines>";
135                 std::vector<std::string> xltypes = ServerInstance->XLines->GetAllTypes();
136                 for (std::vector<std::string>::iterator it = xltypes.begin(); it != xltypes.end(); ++it)
137                 {
138                         XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
139
140                         if (!lookup)
141                                 continue;
142                         for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
143                         {
144                                 data << "<xline type=\"" << it->c_str() << "\"><mask>"
145                                         << Sanitize(i->second->Displayable()) << "</mask><settime>"
146                                         << i->second->set_time << "</settime><duration>" << i->second->duration
147                                         << "</duration><reason>" << Sanitize(i->second->reason)
148                                         << "</reason></xline>";
149                         }
150                 }
151                 return data << "</xlines>";
152         }
153
154         std::ostream& Modules(std::ostream& data)
155         {
156                 data << "<modulelist>";
157                 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
158
159                 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
160                 {
161                         Version v = i->second->GetVersion();
162                         data << "<module><name>" << i->first << "</name><description>" << Sanitize(v.description) << "</description></module>";
163                 }
164                 return data << "</modulelist>";
165         }
166
167         std::ostream& Channels(std::ostream& data)
168         {
169                 data << "<channellist>";
170
171                 const chan_hash& chans = ServerInstance->GetChans();
172                 for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i)
173                 {
174                         Channel* c = i->second;
175
176                         data << "<channel>";
177                         data << "<usercount>" << c->GetUsers().size() << "</usercount><channelname>" << Sanitize(c->name) << "</channelname>";
178                         data << "<channeltopic>";
179                         data << "<topictext>" << Sanitize(c->topic) << "</topictext>";
180                         data << "<setby>" << Sanitize(c->setby) << "</setby>";
181                         data << "<settime>" << c->topicset << "</settime>";
182                         data << "</channeltopic>";
183                         data << "<channelmodes>" << Sanitize(c->ChanModes(true)) << "</channelmodes>";
184
185                         const Channel::MemberMap& ulist = c->GetUsers();
186                         for (Channel::MemberMap::const_iterator x = ulist.begin(); x != ulist.end(); ++x)
187                         {
188                                 Membership* memb = x->second;
189                                 data << "<channelmember><uid>" << memb->user->uuid << "</uid><privs>"
190                                         << Sanitize(memb->GetAllPrefixChars()) << "</privs><modes>"
191                                         << memb->modes << "</modes>";
192                                 DumpMeta(data, memb);
193                                 data << "</channelmember>";
194                         }
195
196                         DumpMeta(data, c);
197
198                         data << "</channel>";
199                 }
200
201                 return data << "</channellist>";
202         }
203
204         std::ostream& Users(std::ostream& data)
205         {
206                 data << "<userlist>";
207                 const user_hash& users = ServerInstance->Users->GetUsers();
208                 for (user_hash::const_iterator i = users.begin(); i != users.end(); ++i)
209                 {
210                         User* u = i->second;
211
212                         data << "<user>";
213                         data << "<nickname>" << u->nick << "</nickname><uuid>" << u->uuid << "</uuid><realhost>"
214                                 << u->GetRealHost() << "</realhost><displayhost>" << u->GetDisplayedHost() << "</displayhost><realname>"
215                                 << Sanitize(u->GetRealName()) << "</realname><server>" << u->server->GetName() << "</server>";
216                         if (u->IsAway())
217                                 data << "<away>" << Sanitize(u->awaymsg) << "</away><awaytime>" << u->awaytime << "</awaytime>";
218                         if (u->IsOper())
219                                 data << "<opertype>" << Sanitize(u->oper->name) << "</opertype>";
220                         data << "<modes>" << u->GetModeLetters().substr(1) << "</modes><ident>" << Sanitize(u->ident) << "</ident>";
221                         LocalUser* lu = IS_LOCAL(u);
222                         if (lu)
223                                 data << "<port>" << lu->GetServerPort() << "</port><servaddr>"
224                                         << lu->server_sa.str() << "</servaddr>";
225                         data << "<ipaddress>" << u->GetIPString() << "</ipaddress>";
226
227                         DumpMeta(data, u);
228
229                         data << "</user>";
230                 }
231                 return data << "</userlist>";
232         }
233
234         std::ostream& Servers(std::ostream& data)
235         {
236                 data << "<serverlist>";
237
238                 ProtocolInterface::ServerList sl;
239                 ServerInstance->PI->GetServerList(sl);
240
241                 for (ProtocolInterface::ServerList::const_iterator b = sl.begin(); b != sl.end(); ++b)
242                 {
243                         data << "<server>";
244                         data << "<servername>" << b->servername << "</servername>";
245                         data << "<parentname>" << b->parentname << "</parentname>";
246                         data << "<description>" << Sanitize(b->description) << "</description>";
247                         data << "<usercount>" << b->usercount << "</usercount>";
248 // This is currently not implemented, so, commented out.
249 //                                      data << "<opercount>" << b->opercount << "</opercount>";
250                         data << "<lagmillisecs>" << b->latencyms << "</lagmillisecs>";
251                         data << "</server>";
252                 }
253
254                 return data << "</serverlist>";
255         }
256
257         std::ostream& Commands(std::ostream& data)
258         {
259                 data << "<commandlist>";
260
261                 const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
262                 for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
263                 {
264                         data << "<command><name>" << i->second->name << "</name><usecount>" << i->second->use_count << "</usecount></command>";
265                 }
266                 return data << "</commandlist>";
267         }
268 }
269
270 class ModuleHttpStats : public Module, public HTTPRequestEventListener
271 {
272         HTTPdAPI API;
273
274  public:
275         ModuleHttpStats()
276                 : HTTPRequestEventListener(this)
277                 , API(this)
278         {
279         }
280
281         ModResult HandleRequest(HTTPRequest* http)
282         {
283                 std::string uri = http->GetURI();
284
285                 if (uri != "/stats" && uri.substr(0, 7) != "/stats/")
286                         return MOD_RES_PASSTHRU;
287
288                 if (uri[uri.size() - 1] == '/')
289                         uri.erase(uri.size() - 1, 1);
290
291                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd event");
292
293                 bool found = true;
294                 std::stringstream data;
295                 data << "<inspircdstats>";
296
297                 if (uri == "/stats")
298                 {
299                         data << Stats::ServerInfo << Stats::General
300                                 << Stats::XLines << Stats::Modules
301                                 << Stats::Channels << Stats::Users
302                                 << Stats::Servers << Stats::Commands;
303                 }
304                 else if (uri == "/stats/general")
305                 {
306                         data << Stats::General;
307                 }
308                 else if (uri == "/stats/users")
309                 {
310                         data << Stats::Users;
311                 }
312                 else
313                 {
314                         found = false;
315                 }
316
317                 if (found)
318                 {
319                         data << "</inspircdstats>";
320                 }
321                 else
322                 {
323                         data.clear();
324                         data.str(std::string());
325                 }
326
327                 /* Send the document back to m_httpd */
328                 HTTPDocumentResponse response(this, *http, &data, found ? 200 : 404);
329                 response.headers.SetHeader("X-Powered-By", MODNAME);
330                 response.headers.SetHeader("Content-Type", "text/xml");
331                 API->SendResponse(response);
332                 return MOD_RES_DENY; // Handled
333         }
334
335         ModResult OnHTTPRequest(HTTPRequest& req) CXX11_OVERRIDE
336         {
337                 return HandleRequest(&req);
338         }
339
340         Version GetVersion() CXX11_OVERRIDE
341         {
342                 return Version("Provides statistics over HTTP via m_httpd", VF_VENDOR);
343         }
344 };
345
346 MODULE_INIT(ModuleHttpStats)