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/>.
27 #include "modules/httpd.h"
29 class ModuleHttpServer;
31 static ModuleHttpServer* HttpModule;
33 static insp::intrusive_list<HttpServerSocket> sockets;
34 static Events::ModuleEventProvider* aclevprov;
35 static Events::ModuleEventProvider* reqevprov;
37 /** HTTP socket states
41 HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
42 HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
43 HTTP_SERVE_SEND_DATA = 2 /* Sending response */
46 /** A socket used for HTTP transport
48 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
50 HttpState InternalState;
54 std::string reqbuffer;
56 unsigned int postsize;
57 std::string request_type;
59 std::string http_version;
61 /** True if this object is in the cull list
65 bool Tick(time_t currtime) CXX11_OVERRIDE
72 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
73 : BufferedSocket(newfd)
75 , InternalState(HTTP_SERVE_WAIT_REQUEST)
80 ServerInstance->Timers.AddTimer(this);
83 via->iohookprov->OnAccept(this, client, server);
91 void OnError(BufferedSocketError) CXX11_OVERRIDE
96 std::string Response(int response)
103 return "SWITCHING PROTOCOLS";
111 return "NON-AUTHORITATIVE INFORMATION";
115 return "RESET CONTENT";
117 return "PARTIAL CONTENT";
119 return "MULTIPLE CHOICES";
121 return "MOVED PERMANENTLY";
127 return "NOT MODIFIED";
131 return "TEMPORARY REDIRECT";
133 return "BAD REQUEST";
135 return "UNAUTHORIZED";
137 return "PAYMENT REQUIRED";
143 return "METHOD NOT ALLOWED";
145 return "NOT ACCEPTABLE";
147 return "PROXY AUTHENTICATION REQUIRED";
149 return "REQUEST TIMEOUT";
155 return "LENGTH REQUIRED";
157 return "PRECONDITION FAILED";
159 return "REQUEST ENTITY TOO LARGE";
161 return "REQUEST-URI TOO LONG";
163 return "UNSUPPORTED MEDIA TYPE";
165 return "REQUESTED RANGE NOT SATISFIABLE";
167 return "EXPECTATION FAILED";
169 return "INTERNAL SERVER ERROR";
171 return "NOT IMPLEMENTED";
173 return "BAD GATEWAY";
175 return "SERVICE UNAVAILABLE";
177 return "GATEWAY TIMEOUT";
179 return "HTTP VERSION NOT SUPPORTED";
187 void SendHTTPError(int response)
190 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
191 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
193 SendHeaders(data.length(), response, empty);
197 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
200 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
202 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
203 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
204 rheaders.SetHeader("Content-Length", ConvToStr(size));
207 rheaders.CreateHeader("Content-Type", "text/html");
209 rheaders.RemoveHeader("Content-Type");
211 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
212 * so remove it, its not essential for what we need.
214 rheaders.SetHeader("Connection", "Close");
216 WriteData(rheaders.GetFormattedHeaders());
222 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
224 postdata.append(recvq);
225 if (postdata.length() >= postsize)
230 reqbuffer.append(recvq);
232 if (reqbuffer.length() >= 8192)
234 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
239 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
240 CheckRequestBuffer();
244 void CheckRequestBuffer()
246 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
247 if (reqend == std::string::npos)
250 // We have the headers; parse them all
251 std::string::size_type hbegin = 0, hend;
252 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
257 if (request_type.empty())
259 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
260 cheader >> request_type;
262 cheader >> http_version;
264 if (request_type.empty() || uri.empty() || http_version.empty())
274 std::string cheader(reqbuffer, hbegin, hend - hbegin);
276 std::string::size_type fieldsep = cheader.find(':');
277 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
283 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
288 reqbuffer.erase(0, reqend + 4);
290 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
291 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
293 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
299 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
301 InternalState = HTTP_SERVE_RECV_POSTDATA;
303 if (reqbuffer.length() >= postsize)
305 postdata.assign(reqbuffer, 0, postsize);
306 reqbuffer.erase(0, postsize);
308 else if (!reqbuffer.empty())
310 postdata = reqbuffer;
314 if (postdata.length() >= postsize)
325 InternalState = HTTP_SERVE_SEND_DATA;
328 ModResult MOD_RESULT;
329 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
330 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
331 if (MOD_RESULT != MOD_RES_DENY)
333 HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
334 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
335 if (MOD_RESULT == MOD_RES_PASSTHRU)
342 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
344 SendHeaders(n->str().length(), response, *hheaders);
355 ServerInstance->GlobalCulls.AddItem(this);
359 class HTTPdAPIImpl : public HTTPdAPIBase
362 HTTPdAPIImpl(Module* parent)
363 : HTTPdAPIBase(parent)
367 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
370 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
374 class ModuleHttpServer : public Module
376 HTTPdAPIImpl APIImpl;
377 unsigned int timeoutsec;
378 Events::ModuleEventProvider acleventprov;
379 Events::ModuleEventProvider reqeventprov;
384 , acleventprov(this, "event/http-acl")
385 , reqeventprov(this, "event/http-request")
387 aclevprov = &acleventprov;
388 reqevprov = &reqeventprov;
391 void init() CXX11_OVERRIDE
396 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
398 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
399 timeoutsec = tag->getInt("timeout", 10, 1);
402 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
404 if (from->bind_tag->getString("type") != "httpd")
405 return MOD_RES_PASSTHRU;
407 std::string incomingip;
408 irc::sockets::satoap(*client, incomingip, port);
409 sockets.push_front(new HttpServerSocket(nfd, incomingip, from, client, server, timeoutsec));
410 return MOD_RES_ALLOW;
413 CullResult cull() CXX11_OVERRIDE
415 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
417 HttpServerSocket* sock = *i;
420 return Module::cull();
423 Version GetVersion() CXX11_OVERRIDE
425 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
429 MODULE_INIT(ModuleHttpServer)