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;
35 /** HTTP socket states
39 HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
40 HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
41 HTTP_SERVE_SEND_DATA = 2 /* Sending response */
44 /** A socket used for HTTP transport
46 class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket>
48 HttpState InternalState;
52 std::string reqbuffer;
54 unsigned int postsize;
55 std::string request_type;
57 std::string http_version;
59 /** True if this object is in the cull list
63 bool Tick(time_t currtime) CXX11_OVERRIDE
70 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec)
71 : BufferedSocket(newfd)
73 , InternalState(HTTP_SERVE_WAIT_REQUEST)
78 ServerInstance->Timers.AddTimer(this);
81 via->iohookprov->OnAccept(this, client, server);
89 void OnError(BufferedSocketError) CXX11_OVERRIDE
94 std::string Response(int response)
101 return "SWITCHING PROTOCOLS";
109 return "NON-AUTHORITATIVE INFORMATION";
113 return "RESET CONTENT";
115 return "PARTIAL CONTENT";
117 return "MULTIPLE CHOICES";
119 return "MOVED PERMANENTLY";
125 return "NOT MODIFIED";
129 return "TEMPORARY REDIRECT";
131 return "BAD REQUEST";
133 return "UNAUTHORIZED";
135 return "PAYMENT REQUIRED";
141 return "METHOD NOT ALLOWED";
143 return "NOT ACCEPTABLE";
145 return "PROXY AUTHENTICATION REQUIRED";
147 return "REQUEST TIMEOUT";
153 return "LENGTH REQUIRED";
155 return "PRECONDITION FAILED";
157 return "REQUEST ENTITY TOO LARGE";
159 return "REQUEST-URI TOO LONG";
161 return "UNSUPPORTED MEDIA TYPE";
163 return "REQUESTED RANGE NOT SATISFIABLE";
165 return "EXPECTATION FAILED";
167 return "INTERNAL SERVER ERROR";
169 return "NOT IMPLEMENTED";
171 return "BAD GATEWAY";
173 return "SERVICE UNAVAILABLE";
175 return "GATEWAY TIMEOUT";
177 return "HTTP VERSION NOT SUPPORTED";
185 void SendHTTPError(int response)
188 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
189 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
191 SendHeaders(data.length(), response, empty);
195 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
198 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
200 rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true));
201 rheaders.CreateHeader("Server", INSPIRCD_BRANCH);
202 rheaders.SetHeader("Content-Length", ConvToStr(size));
205 rheaders.CreateHeader("Content-Type", "text/html");
207 rheaders.RemoveHeader("Content-Type");
209 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
210 * so remove it, its not essential for what we need.
212 rheaders.SetHeader("Connection", "Close");
214 WriteData(rheaders.GetFormattedHeaders());
220 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
222 postdata.append(recvq);
223 if (postdata.length() >= postsize)
228 reqbuffer.append(recvq);
230 if (reqbuffer.length() >= 8192)
232 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
237 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
238 CheckRequestBuffer();
242 void CheckRequestBuffer()
244 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
245 if (reqend == std::string::npos)
248 // We have the headers; parse them all
249 std::string::size_type hbegin = 0, hend;
250 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
255 if (request_type.empty())
257 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
258 cheader >> request_type;
260 cheader >> http_version;
262 if (request_type.empty() || uri.empty() || http_version.empty())
272 std::string cheader(reqbuffer, hbegin, hend - hbegin);
274 std::string::size_type fieldsep = cheader.find(':');
275 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
281 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
286 reqbuffer.erase(0, reqend + 4);
288 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
289 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
291 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
297 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
299 InternalState = HTTP_SERVE_RECV_POSTDATA;
301 if (reqbuffer.length() >= postsize)
303 postdata.assign(reqbuffer, 0, postsize);
304 reqbuffer.erase(0, postsize);
306 else if (!reqbuffer.empty())
308 postdata = reqbuffer;
312 if (postdata.length() >= postsize)
323 InternalState = HTTP_SERVE_SEND_DATA;
326 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
330 HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
339 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
341 SendHeaders(n->str().length(), response, *hheaders);
352 ServerInstance->GlobalCulls.AddItem(this);
356 class HTTPdAPIImpl : public HTTPdAPIBase
359 HTTPdAPIImpl(Module* parent)
360 : HTTPdAPIBase(parent)
364 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;
382 void init() CXX11_OVERRIDE
387 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
389 ConfigTag* tag = ServerInstance->Config->ConfValue("httpd");
390 timeoutsec = tag->getInt("timeout", 10, 1);
393 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
395 if (from->bind_tag->getString("type") != "httpd")
396 return MOD_RES_PASSTHRU;
398 std::string incomingip;
399 irc::sockets::satoap(*client, incomingip, port);
400 sockets.push_front(new HttpServerSocket(nfd, incomingip, from, client, server, timeoutsec));
401 return MOD_RES_ALLOW;
404 CullResult cull() CXX11_OVERRIDE
406 for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i)
408 HttpServerSocket* sock = *i;
411 return Module::cull();
414 Version GetVersion() CXX11_OVERRIDE
416 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
420 MODULE_INIT(ModuleHttpServer)