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 John Brooks <john.brooks@dereferenced.net>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 /// $CompilerFlags: -Ivendor_directory("http_parser")
29 #include "modules/httpd.h"
31 // Fix warnings about the use of commas at end of enumerator lists on C++03.
33 # pragma clang diagnostic ignored "-Wc++11-extensions"
34 #elif defined __GNUC__
35 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
36 # pragma GCC diagnostic ignored "-Wpedantic"
38 # pragma GCC diagnostic ignored "-pedantic"
42 // Fix warnings about shadowing in http_parser.
43 #pragma GCC diagnostic ignored "-Wshadow"
45 #include <http_parser.c>
47 class ModuleHttpServer;
49 static ModuleHttpServer* HttpModule;
50 static insp::intrusive_list<HttpServerSocket> sockets;
51 static Events::ModuleEventProvider* aclevprov;
52 static Events::ModuleEventProvider* reqevprov;
53 static http_parser_settings parser_settings;
55 /** A socket used for HTTP transport
57 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
59 friend ModuleHttpServer;
69 /** True if this object is in the cull list
73 bool Tick(time_t currtime) CXX11_OVERRIDE
79 template<int (HttpServerSocket::*f)()>
80 static int Callback(http_parser* p)
82 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
86 template<int (HttpServerSocket::*f)(const char*, size_t)>
87 static int DataCallback(http_parser* p, const char* buf, size_t len)
89 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
90 return (sock->*f)(buf, len);
93 static void ConfigureParser()
95 http_parser_settings_init(&parser_settings);
96 parser_settings.on_message_begin = Callback<&HttpServerSocket::OnMessageBegin>;
97 parser_settings.on_url = DataCallback<&HttpServerSocket::OnUrl>;
98 parser_settings.on_header_field = DataCallback<&HttpServerSocket::OnHeaderField>;
99 parser_settings.on_body = DataCallback<&HttpServerSocket::OnBody>;
100 parser_settings.on_message_complete = Callback<&HttpServerSocket::OnMessageComplete>;
106 header_state = HEADER_NONE;
112 bool AcceptData(size_t len)
114 total_buffers += len;
115 return total_buffers < 8192;
118 int OnUrl(const char* buf, size_t len)
120 if (!AcceptData(len))
122 status_code = HTTP_STATUS_URI_TOO_LONG;
125 uri.append(buf, len);
129 enum { HEADER_NONE, HEADER_FIELD, HEADER_VALUE } header_state;
130 std::string header_field;
131 std::string header_value;
133 void OnHeaderComplete()
135 headers.SetHeader(header_field, header_value);
136 header_field.clear();
137 header_value.clear();
140 int OnHeaderField(const char* buf, size_t len)
142 if (header_state == HEADER_VALUE)
144 header_state = HEADER_FIELD;
145 if (!AcceptData(len))
147 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
150 header_field.append(buf, len);
154 int OnHeaderValue(const char* buf, size_t len)
156 header_state = HEADER_VALUE;
157 if (!AcceptData(len))
159 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
162 header_value.append(buf, len);
166 int OnHeadersComplete()
168 if (header_state != HEADER_NONE)
173 int OnBody(const char* buf, size_t len)
175 if (!AcceptData(len))
177 status_code = HTTP_STATUS_PAYLOAD_TOO_LARGE;
180 body.append(buf, len);
184 int OnMessageComplete()
191 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
192 : BufferedSocket(newfd)
198 if ((!via->iohookprovs.empty()) && (via->iohookprovs.back()))
200 via->iohookprovs.back()->OnAccept(this, client, server);
201 // IOHook may have errored
202 if (!getError().empty())
210 http_parser_init(&parser, HTTP_REQUEST);
211 ServerInstance->Timers.AddTimer(this);
219 void OnError(BufferedSocketError) CXX11_OVERRIDE
224 const char* Response(unsigned int response)
228 #define HTTP_STATUS_CASE(n, m, s) case n: return #s;
229 HTTP_STATUS_MAP(HTTP_STATUS_CASE)
236 void SendHTTPError(unsigned int response)
239 std::string data = InspIRCd::Format(
240 "<html><head></head><body>Server error %u: %s<br>"
241 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>", response, Response(response));
243 SendHeaders(data.length(), response, empty);
248 void SendHeaders(unsigned long size, unsigned int response, HTTPHeaders &rheaders)
250 WriteData(InspIRCd::Format("HTTP/%u.%u %u %s\r\n", parser.http_major ? parser.http_major : 1, parser.http_major ? parser.http_minor : 1, response, Response(response)));
252 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
253 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
254 rheaders.SetHeader("Content-Length", ConvToStr(size));
257 rheaders.CreateHeader("Content-Type", "text/html");
259 rheaders.RemoveHeader("Content-Type");
261 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
262 * so remove it, its not essential for what we need.
264 rheaders.SetHeader("Connection", "Close");
266 WriteData(rheaders.GetFormattedHeaders());
270 void OnDataReady() CXX11_OVERRIDE
272 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
274 http_parser_execute(&parser, &parser_settings, recvq.data(), recvq.size());
275 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
276 SendHTTPError(status_code ? status_code : 400);
281 ModResult MOD_RESULT;
282 std::string method = http_method_str(static_cast<http_method>(parser.method));
283 HTTPRequest acl(method, uri, &headers, this, ip, body);
284 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
285 if (MOD_RESULT != MOD_RES_DENY)
287 HTTPRequest url(method, uri, &headers, this, ip, body);
288 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
289 if (MOD_RESULT == MOD_RES_PASSTHRU)
296 void Page(std::stringstream* n, unsigned int response, HTTPHeaders* hheaders)
298 SendHeaders(n->str().length(), response, *hheaders);
310 ServerInstance->GlobalCulls.AddItem(this);
314 class HTTPdAPIImpl : public HTTPdAPIBase
317 HTTPdAPIImpl(Module* parent)
318 : HTTPdAPIBase(parent)
322 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
324 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
328 class ModuleHttpServer : public Module
330 HTTPdAPIImpl APIImpl;
331 unsigned int timeoutsec;
332 Events::ModuleEventProvider acleventprov;
333 Events::ModuleEventProvider reqeventprov;
338 , acleventprov(this, "event/http-acl")
339 , reqeventprov(this, "event/http-request")
341 aclevprov = &acleventprov;
342 reqevprov = &reqeventprov;
343 HttpServerSocket::ConfigureParser();
346 void init() CXX11_OVERRIDE
351 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
353 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
354 timeoutsec = tag->getDuration("timeout", 10, 1);
357 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
359 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "httpd"))
360 return MOD_RES_PASSTHRU;
362 sockets.push_front(new HttpServerSocket(nfd, client->addr(), from, client, server, timeoutsec));
363 return MOD_RES_ALLOW;
366 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
368 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); )
370 HttpServerSocket* sock = *i;
372 if (sock->GetModHook(mod))
380 CullResult cull() CXX11_OVERRIDE
382 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
384 HttpServerSocket* sock = *i;
387 return Module::cull();
390 Version GetVersion() CXX11_OVERRIDE
392 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
396 MODULE_INIT(ModuleHttpServer)