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 and long long
32 // on C++03 and warnings about shadowing in the http_parser library.
34 # pragma clang diagnostic ignored "-Wc++11-extensions"
35 # pragma clang diagnostic ignored "-Wc++11-long-long"
36 #elif defined __GNUC__
37 # pragma GCC diagnostic ignored "-Wlong-long"
38 # pragma GCC diagnostic ignored "-Wshadow"
39 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
40 # pragma GCC diagnostic ignored "-Wpedantic"
42 # pragma GCC diagnostic ignored "-pedantic"
46 #include <http_parser.c>
48 class ModuleHttpServer;
50 static ModuleHttpServer* HttpModule;
51 static insp::intrusive_list<HttpServerSocket> sockets;
52 static Events::ModuleEventProvider* aclevprov;
53 static Events::ModuleEventProvider* reqevprov;
54 static http_parser_settings parser_settings;
56 /** A socket used for HTTP transport
58 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
61 friend class ModuleHttpServer;
72 /** True if this object is in the cull list
77 bool Tick(time_t currtime) CXX11_OVERRIDE
88 template<int (HttpServerSocket::*f)()>
89 static int Callback(http_parser* p)
91 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
95 template<int (HttpServerSocket::*f)(const char*, size_t)>
96 static int DataCallback(http_parser* p, const char* buf, size_t len)
98 HttpServerSocket* sock = static_cast<HttpServerSocket*>(p->data);
99 return (sock->*f)(buf, len);
102 static void ConfigureParser()
104 http_parser_settings_init(&parser_settings);
105 parser_settings.on_message_begin = Callback<&HttpServerSocket::OnMessageBegin>;
106 parser_settings.on_url = DataCallback<&HttpServerSocket::OnUrl>;
107 parser_settings.on_header_field = DataCallback<&HttpServerSocket::OnHeaderField>;
108 parser_settings.on_body = DataCallback<&HttpServerSocket::OnBody>;
109 parser_settings.on_message_complete = Callback<&HttpServerSocket::OnMessageComplete>;
115 header_state = HEADER_NONE;
121 bool AcceptData(size_t len)
123 total_buffers += len;
124 return total_buffers < 8192;
127 int OnUrl(const char* buf, size_t len)
129 if (!AcceptData(len))
131 status_code = HTTP_STATUS_URI_TOO_LONG;
134 uri.append(buf, len);
138 enum { HEADER_NONE, HEADER_FIELD, HEADER_VALUE } header_state;
139 std::string header_field;
140 std::string header_value;
142 void OnHeaderComplete()
144 headers.SetHeader(header_field, header_value);
145 header_field.clear();
146 header_value.clear();
149 int OnHeaderField(const char* buf, size_t len)
151 if (header_state == HEADER_VALUE)
153 header_state = HEADER_FIELD;
154 if (!AcceptData(len))
156 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
159 header_field.append(buf, len);
163 int OnHeaderValue(const char* buf, size_t len)
165 header_state = HEADER_VALUE;
166 if (!AcceptData(len))
168 status_code = HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE;
171 header_value.append(buf, len);
175 int OnHeadersComplete()
177 if (header_state != HEADER_NONE)
182 int OnBody(const char* buf, size_t len)
184 if (!AcceptData(len))
186 status_code = HTTP_STATUS_PAYLOAD_TOO_LARGE;
189 body.append(buf, len);
193 int OnMessageComplete()
195 messagecomplete = true;
201 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
202 : BufferedSocket(newfd)
207 , messagecomplete(false)
209 if ((!via->iohookprovs.empty()) && (via->iohookprovs.back()))
211 via->iohookprovs.back()->OnAccept(this, client, server);
212 // IOHook may have errored
213 if (!getError().empty())
221 http_parser_init(&parser, HTTP_REQUEST);
222 ServerInstance->Timers.AddTimer(this);
230 void OnError(BufferedSocketError) CXX11_OVERRIDE
235 void SendHTTPError(unsigned int response)
238 std::string data = InspIRCd::Format(
239 "<html><head></head><body>Server error %u: %s<br>"
240 "<small>Powered by <a href='https://www.inspircd.org'>InspIRCd</a></small></body></html>", response, http_status_str((http_status)response));
242 Page(data, response, &empty);
245 void SendHeaders(unsigned long size, unsigned int response, HTTPHeaders &rheaders)
247 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)));
249 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
250 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
251 rheaders.SetHeader("Content-Length", ConvToStr(size));
254 rheaders.CreateHeader("Content-Type", "text/html");
256 rheaders.RemoveHeader("Content-Type");
258 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
259 * so remove it, its not essential for what we need.
261 rheaders.SetHeader("Connection", "Close");
263 WriteData(rheaders.GetFormattedHeaders());
267 void OnDataReady() CXX11_OVERRIDE
269 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
271 http_parser_execute(&parser, &parser_settings, recvq.data(), recvq.size());
272 if (parser.upgrade || HTTP_PARSER_ERRNO(&parser))
273 SendHTTPError(status_code ? status_code : 400);
278 ModResult MOD_RESULT;
279 std::string method = http_method_str(static_cast<http_method>(parser.method));
280 HTTPRequestURI parsed;
281 ParseURI(uri, parsed);
282 HTTPRequest acl(method, parsed, &headers, this, ip, body);
283 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
284 if (MOD_RESULT != MOD_RES_DENY)
286 HTTPRequest url(method, parsed, &headers, this, ip, body);
287 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
288 if (MOD_RESULT == MOD_RES_PASSTHRU)
295 void Page(const std::string& s, unsigned int response, HTTPHeaders* hheaders)
297 SendHeaders(s.length(), response, *hheaders);
302 void Page(std::stringstream* n, unsigned int response, HTTPHeaders* hheaders)
304 Page(n->str(), response, hheaders);
314 ServerInstance->GlobalCulls.AddItem(this);
317 bool ParseURI(const std::string& uri, HTTPRequestURI& out)
319 http_parser_url_init(&url);
320 if (http_parser_parse_url(uri.c_str(), uri.size(), 0, &url) != 0)
323 if (url.field_set & (1 << UF_PATH))
324 out.path = uri.substr(url.field_data[UF_PATH].off, url.field_data[UF_PATH].len);
326 if (url.field_set & (1 << UF_FRAGMENT))
327 out.fragment = uri.substr(url.field_data[UF_FRAGMENT].off, url.field_data[UF_FRAGMENT].len);
329 std::string param_str;
330 if (url.field_set & (1 << UF_QUERY))
331 param_str = uri.substr(url.field_data[UF_QUERY].off, url.field_data[UF_QUERY].len);
333 irc::sepstream param_stream(param_str, '&');
335 std::string::size_type eq_pos;
336 while (param_stream.GetToken(token))
338 eq_pos = token.find('=');
339 if (eq_pos == std::string::npos)
341 out.query_params.insert(std::make_pair(token, ""));
345 out.query_params.insert(std::make_pair(token.substr(0, eq_pos), token.substr(eq_pos + 1)));
352 class HTTPdAPIImpl : public HTTPdAPIBase
355 HTTPdAPIImpl(Module* parent)
356 : HTTPdAPIBase(parent)
360 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
362 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
366 class ModuleHttpServer : public Module
368 HTTPdAPIImpl APIImpl;
369 unsigned int timeoutsec;
370 Events::ModuleEventProvider acleventprov;
371 Events::ModuleEventProvider reqeventprov;
376 , acleventprov(this, "event/http-acl")
377 , reqeventprov(this, "event/http-request")
379 aclevprov = &acleventprov;
380 reqevprov = &reqeventprov;
381 HttpServerSocket::ConfigureParser();
384 void init() CXX11_OVERRIDE
389 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
391 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
392 timeoutsec = tag->getDuration("timeout", 10, 1);
395 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
397 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "httpd"))
398 return MOD_RES_PASSTHRU;
400 sockets.push_front(new HttpServerSocket(nfd, client->addr(), from, client, server, timeoutsec));
401 return MOD_RES_ALLOW;
404 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
406 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); )
408 HttpServerSocket* sock = *i;
410 if (sock->GetModHook(mod))
418 CullResult cull() CXX11_OVERRIDE
420 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
422 HttpServerSocket* sock = *i;
425 return Module::cull();
428 Version GetVersion() CXX11_OVERRIDE
430 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
434 MODULE_INIT(ModuleHttpServer)