1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 /* $ModDesc: Provides HTTP serving facilities to modules */
18 /* $ModDep: httpd.h */
20 class ModuleHttpServer;
22 static ModuleHttpServer* HttpModule;
25 /** HTTP socket states
30 HTTP_SERVE_WAIT_REQUEST = 1, /* Waiting for a full request */
31 HTTP_SERVE_RECV_POSTDATA = 2, /* Waiting to finish recieving POST data */
32 HTTP_SERVE_SEND_DATA = 3 /* Sending response */
35 /** A socket used for HTTP transport
37 class HttpServerSocket : public BufferedSocket
40 HttpState InternalState;
43 std::string reqbuffer;
45 unsigned int postsize;
46 std::string request_type;
48 std::string http_version;
53 HttpServerSocket(InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, FileReader* index_page) : BufferedSocket(SI, shost, iport, listening, maxtime), index(index_page), postsize(0)
55 InternalState = HTTP_LISTEN;
58 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : BufferedSocket(SI, newfd, ip), index(ind), postsize(0), keepalive(false)
60 InternalState = HTTP_SERVE_WAIT_REQUEST;
63 FileReader* GetIndex()
72 virtual int OnIncomingConnection(int newsock, char* ip)
74 if (InternalState == HTTP_LISTEN)
76 new HttpServerSocket(this->Instance, newsock, ip, index);
81 virtual void OnClose()
85 std::string Response(int response)
92 return "SWITCHING PROTOCOLS";
100 return "NON-AUTHORITATIVE INFORMATION";
104 return "RESET CONTENT";
106 return "PARTIAL CONTENT";
108 return "MULTIPLE CHOICES";
110 return "MOVED PERMENANTLY";
116 return "NOT MODIFIED";
120 return "TEMPORARY REDIRECT";
122 return "BAD REQUEST";
124 return "UNAUTHORIZED";
126 return "PAYMENT REQUIRED";
132 return "METHOD NOT ALLOWED";
134 return "NOT ACCEPTABLE";
136 return "PROXY AUTHENTICATION REQUIRED";
138 return "REQUEST TIMEOUT";
144 return "LENGTH REQUIRED";
146 return "PRECONDITION FAILED";
148 return "REQUEST ENTITY TOO LARGE";
150 return "REQUEST-URI TOO LONG";
152 return "UNSUPPORTED MEDIA TYPE";
154 return "REQUESTED RANGE NOT SATISFIABLE";
156 return "EXPECTATION FAILED";
158 return "INTERNAL SERVER ERROR";
160 return "NOT IMPLEMENTED";
162 return "BAD GATEWAY";
164 return "SERVICE UNAVAILABLE";
166 return "GATEWAY TIMEOUT";
168 return "HTTP VERSION NOT SUPPORTED";
176 void SendHTTPError(int response)
179 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
180 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
182 SendHeaders(data.length(), response, empty);
186 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
189 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
191 time_t local = this->Instance->Time();
192 struct tm *timeinfo = gmtime(&local);
193 char *date = asctime(timeinfo);
194 date[strlen(date) - 1] = '\0';
195 rheaders.CreateHeader("Date", date);
197 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.1");
198 rheaders.SetHeader("Content-Length", ConvToStr(size));
201 rheaders.CreateHeader("Content-Type", "text/html");
203 rheaders.RemoveHeader("Content-Type");
205 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
206 * so remove it, its not essential for what we need.
208 rheaders.SetHeader("Connection", "Close");
210 this->Write(rheaders.GetFormattedHeaders());
214 virtual bool OnDataReady()
216 const char* data = this->Read();
218 /* Check that the data read is a valid pointer and it has some content */
222 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
224 postdata.append(data);
225 if (postdata.length() >= postsize)
230 reqbuffer.append(data);
232 if (reqbuffer.length() >= 8192)
234 Instance->Logs->Log("m_httpd",DEBUG, "m_httpd dropped connection due to an oversized request buffer");
239 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
240 CheckRequestBuffer();
246 void CheckRequestBuffer()
248 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
249 if (reqend == std::string::npos)
252 // We have the headers; parse them all
253 std::string::size_type hbegin = 0, hend;
254 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
259 if (request_type.empty())
261 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
262 cheader >> request_type;
264 cheader >> http_version;
266 if (request_type.empty() || uri.empty() || http_version.empty())
276 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
278 std::string::size_type fieldsep = cheader.find(':');
279 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
285 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
290 reqbuffer.erase(0, reqend + 4);
292 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
293 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
295 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
301 if (strcasecmp(headers.GetHeader("Connection").c_str(), "keep-alive") == 0)
304 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
306 InternalState = HTTP_SERVE_RECV_POSTDATA;
308 if (reqbuffer.length() >= postsize)
310 postdata = reqbuffer.substr(0, postsize);
311 reqbuffer.erase(0, postsize);
313 else if (!reqbuffer.empty())
315 postdata = reqbuffer;
319 if (postdata.length() >= postsize)
330 InternalState = HTTP_SERVE_SEND_DATA;
332 if ((request_type == "GET") && (uri == "/"))
335 SendHeaders(index->ContentSize(), 200, empty);
336 this->Write(index->Contents());
341 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
342 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
343 e.Send(this->Instance);
351 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
353 SendHeaders(n->str().length(), response, *hheaders);
354 this->Write(n->str());
355 Instance->SE->DelFd(this);
360 class ModuleHttpServer : public Module
362 std::vector<HttpServerSocket*> httpsocks;
370 std::string indexfile;
372 HttpServerSocket* http;
373 ConfigReader c(ServerInstance);
377 for (int i = 0; i < c.Enumerate("http"); i++)
379 host = c.ReadValue("http", "host", i);
380 bindip = c.ReadValue("http", "ip", i);
381 port = c.ReadInteger("http", "port", i, true);
382 indexfile = c.ReadValue("http", "index", i);
383 index = new FileReader(ServerInstance, indexfile);
384 if (!index->Exists())
385 throw ModuleException("Can't read index file: "+indexfile);
386 http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
387 httpsocks.push_back(http);
391 ModuleHttpServer(InspIRCd* Me) : Module(Me)
395 Implementation eventlist[] = { I_OnRequest };
396 ServerInstance->Modules->Attach(eventlist, this, 1);
399 virtual const char* OnRequest(Request* request)
402 HTTPDocument* doc = (HTTPDocument*)request->GetData();
403 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
404 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
409 virtual ~ModuleHttpServer()
411 for (size_t i = 0; i < httpsocks.size(); i++)
413 ServerInstance->SE->DelFd(httpsocks[i]);
414 httpsocks[i]->Close();
415 delete httpsocks[i]->GetIndex();
417 ServerInstance->BufferedSocketCull();
420 virtual Version GetVersion()
422 return Version(1,2,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
426 MODULE_INIT(ModuleHttpServer)