2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
25 #include "modules/httpd.h"
32 static const insp::flat_map<char, char const*>& entities;
35 static const insp::flat_map<char, char const*>& init_entities()
37 static insp::flat_map<char, char const*> entities;
40 entities['&'] = "amp";
41 entities['"'] = "quot";
45 const insp::flat_map<char, char const*>& Entities::entities = init_entities();
47 std::string Sanitize(const std::string& str)
50 ret.reserve(str.length() * 2);
52 for (std::string::const_iterator x = str.begin(); x != str.end(); ++x)
54 insp::flat_map<char, char const*>::const_iterator it = Entities::entities.find(*x);
56 if (it != Entities::entities.end())
62 else if (*x == 0x09 || *x == 0x0A || *x == 0x0D || ((*x >= 0x20) && (*x <= 0x7e)))
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]
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.
75 ret += BinToBase64(str);
83 void DumpMeta(std::ostream& data, Extensible* ext)
86 for (Extensible::ExtensibleStore::const_iterator i = ext->GetExtList().begin(); i != ext->GetExtList().end(); i++)
88 ExtensionItem* item = i->first;
89 std::string value = item->serialize(FORMAT_USER, ext, i->second);
91 data << "<meta name=\"" << item->name << "\">" << Sanitize(value) << "</meta>";
92 else if (!item->name.empty())
93 data << "<meta name=\"" << item->name << "\"/>";
95 data << "</metadata>";
98 std::ostream& ServerInfo(std::ostream& data)
100 return data << "<server><name>" << ServerInstance->Config->ServerName << "</name><description>"
101 << Sanitize(ServerInstance->Config->ServerDesc) << "</description><version>"
102 << Sanitize(ServerInstance->GetVersionString(true)) << "</version></server>";
105 std::ostream& ISupport(std::ostream& data)
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)
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>";
115 return data << "</isupport>";
118 std::ostream& General(std::ostream& data)
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>";
130 return data << "</general>";
133 std::ostream& XLines(std::ostream& data)
136 std::vector<std::string> xltypes = ServerInstance->XLines->GetAllTypes();
137 for (std::vector<std::string>::iterator it = xltypes.begin(); it != xltypes.end(); ++it)
139 XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
143 for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
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>";
152 return data << "</xlines>";
155 std::ostream& Modules(std::ostream& data)
157 data << "<modulelist>";
158 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
160 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
162 Version v = i->second->GetVersion();
163 data << "<module><name>" << i->first << "</name><description>" << Sanitize(v.description) << "</description></module>";
165 return data << "</modulelist>";
168 std::ostream& Channels(std::ostream& data)
170 data << "<channellist>";
172 const chan_hash& chans = ServerInstance->GetChans();
173 for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i)
175 Channel* c = i->second;
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>";
186 const Channel::MemberMap& ulist = c->GetUsers();
187 for (Channel::MemberMap::const_iterator x = ulist.begin(); x != ulist.end(); ++x)
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>";
199 data << "</channel>";
202 return data << "</channellist>";
205 std::ostream& DumpUser(std::ostream& data, User* u)
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>";
214 data << "<away>" << Sanitize(u->awaymsg) << "</away><awaytime>" << u->awaytime << "</awaytime>";
217 data << "<opertype>" << Sanitize(u->oper->name) << "</opertype>";
219 data << "<modes>" << u->GetModeLetters().substr(1) << "</modes><ident>" << Sanitize(u->ident) << "</ident>";
221 LocalUser* lu = IS_LOCAL(u);
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>";
228 data << "<ipaddress>" << u->GetIPString() << "</ipaddress>";
236 std::ostream& Users(std::ostream& data)
238 data << "<userlist>";
239 const user_hash& users = ServerInstance->Users->GetUsers();
240 for (user_hash::const_iterator i = users.begin(); i != users.end(); ++i)
244 if (u->registered != REG_ALL)
249 return data << "</userlist>";
252 std::ostream& Servers(std::ostream& data)
254 data << "<serverlist>";
256 ProtocolInterface::ServerList sl;
257 ServerInstance->PI->GetServerList(sl);
259 for (ProtocolInterface::ServerList::const_iterator b = sl.begin(); b != sl.end(); ++b)
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>";
272 return data << "</serverlist>";
275 std::ostream& Commands(std::ostream& data)
277 data << "<commandlist>";
279 const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
280 for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
282 data << "<command><name>" << i->second->name << "</name><usecount>" << i->second->use_count << "</usecount></command>";
284 return data << "</commandlist>";
300 UserSorter(OrderBy Order, bool Desc = false) : order(Order), desc(Desc) {}
302 template <typename T>
303 inline bool Compare(const T& a, const T& b)
305 return desc ? a > b : a < b;
308 bool operator()(User* u1, User* u2)
312 return Compare(IS_LOCAL(u1)->idle_lastmsg, IS_LOCAL(u2)->idle_lastmsg);
315 return Compare(u1->nick, u2->nick);
325 std::ostream& ListUsers(std::ostream& data, const HTTPQueryParameters& params)
330 data << "<userlist>";
333 size_t limit = params.getNum<size_t>("limit");
334 bool showunreg = params.getBool("showunreg");
335 bool localonly = params.getBool("localonly");
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;
342 // We can only check idle times on local users
346 const std::string& sortmethod = params.getString("sortby");
347 bool desc = params.getBool("desc", false);
350 if (stdalgo::string::equalsci(sortmethod, "nick"))
352 else if (stdalgo::string::equalsci(sortmethod, "lastmsg"))
354 orderby = OB_LASTMSG;
355 // We can only check idle times on local users
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)
367 if (!showunreg && u->registered != REG_ALL)
370 LocalUser* lu = IS_LOCAL(u);
371 if (localonly && !lu)
374 if (min_idle && lu->idle_lastmsg > maxlastmsg)
377 user_list.push_back(u);
380 UserSorter sorter(orderby, desc);
381 if (sorter.order != OB_NONE && !(!localonly && sorter.order == OB_LASTMSG))
382 user_list.sort(sorter);
385 for (NewUserList::const_iterator i = user_list.begin(); i != user_list.end() && (!limit || count < limit); ++i, ++count)
388 data << "</userlist>";
393 class ModuleHttpStats : public Module, public HTTPRequestEventListener
400 : HTTPRequestEventListener(this)
402 , enableparams(false)
406 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
408 ConfigTag* conf = ServerInstance->Config->ConfValue("httpstats");
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");
416 ModResult HandleRequest(HTTPRequest* http)
418 std::string path = http->GetPath();
420 if (path != "/stats" && path.substr(0, 7) != "/stats/")
421 return MOD_RES_PASSTHRU;
423 if (path[path.size() - 1] == '/')
424 path.erase(path.size() - 1, 1);
426 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd event");
429 std::stringstream data;
430 data << "<inspircdstats>";
432 if (path == "/stats")
434 data << Stats::ServerInfo << Stats::General
435 << Stats::XLines << Stats::Modules
436 << Stats::Channels << Stats::Users
437 << Stats::Servers << Stats::Commands;
439 else if (path == "/stats/general")
441 data << Stats::General;
443 else if (path == "/stats/users")
446 Stats::ListUsers(data, http->GetParsedURI().query_params);
448 data << Stats::Users;
457 data << "</inspircdstats>";
462 data.str(std::string());
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
473 ModResult OnHTTPRequest(HTTPRequest& req) CXX11_OVERRIDE
475 return HandleRequest(&req);
478 Version GetVersion() CXX11_OVERRIDE
480 return Version("Provides statistics over HTTP via m_httpd", VF_VENDOR);
484 MODULE_INIT(ModuleHttpStats)