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/>.
28 /* $ModDesc: Provides HTTP serving facilities to modules */
29 /* $ModDep: 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;
62 HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
63 : BufferedSocket(newfd), ip(IP), postsize(0)
65 InternalState = HTTP_SERVE_WAIT_REQUEST;
67 FOREACH_MOD(I_OnHookIO, OnHookIO(this, via));
69 GetIOHook()->OnStreamSocketAccept(this, client, server);
72 virtual void OnError(BufferedSocketError)
74 ServerInstance->GlobalCulls.AddItem(this);
77 std::string Response(int response)
84 return "SWITCHING PROTOCOLS";
92 return "NON-AUTHORITATIVE INFORMATION";
96 return "RESET CONTENT";
98 return "PARTIAL CONTENT";
100 return "MULTIPLE CHOICES";
102 return "MOVED PERMENANTLY";
108 return "NOT MODIFIED";
112 return "TEMPORARY REDIRECT";
114 return "BAD REQUEST";
116 return "UNAUTHORIZED";
118 return "PAYMENT REQUIRED";
124 return "METHOD NOT ALLOWED";
126 return "NOT ACCEPTABLE";
128 return "PROXY AUTHENTICATION REQUIRED";
130 return "REQUEST TIMEOUT";
136 return "LENGTH REQUIRED";
138 return "PRECONDITION FAILED";
140 return "REQUEST ENTITY TOO LARGE";
142 return "REQUEST-URI TOO LONG";
144 return "UNSUPPORTED MEDIA TYPE";
146 return "REQUESTED RANGE NOT SATISFIABLE";
148 return "EXPECTATION FAILED";
150 return "INTERNAL SERVER ERROR";
152 return "NOT IMPLEMENTED";
154 return "BAD GATEWAY";
156 return "SERVICE UNAVAILABLE";
158 return "GATEWAY TIMEOUT";
160 return "HTTP VERSION NOT SUPPORTED";
168 void SendHTTPError(int response)
171 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
172 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
174 SendHeaders(data.length(), response, empty);
178 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
181 WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
183 time_t local = ServerInstance->Time();
184 struct tm *timeinfo = gmtime(&local);
185 char *date = asctime(timeinfo);
186 date[strlen(date) - 1] = '\0';
187 rheaders.CreateHeader("Date", date);
189 rheaders.CreateHeader("Server", BRANCH);
190 rheaders.SetHeader("Content-Length", ConvToStr(size));
193 rheaders.CreateHeader("Content-Type", "text/html");
195 rheaders.RemoveHeader("Content-Type");
197 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
198 * so remove it, its not essential for what we need.
200 rheaders.SetHeader("Connection", "Close");
202 WriteData(rheaders.GetFormattedHeaders());
208 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
210 postdata.append(recvq);
211 if (postdata.length() >= postsize)
216 reqbuffer.append(recvq);
218 if (reqbuffer.length() >= 8192)
220 ServerInstance->Logs->Log("m_httpd",DEBUG, "m_httpd dropped connection due to an oversized request buffer");
225 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
226 CheckRequestBuffer();
230 void CheckRequestBuffer()
232 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
233 if (reqend == std::string::npos)
236 // We have the headers; parse them all
237 std::string::size_type hbegin = 0, hend;
238 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
243 if (request_type.empty())
245 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
246 cheader >> request_type;
248 cheader >> http_version;
250 if (request_type.empty() || uri.empty() || http_version.empty())
260 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
262 std::string::size_type fieldsep = cheader.find(':');
263 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
269 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
274 reqbuffer.erase(0, reqend + 4);
276 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
277 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
279 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
285 if (headers.IsSet("Content-Length") && (postsize = ConvToInt(headers.GetHeader("Content-Length"))) > 0)
287 InternalState = HTTP_SERVE_RECV_POSTDATA;
289 if (reqbuffer.length() >= postsize)
291 postdata = reqbuffer.substr(0, postsize);
292 reqbuffer.erase(0, postsize);
294 else if (!reqbuffer.empty())
296 postdata = reqbuffer;
300 if (postdata.length() >= postsize)
311 InternalState = HTTP_SERVE_SEND_DATA;
314 HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata);
318 HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata);
327 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
329 SendHeaders(n->str().length(), response, *hheaders);
334 class ModuleHttpServer : public Module
336 std::vector<HttpServerSocket *> httpsocks;
342 ServerInstance->Modules->Attach(I_OnAcceptConnection, this);
345 void OnRequest(Request& request)
347 if (strcmp(request.id, "HTTP-DOC") != 0)
349 HTTPDocumentResponse& resp = static_cast<HTTPDocumentResponse&>(request);
351 resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers);
354 ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
356 if (from->bind_tag->getString("type") != "httpd")
357 return MOD_RES_PASSTHRU;
359 std::string incomingip;
360 irc::sockets::satoap(*client, incomingip, port);
361 new HttpServerSocket(nfd, incomingip, from, client, server);
362 return MOD_RES_ALLOW;
366 virtual ~ModuleHttpServer()
368 for (size_t i = 0; i < httpsocks.size(); i++)
370 httpsocks[i]->cull();
375 virtual Version GetVersion()
377 return Version("Provides HTTP serving facilities to modules", VF_VENDOR);
381 MODULE_INIT(ModuleHttpServer)