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"
32 # pragma GCC diagnostic push
35 // Fix warnings about the use of commas at end of enumerator lists and long long
38 # pragma clang diagnostic ignored "-Wc++11-extensions"
39 # pragma clang diagnostic ignored "-Wc++11-long-long"
40 #elif defined __GNUC__
41 # pragma GCC diagnostic ignored "-Wlong-long"
42 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
43 # pragma GCC diagnostic ignored "-Wpedantic"
45 # pragma GCC diagnostic ignored "-pedantic"
49 // Fix warnings about shadowing in http_parser.
51 # pragma GCC diagnostic ignored "-Wshadow"
54 #include <http_parser.c>
57 # pragma GCC diagnostic pop
60 class ModuleHttpServer;
62 static ModuleHttpServer* HttpModule;
63 static insp::intrusive_list<HttpServerSocket> sockets;
64 static Events::ModuleEventProvider* aclevprov;
65 static Events::ModuleEventProvider* reqevprov;
66 static http_parser_settings parser_settings;
68 /** A socket used for HTTP transport
70 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
73 friend class ModuleHttpServer;
84 /** True if this object is in the cull list
89 bool Tick(time_t currtime) CXX11_OVERRIDE
100 template<int (HttpServerSocket::*f)()>
101 static int Callback(http_parser* p)
103 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
107 template<int (HttpServerSocket::*f)(const char*, size_t)>
108 static int DataCallback(http_parser* p, const char* buf, size_t len)
110 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
111 return (sock->*f)(buf, len);
114 static void ConfigureParser()
116 http_parser_settings_init(&parser_settings);
117 parser_settings.on_message_begin = Callback<&HttpServerSocket::OnMessageBegin>;
118 parser_settings.on_url = DataCallback<&HttpServerSocket::OnUrl>;
119 parser_settings.on_header_field = DataCallback<&HttpServerSocket::OnHeaderField>;
120 parser_settings.on_body = DataCallback<&HttpServerSocket::OnBody>;
121 parser_settings.on_message_complete = Callback<&HttpServerSocket::OnMessageComplete>;
127 header_state = HEADER_NONE;
133 bool AcceptData(size_t len)
135 total_buffers += len;
136 return total_buffers < 8192;
139 int OnUrl(const char* buf, size_t len)
141 if (!AcceptData(len))
143 status_code = HTTP_STATUS_URI_TOO_LONG;
146 uri.append(buf, len);
150 enum { HEADER_NONE, HEADER_FIELD, HEADER_VALUE } header_state;
151 std::string header_field;
152 std::string header_value;
154 void OnHeaderComplete()
156 headers.SetHeader(header_field, header_value);
157 header_field.clear();
158 header_value.clear();
161 int OnHeaderField(const char* buf, size_t len)
163 if (header_state == HEADER_VALUE)
165 header_state = HEADER_FIELD;
166 if (!AcceptData(len))
168 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
171 header_field.append(buf, len);
175 int OnHeaderValue(const char* buf, size_t len)
177 header_state = HEADER_VALUE;
178 if (!AcceptData(len))
180 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
183 header_value.append(buf, len);
187 int OnHeadersComplete()
189 if (header_state != HEADER_NONE)
194 int OnBody(const char* buf, size_t len)
196 if (!AcceptData(len))
198 status_code = HTTP_STATUS_PAYLOAD_TOO_LARGE;
201 body.append(buf, len);
205 int OnMessageComplete()
207 messagecomplete = true;
213 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
214 : BufferedSocket(newfd)
219 , messagecomplete(false)
221 if ((!via->iohookprovs.empty()) && (via->iohookprovs.back()))
223 via->iohookprovs.back()->OnAccept(this, client, server);
224 // IOHook may have errored
225 if (!getError().empty())
233 http_parser_init(&parser, HTTP_REQUEST);
234 ServerInstance->Timers.AddTimer(this);
242 void OnError(BufferedSocketError) CXX11_OVERRIDE
247 void SendHTTPError(unsigned int response)
250 std::string data = InspIRCd::Format(
251 "<html><head></head><body>Server error %u: %s<br>"
252 "<small>Powered by <a href='https://www.inspircd.org'>InspIRCd</a></small></body></html>", response, http_status_str((http_status)response));
254 Page(data, response, &empty);
257 void SendHeaders(unsigned long size, unsigned int response, HTTPHeaders &rheaders)
259 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, http_status_str((http_status)response)));
261 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
262 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
263 rheaders.SetHeader("Content-Length", ConvToStr(size));
266 rheaders.CreateHeader("Content-Type", "text/html");
268 rheaders.RemoveHeader("Content-Type");
270 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
271 * so remove it, its not essential for what we need.
273 rheaders.SetHeader("Connection", "Close");
275 WriteData(rheaders.GetFormattedHeaders());
279 void OnDataReady() CXX11_OVERRIDE
281 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
283 http_parser_execute(&parser, &parser_settings, recvq.data(), recvq.size());
284 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
285 SendHTTPError(status_code ? status_code : 400);
290 ModResult MOD_RESULT;
291 std::string method = http_method_str(static_cast<http_method>(parser.method));
292 HTTPRequestURI parsed;
293 ParseURI(uri, parsed);
294 HTTPRequest acl(method, parsed, &headers, this, ip, body);
295 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
296 if (MOD_RESULT != MOD_RES_DENY)
298 HTTPRequest request(method, parsed, &headers, this, ip, body);
299 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (request));
300 if (MOD_RESULT == MOD_RES_PASSTHRU)
307 void Page(const std::string& s, unsigned int response, HTTPHeaders* hheaders)
309 SendHeaders(s.length(), response, *hheaders);
314 void Page(std::stringstream* n, unsigned int response, HTTPHeaders* hheaders)
316 Page(n->str(), response, hheaders);
326 ServerInstance->GlobalCulls.AddItem(this);
329 bool ParseURI(const std::string& uristr, HTTPRequestURI& out)
331 http_parser_url_init(&url);
332 if (http_parser_parse_url(uristr.c_str(), uristr.size(), 0, &url) != 0)
335 if (url.field_set & (1 << UF_PATH))
336 out.path = uri.substr(url.field_data[UF_PATH].off, url.field_data[UF_PATH].len);
338 if (url.field_set & (1 << UF_FRAGMENT))
339 out.fragment = uri.substr(url.field_data[UF_FRAGMENT].off, url.field_data[UF_FRAGMENT].len);
341 std::string param_str;
342 if (url.field_set & (1 << UF_QUERY))
343 param_str = uri.substr(url.field_data[UF_QUERY].off, url.field_data[UF_QUERY].len);
345 irc::sepstream param_stream(param_str, '&');
347 std::string::size_type eq_pos;
348 while (param_stream.GetToken(token))
350 eq_pos = token.find('=');
351 if (eq_pos == std::string::npos)
353 out.query_params.insert(std::make_pair(token, ""));
357 out.query_params.insert(std::make_pair(token.substr(0, eq_pos), token.substr(eq_pos + 1)));
364 class HTTPdAPIImpl : public HTTPdAPIBase
367 HTTPdAPIImpl(Module* parent)
368 : HTTPdAPIBase(parent)
372 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
374 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
378 class ModuleHttpServer : public Module
380 HTTPdAPIImpl APIImpl;
381 unsigned int timeoutsec;
382 Events::ModuleEventProvider acleventprov;
383 Events::ModuleEventProvider reqeventprov;
388 , acleventprov(this, "event/http-acl")
389 , reqeventprov(this, "event/http-request")
391 aclevprov = &acleventprov;
392 reqevprov = &reqeventprov;
393 HttpServerSocket::ConfigureParser();
396 void init() CXX11_OVERRIDE
401 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
403 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
404 timeoutsec = tag->getDuration("timeout", 10, 1);
407 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
409 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "httpd"))
410 return MOD_RES_PASSTHRU;
412 sockets.push_front(new HttpServerSocket(nfd, client->addr(), from, client, server, timeoutsec));
413 return MOD_RES_ALLOW;
416 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
418 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); )
420 HttpServerSocket* sock = *i;
422 if (sock->GetModHook(mod))
430 CullResult cull() CXX11_OVERRIDE
432 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
434 HttpServerSocket* sock = *i;
437 return Module::cull();
440 Version GetVersion() CXX11_OVERRIDE
442 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
446 MODULE_INIT(ModuleHttpServer)