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;
32 static insp::intrusive_list<HttpServerSocket> sockets;
33 static Events::ModuleEventProvider* aclevprov;
34 static Events::ModuleEventProvider* reqevprov;
36 /** HTTP socket states
40 HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
41 HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
42 HTTP_SERVE_SEND_DATA = 2 /* Sending response */
45 /** A socket used for HTTP transport
47 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
49 HttpState InternalState;
53 std::string reqbuffer;
55 unsigned int postsize;
56 std::string request_type;
58 std::string http_version;
60 /** True if this object is in the cull list
64 bool Tick(time_t currtime) CXX11_OVERRIDE
71 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
72 : BufferedSocket(newfd)
74 , InternalState(HTTP_SERVE_WAIT_REQUEST)
79 ServerInstance->Timers.AddTimer(this);
82 via->iohookprov->OnAccept(this, client, server);
90 void OnError(BufferedSocketError) CXX11_OVERRIDE
95 std::string Response(int response)
102 return "SWITCHING PROTOCOLS";
110 return "NON-AUTHORITATIVE INFORMATION";
114 return "RESET CONTENT";
116 return "PARTIAL CONTENT";
118 return "MULTIPLE CHOICES";
120 return "MOVED PERMANENTLY";
126 return "NOT MODIFIED";
130 return "TEMPORARY REDIRECT";
132 return "BAD REQUEST";
134 return "UNAUTHORIZED";
136 return "PAYMENT REQUIRED";
142 return "METHOD NOT ALLOWED";
144 return "NOT ACCEPTABLE";
146 return "PROXY AUTHENTICATION REQUIRED";
148 return "REQUEST TIMEOUT";
154 return "LENGTH REQUIRED";
156 return "PRECONDITION FAILED";
158 return "REQUEST ENTITY TOO LARGE";
160 return "REQUEST-URI TOO LONG";
162 return "UNSUPPORTED MEDIA TYPE";
164 return "REQUESTED RANGE NOT SATISFIABLE";
166 return "EXPECTATION FAILED";
168 return "INTERNAL SERVER ERROR";
170 return "NOT IMPLEMENTED";
172 return "BAD GATEWAY";
174 return "SERVICE UNAVAILABLE";
176 return "GATEWAY TIMEOUT";
178 return "HTTP VERSION NOT SUPPORTED";
186 void SendHTTPError(int response)
189 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
190 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
192 SendHeaders(data.length(), response, empty);
196 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
199 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
201 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
202 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
203 rheaders.SetHeader("Content-Length", ConvToStr(size));
206 rheaders.CreateHeader("Content-Type", "text/html");
208 rheaders.RemoveHeader("Content-Type");
210 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
211 * so remove it, its not essential for what we need.
213 rheaders.SetHeader("Connection", "Close");
215 WriteData(rheaders.GetFormattedHeaders());
221 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
223 postdata.append(recvq);
224 if (postdata.length() >= postsize)
229 reqbuffer.append(recvq);
231 if (reqbuffer.length() >= 8192)
233 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
238 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
239 CheckRequestBuffer();
243 void CheckRequestBuffer()
245 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
246 if (reqend == std::string::npos)
249 // We have the headers; parse them all
250 std::string::size_type hbegin = 0, hend;
251 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
256 if (request_type.empty())
258 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
259 cheader >> request_type;
261 cheader >> http_version;
263 if (request_type.empty() || uri.empty() || http_version.empty())
273 std::string cheader(reqbuffer, hbegin, hend - hbegin);
275 std::string::size_type fieldsep = cheader.find(':');
276 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
282 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
287 reqbuffer.erase(0, reqend + 4);
289 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
290 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
292 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
298 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
300 InternalState = HTTP_SERVE_RECV_POSTDATA;
302 if (reqbuffer.length() >= postsize)
304 postdata.assign(reqbuffer, 0, postsize);
305 reqbuffer.erase(0, postsize);
307 else if (!reqbuffer.empty())
309 postdata = reqbuffer;
313 if (postdata.length() >= postsize)
324 InternalState = HTTP_SERVE_SEND_DATA;
326 ModResult MOD_RESULT;
327 HTTPRequest acl(request_type, uri, &headers, this, ip, postdata);
328 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
329 if (MOD_RESULT != MOD_RES_DENY)
331 HTTPRequest url(request_type, uri, &headers, this, ip, postdata);
332 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
333 if (MOD_RESULT == MOD_RES_PASSTHRU)
340 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
342 SendHeaders(n->str().length(), response, *hheaders);
353 ServerInstance->GlobalCulls.AddItem(this);
357 class HTTPdAPIImpl : public HTTPdAPIBase
360 HTTPdAPIImpl(Module* parent)
361 : HTTPdAPIBase(parent)
365 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
367 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
371 class ModuleHttpServer : public Module
373 HTTPdAPIImpl APIImpl;
374 unsigned int timeoutsec;
375 Events::ModuleEventProvider acleventprov;
376 Events::ModuleEventProvider reqeventprov;
381 , acleventprov(this, "event/http-acl")
382 , reqeventprov(this, "event/http-request")
384 aclevprov = &acleventprov;
385 reqevprov = &reqeventprov;
388 void init() CXX11_OVERRIDE
393 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
395 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
396 timeoutsec = tag->getInt("timeout", 10, 1);
399 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
401 if (from->bind_tag->getString("type") != "httpd")
402 return MOD_RES_PASSTHRU;
404 std::string incomingip;
405 irc::sockets::satoap(*client, incomingip, port);
406 sockets.push_front(new HttpServerSocket(nfd, incomingip, from, client, server, timeoutsec));
407 return MOD_RES_ALLOW;
410 CullResult cull() CXX11_OVERRIDE
412 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
414 HttpServerSocket* sock = *i;
417 return Module::cull();
420 Version GetVersion() CXX11_OVERRIDE
422 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
426 MODULE_INIT(ModuleHttpServer)