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 # pragma GCC diagnostic ignored "-pedantic"
38 // Fix warnings about shadowing in http_parser.
39 #pragma GCC diagnostic ignored "-Wshadow"
41 #include <http_parser.c>
43 class ModuleHttpServer;
45 static ModuleHttpServer* HttpModule;
46 static insp::intrusive_list<HttpServerSocket> sockets;
47 static Events::ModuleEventProvider* aclevprov;
48 static Events::ModuleEventProvider* reqevprov;
49 static http_parser_settings parser_settings;
51 /** A socket used for HTTP transport
53 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
55 friend ModuleHttpServer;
65 /** True if this object is in the cull list
69 bool Tick(time_t currtime) CXX11_OVERRIDE
75 template<int (HttpServerSocket::*f)()>
76 static int Callback(http_parser* p)
78 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
82 template<int (HttpServerSocket::*f)(const char*, size_t)>
83 static int DataCallback(http_parser* p, const char* buf, size_t len)
85 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
86 return (sock->*f)(buf, len);
89 static void ConfigureParser()
91 http_parser_settings_init(&parser_settings);
92 parser_settings.on_message_begin = Callback<&HttpServerSocket::OnMessageBegin>;
93 parser_settings.on_url = DataCallback<&HttpServerSocket::OnUrl>;
94 parser_settings.on_header_field = DataCallback<&HttpServerSocket::OnHeaderField>;
95 parser_settings.on_body = DataCallback<&HttpServerSocket::OnBody>;
96 parser_settings.on_message_complete = Callback<&HttpServerSocket::OnMessageComplete>;
102 header_state = HEADER_NONE;
108 bool AcceptData(size_t len)
110 total_buffers += len;
111 return total_buffers < 8192;
114 int OnUrl(const char* buf, size_t len)
116 if (!AcceptData(len))
118 status_code = HTTP_STATUS_URI_TOO_LONG;
121 uri.append(buf, len);
125 enum { HEADER_NONE, HEADER_FIELD, HEADER_VALUE } header_state;
126 std::string header_field;
127 std::string header_value;
129 void OnHeaderComplete()
131 headers.SetHeader(header_field, header_value);
132 header_field.clear();
133 header_value.clear();
136 int OnHeaderField(const char* buf, size_t len)
138 if (header_state == HEADER_VALUE)
140 header_state = HEADER_FIELD;
141 if (!AcceptData(len))
143 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
146 header_field.append(buf, len);
150 int OnHeaderValue(const char* buf, size_t len)
152 header_state = HEADER_VALUE;
153 if (!AcceptData(len))
155 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
158 header_value.append(buf, len);
162 int OnHeadersComplete()
164 if (header_state != HEADER_NONE)
169 int OnBody(const char* buf, size_t len)
171 if (!AcceptData(len))
173 status_code = HTTP_STATUS_PAYLOAD_TOO_LARGE;
176 body.append(buf, len);
180 int OnMessageComplete()
187 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
188 : BufferedSocket(newfd)
194 if ((!via->iohookprovs.empty()) && (via->iohookprovs.back()))
196 via->iohookprovs.back()->OnAccept(this, client, server);
197 // IOHook may have errored
198 if (!getError().empty())
206 http_parser_init(&parser, HTTP_REQUEST);
207 ServerInstance->Timers.AddTimer(this);
215 void OnError(BufferedSocketError) CXX11_OVERRIDE
220 const char* Response(unsigned int response)
224 #define HTTP_STATUS_CASE(n, m, s) case n: return #s;
225 HTTP_STATUS_MAP(HTTP_STATUS_CASE)
232 void SendHTTPError(unsigned int response)
235 std::string data = InspIRCd::Format(
236 "<html><head></head><body>Server error %u: %s<br>"
237 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>", response, Response(response));
239 SendHeaders(data.length(), response, empty);
244 void SendHeaders(unsigned long size, unsigned int response, HTTPHeaders &rheaders)
246 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)));
248 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
249 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
250 rheaders.SetHeader("Content-Length", ConvToStr(size));
253 rheaders.CreateHeader("Content-Type", "text/html");
255 rheaders.RemoveHeader("Content-Type");
257 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
258 * so remove it, its not essential for what we need.
260 rheaders.SetHeader("Connection", "Close");
262 WriteData(rheaders.GetFormattedHeaders());
266 void OnDataReady() CXX11_OVERRIDE
268 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
270 http_parser_execute(&parser, &parser_settings, recvq.data(), recvq.size());
271 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
272 SendHTTPError(status_code ? status_code : 400);
277 ModResult MOD_RESULT;
278 std::string method = http_method_str(static_cast<http_method>(parser.method));
279 HTTPRequest acl(method, uri, &headers, this, ip, body);
280 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
281 if (MOD_RESULT != MOD_RES_DENY)
283 HTTPRequest url(method, uri, &headers, this, ip, body);
284 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
285 if (MOD_RESULT == MOD_RES_PASSTHRU)
292 void Page(std::stringstream* n, unsigned int response, HTTPHeaders* hheaders)
294 SendHeaders(n->str().length(), response, *hheaders);
306 ServerInstance->GlobalCulls.AddItem(this);
310 class HTTPdAPIImpl : public HTTPdAPIBase
313 HTTPdAPIImpl(Module* parent)
314 : HTTPdAPIBase(parent)
318 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
320 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
324 class ModuleHttpServer : public Module
326 HTTPdAPIImpl APIImpl;
327 unsigned int timeoutsec;
328 Events::ModuleEventProvider acleventprov;
329 Events::ModuleEventProvider reqeventprov;
334 , acleventprov(this, "event/http-acl")
335 , reqeventprov(this, "event/http-request")
337 aclevprov = &acleventprov;
338 reqevprov = &reqeventprov;
339 HttpServerSocket::ConfigureParser();
342 void init() CXX11_OVERRIDE
347 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
349 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
350 timeoutsec = tag->getDuration("timeout", 10, 1);
353 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
355 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "httpd"))
356 return MOD_RES_PASSTHRU;
358 sockets.push_front(new HttpServerSocket(nfd, client->addr(), from, client, server, timeoutsec));
359 return MOD_RES_ALLOW;
362 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
364 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); )
366 HttpServerSocket* sock = *i;
368 if (sock->GetModHook(mod))
376 CullResult cull() CXX11_OVERRIDE
378 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
380 HttpServerSocket* sock = *i;
383 return Module::cull();
386 Version GetVersion() CXX11_OVERRIDE
388 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
392 MODULE_INIT(ModuleHttpServer)