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;
34 /** HTTP socket states
38 HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
39 HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
40 HTTP_SERVE_SEND_DATA = 2 /* Sending response */
43 /** A socket used for HTTP transport
45 class HttpServerSocket : public BufferedSocket
47 HttpState InternalState;
51 std::string reqbuffer;
53 unsigned int postsize;
54 std::string request_type;
56 std::string http_version;
59 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
60 : BufferedSocket(newfd), ip(IP), postsize(0)
62 InternalState = HTTP_SERVE_WAIT_REQUEST;
64 FOREACH_MOD(OnHookIO, (this, via));
66 GetIOHook()->OnStreamSocketAccept(this, client, server);
69 void OnError(BufferedSocketError) CXX11_OVERRIDE
71 ServerInstance->GlobalCulls.AddItem(this);
74 std::string Response(int response)
81 return "SWITCHING PROTOCOLS";
89 return "NON-AUTHORITATIVE INFORMATION";
93 return "RESET CONTENT";
95 return "PARTIAL CONTENT";
97 return "MULTIPLE CHOICES";
99 return "MOVED PERMENANTLY";
105 return "NOT MODIFIED";
109 return "TEMPORARY REDIRECT";
111 return "BAD REQUEST";
113 return "UNAUTHORIZED";
115 return "PAYMENT REQUIRED";
121 return "METHOD NOT ALLOWED";
123 return "NOT ACCEPTABLE";
125 return "PROXY AUTHENTICATION REQUIRED";
127 return "REQUEST TIMEOUT";
133 return "LENGTH REQUIRED";
135 return "PRECONDITION FAILED";
137 return "REQUEST ENTITY TOO LARGE";
139 return "REQUEST-URI TOO LONG";
141 return "UNSUPPORTED MEDIA TYPE";
143 return "REQUESTED RANGE NOT SATISFIABLE";
145 return "EXPECTATION FAILED";
147 return "INTERNAL SERVER ERROR";
149 return "NOT IMPLEMENTED";
151 return "BAD GATEWAY";
153 return "SERVICE UNAVAILABLE";
155 return "GATEWAY TIMEOUT";
157 return "HTTP VERSION NOT SUPPORTED";
165 void SendHTTPError(int response)
168 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
169 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
171 SendHeaders(data.length(), response, empty);
175 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
178 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
180 time_t local = ServerInstance->Time();
181 struct tm *timeinfo = gmtime(&local);
182 char *date = asctime(timeinfo);
183 date[strlen(date) - 1] = '\0';
184 rheaders.CreateHeader("Date", date);
186 rheaders.CreateHeader("Server", BRANCH);
187 rheaders.SetHeader("Content-Length", ConvToStr(size));
190 rheaders.CreateHeader("Content-Type", "text/html");
192 rheaders.RemoveHeader("Content-Type");
194 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
195 * so remove it, its not essential for what we need.
197 rheaders.SetHeader("Connection", "Close");
199 WriteData(rheaders.GetFormattedHeaders());
205 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
207 postdata.append(recvq);
208 if (postdata.length() >= postsize)
213 reqbuffer.append(recvq);
215 if (reqbuffer.length() >= 8192)
217 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
222 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
223 CheckRequestBuffer();
227 void CheckRequestBuffer()
229 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
230 if (reqend == std::string::npos)
233 // We have the headers; parse them all
234 std::string::size_type hbegin = 0, hend;
235 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
240 if (request_type.empty())
242 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
243 cheader >> request_type;
245 cheader >> http_version;
247 if (request_type.empty() || uri.empty() || http_version.empty())
257 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
259 std::string::size_type fieldsep = cheader.find(':');
260 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
266 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
271 reqbuffer.erase(0, reqend + 4);
273 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
274 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
276 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
282 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
284 InternalState = HTTP_SERVE_RECV_POSTDATA;
286 if (reqbuffer.length() >= postsize)
288 postdata = reqbuffer.substr(0, postsize);
289 reqbuffer.erase(0, postsize);
291 else if (!reqbuffer.empty())
293 postdata = reqbuffer;
297 if (postdata.length() >= postsize)
308 InternalState = HTTP_SERVE_SEND_DATA;
311 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
315 HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
324 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
326 SendHeaders(n->str().length(), response, *hheaders);
331 class HTTPdAPIImpl : public HTTPdAPIBase
334 HTTPdAPIImpl(Module* parent)
335 : HTTPdAPIBase(parent)
339 void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE
342 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
346 class ModuleHttpServer : public Module
348 std::vector<HttpServerSocket *> httpsocks;
349 HTTPdAPIImpl APIImpl;
357 void init() CXX11_OVERRIDE
362 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
364 if (from->bind_tag->getString("type") != "httpd")
365 return MOD_RES_PASSTHRU;
367 std::string incomingip;
368 irc::sockets::satoap(*client, incomingip, port);
369 new HttpServerSocket(nfd, incomingip, from, client, server);
370 return MOD_RES_ALLOW;
375 for (size_t i = 0; i < httpsocks.size(); i++)
377 httpsocks[i]->cull();
382 Version GetVersion() CXX11_OVERRIDE
384 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
388 MODULE_INIT(ModuleHttpServer)