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 if ((!via->iohookprovs.empty()) && (via->iohookprovs.back()))
81 via->iohookprovs.back()->OnAccept(this, client, server);
82 // IOHook may have errored
83 if (!getError().empty())
90 ServerInstance->Timers.AddTimer(this);
98 void OnError(BufferedSocketError) CXX11_OVERRIDE
103 std::string Response(unsigned int response)
110 return "SWITCHING PROTOCOLS";
118 return "NON-AUTHORITATIVE INFORMATION";
122 return "RESET CONTENT";
124 return "PARTIAL CONTENT";
126 return "MULTIPLE CHOICES";
128 return "MOVED PERMANENTLY";
134 return "NOT MODIFIED";
138 return "TEMPORARY REDIRECT";
140 return "BAD REQUEST";
142 return "UNAUTHORIZED";
144 return "PAYMENT REQUIRED";
150 return "METHOD NOT ALLOWED";
152 return "NOT ACCEPTABLE";
154 return "PROXY AUTHENTICATION REQUIRED";
156 return "REQUEST TIMEOUT";
162 return "LENGTH REQUIRED";
164 return "PRECONDITION FAILED";
166 return "REQUEST ENTITY TOO LARGE";
168 return "REQUEST-URI TOO LONG";
170 return "UNSUPPORTED MEDIA TYPE";
172 return "REQUESTED RANGE NOT SATISFIABLE";
174 return "EXPECTATION FAILED";
176 return "INTERNAL SERVER ERROR";
178 return "NOT IMPLEMENTED";
180 return "BAD GATEWAY";
182 return "SERVICE UNAVAILABLE";
184 return "GATEWAY TIMEOUT";
186 return "HTTP VERSION NOT SUPPORTED";
194 void SendHTTPError(unsigned int response)
197 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
198 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
200 SendHeaders(data.length(), response, empty);
204 void SendHeaders(unsigned long size, unsigned int response, HTTPHeaders &rheaders)
207 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
209 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
210 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
211 rheaders.SetHeader("Content-Length", ConvToStr(size));
214 rheaders.CreateHeader("Content-Type", "text/html");
216 rheaders.RemoveHeader("Content-Type");
218 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
219 * so remove it, its not essential for what we need.
221 rheaders.SetHeader("Connection", "Close");
223 WriteData(rheaders.GetFormattedHeaders());
227 void OnDataReady() CXX11_OVERRIDE
229 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
231 postdata.append(recvq);
232 if (postdata.length() >= postsize)
237 reqbuffer.append(recvq);
239 if (reqbuffer.length() >= 8192)
241 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
246 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
247 CheckRequestBuffer();
251 void CheckRequestBuffer()
253 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
254 if (reqend == std::string::npos)
257 // We have the headers; parse them all
258 std::string::size_type hbegin = 0, hend;
259 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
264 if (request_type.empty())
266 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
267 cheader >> request_type;
269 cheader >> http_version;
271 if (request_type.empty() || uri.empty() || http_version.empty())
281 std::string cheader(reqbuffer, hbegin, hend - hbegin);
283 std::string::size_type fieldsep = cheader.find(':');
284 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
290 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
295 reqbuffer.erase(0, reqend + 4);
297 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
298 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
300 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
306 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
308 InternalState = HTTP_SERVE_RECV_POSTDATA;
310 if (reqbuffer.length() >= postsize)
312 postdata.assign(reqbuffer, 0, postsize);
313 reqbuffer.erase(0, postsize);
315 else if (!reqbuffer.empty())
317 postdata = reqbuffer;
321 if (postdata.length() >= postsize)
332 InternalState = HTTP_SERVE_SEND_DATA;
334 ModResult MOD_RESULT;
335 HTTPRequest acl(request_type, uri, &headers, this, ip, postdata);
336 FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl));
337 if (MOD_RESULT != MOD_RES_DENY)
339 HTTPRequest url(request_type, uri, &headers, this, ip, postdata);
340 FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url));
341 if (MOD_RESULT == MOD_RES_PASSTHRU)
348 void Page(std::stringstream* n, unsigned int response, HTTPHeaders *hheaders)
350 SendHeaders(n->str().length(), response, *hheaders);
362 ServerInstance->GlobalCulls.AddItem(this);
366 class HTTPdAPIImpl : public HTTPdAPIBase
369 HTTPdAPIImpl(Module* parent)
370 : HTTPdAPIBase(parent)
374 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
376 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
380 class ModuleHttpServer : public Module
382 HTTPdAPIImpl APIImpl;
383 unsigned int timeoutsec;
384 Events::ModuleEventProvider acleventprov;
385 Events::ModuleEventProvider reqeventprov;
390 , acleventprov(this, "event/http-acl")
391 , reqeventprov(this, "event/http-request")
393 aclevprov = &acleventprov;
394 reqevprov = &reqeventprov;
397 void init() CXX11_OVERRIDE
402 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
404 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
405 timeoutsec = tag->getDuration("timeout", 10, 1);
408 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
410 if (!stdalgo::string::equalsci(from->bind_tag->getString("type"), "httpd"))
411 return MOD_RES_PASSTHRU;
413 sockets.push_front(new HttpServerSocket(nfd, client->addr(), from, client, server, timeoutsec));
414 return MOD_RES_ALLOW;
417 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
419 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); )
421 HttpServerSocket* sock = *i;
423 if (sock->GetModHook(mod))
431 CullResult cull() CXX11_OVERRIDE
433 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
435 HttpServerSocket* sock = *i;
438 return Module::cull();
441 Version GetVersion() CXX11_OVERRIDE
443 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
447 MODULE_INIT(ModuleHttpServer)