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/>.
26 #include "modules/httpd.h"
28 /* $ModDesc: Provides HTTP serving facilities to modules */
29 /* $ModDep: modules/httpd.h */
31 class ModuleHttpServer;
33 static ModuleHttpServer* HttpModule;
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
49 HttpState InternalState;
53 std::string reqbuffer;
55 unsigned int postsize;
56 std::string request_type;
58 std::string http_version;
61 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
62 : BufferedSocket(newfd), ip(IP), postsize(0)
64 InternalState = HTTP_SERVE_WAIT_REQUEST;
66 FOREACH_MOD(I_OnHookIO, OnHookIO(this, via));
68 GetIOHook()->OnStreamSocketAccept(this, client, server);
71 void OnError(BufferedSocketError) CXX11_OVERRIDE
73 ServerInstance->GlobalCulls.AddItem(this);
76 std::string Response(int response)
83 return "SWITCHING PROTOCOLS";
91 return "NON-AUTHORITATIVE INFORMATION";
95 return "RESET CONTENT";
97 return "PARTIAL CONTENT";
99 return "MULTIPLE CHOICES";
101 return "MOVED PERMENANTLY";
107 return "NOT MODIFIED";
111 return "TEMPORARY REDIRECT";
113 return "BAD REQUEST";
115 return "UNAUTHORIZED";
117 return "PAYMENT REQUIRED";
123 return "METHOD NOT ALLOWED";
125 return "NOT ACCEPTABLE";
127 return "PROXY AUTHENTICATION REQUIRED";
129 return "REQUEST TIMEOUT";
135 return "LENGTH REQUIRED";
137 return "PRECONDITION FAILED";
139 return "REQUEST ENTITY TOO LARGE";
141 return "REQUEST-URI TOO LONG";
143 return "UNSUPPORTED MEDIA TYPE";
145 return "REQUESTED RANGE NOT SATISFIABLE";
147 return "EXPECTATION FAILED";
149 return "INTERNAL SERVER ERROR";
151 return "NOT IMPLEMENTED";
153 return "BAD GATEWAY";
155 return "SERVICE UNAVAILABLE";
157 return "GATEWAY TIMEOUT";
159 return "HTTP VERSION NOT SUPPORTED";
167 void SendHTTPError(int response)
170 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
171 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
173 SendHeaders(data.length(), response, empty);
177 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
180 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
182 time_t local = ServerInstance->Time();
183 struct tm *timeinfo = gmtime(&local);
184 char *date = asctime(timeinfo);
185 date[strlen(date) - 1] = '\0';
186 rheaders.CreateHeader("Date", date);
188 rheaders.CreateHeader("Server", BRANCH);
189 rheaders.SetHeader("Content-Length", ConvToStr(size));
192 rheaders.CreateHeader("Content-Type", "text/html");
194 rheaders.RemoveHeader("Content-Type");
196 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
197 * so remove it, its not essential for what we need.
199 rheaders.SetHeader("Connection", "Close");
201 WriteData(rheaders.GetFormattedHeaders());
207 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
209 postdata.append(recvq);
210 if (postdata.length() >= postsize)
215 reqbuffer.append(recvq);
217 if (reqbuffer.length() >= 8192)
219 ServerInstance->Logs->Log("m_httpd",LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer");
224 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
225 CheckRequestBuffer();
229 void CheckRequestBuffer()
231 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
232 if (reqend == std::string::npos)
235 // We have the headers; parse them all
236 std::string::size_type hbegin = 0, hend;
237 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
242 if (request_type.empty())
244 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
245 cheader >> request_type;
247 cheader >> http_version;
249 if (request_type.empty() || uri.empty() || http_version.empty())
259 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
261 std::string::size_type fieldsep = cheader.find(':');
262 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
268 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
273 reqbuffer.erase(0, reqend + 4);
275 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
276 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
278 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
284 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
286 InternalState = HTTP_SERVE_RECV_POSTDATA;
288 if (reqbuffer.length() >= postsize)
290 postdata = reqbuffer.substr(0, postsize);
291 reqbuffer.erase(0, postsize);
293 else if (!reqbuffer.empty())
295 postdata = reqbuffer;
299 if (postdata.length() >= postsize)
310 InternalState = HTTP_SERVE_SEND_DATA;
313 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
317 HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
326 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
328 SendHeaders(n->str().length(), response, *hheaders);
333 class ModuleHttpServer : public Module
335 std::vector<HttpServerSocket *> httpsocks;
338 void init() CXX11_OVERRIDE
341 ServerInstance->Modules->Attach(I_OnAcceptConnection, this);
344 void OnRequest(Request& request) CXX11_OVERRIDE
346 if (strcmp(request.id, "HTTP-DOC") != 0)
348 HTTPDocumentResponse& resp = static_cast<HTTPDocumentResponse&>(request);
350 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
353 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
355 if (from->bind_tag->getString("type") != "httpd")
356 return MOD_RES_PASSTHRU;
358 std::string incomingip;
359 irc::sockets::satoap(*client, incomingip, port);
360 new HttpServerSocket(nfd, incomingip, from, client, server);
361 return MOD_RES_ALLOW;
366 for (size_t i = 0; i < httpsocks.size(); i++)
368 httpsocks[i]->cull();
373 Version GetVersion() CXX11_OVERRIDE
375 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
379 MODULE_INIT(ModuleHttpServer)