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;
52 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)
54 InternalState = HTTP_LISTEN;
57 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : BufferedSocket(SI, newfd, ip), index(ind), postsize(0)
59 InternalState = HTTP_SERVE_WAIT_REQUEST;
62 FileReader* GetIndex()
71 virtual int OnIncomingConnection(int newsock, char* ip)
73 if (InternalState == HTTP_LISTEN)
75 new HttpServerSocket(this->Instance, newsock, ip, index);
80 virtual void OnClose()
84 std::string Response(int response)
91 return "SWITCHING PROTOCOLS";
99 return "NON-AUTHORITATIVE INFORMATION";
103 return "RESET CONTENT";
105 return "PARTIAL CONTENT";
107 return "MULTIPLE CHOICES";
109 return "MOVED PERMENANTLY";
115 return "NOT MODIFIED";
119 return "TEMPORARY REDIRECT";
121 return "BAD REQUEST";
123 return "UNAUTHORIZED";
125 return "PAYMENT REQUIRED";
131 return "METHOD NOT ALLOWED";
133 return "NOT ACCEPTABLE";
135 return "PROXY AUTHENTICATION REQUIRED";
137 return "REQUEST TIMEOUT";
143 return "LENGTH REQUIRED";
145 return "PRECONDITION FAILED";
147 return "REQUEST ENTITY TOO LARGE";
149 return "REQUEST-URI TOO LONG";
151 return "UNSUPPORTED MEDIA TYPE";
153 return "REQUESTED RANGE NOT SATISFIABLE";
155 return "EXPECTATION FAILED";
157 return "INTERNAL SERVER ERROR";
159 return "NOT IMPLEMENTED";
161 return "BAD GATEWAY";
163 return "SERVICE UNAVAILABLE";
165 return "GATEWAY TIMEOUT";
167 return "HTTP VERSION NOT SUPPORTED";
175 void SendHTTPError(int response)
178 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
179 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
181 SendHeaders(data.length(), response, empty);
183 this->FlushWriteBuffer();
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.2");
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())
277 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
279 std::string::size_type fieldsep = cheader.find(':');
280 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
287 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
292 reqbuffer.erase(0, reqend + 4);
294 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
295 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
297 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.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());
337 this->FlushWriteBuffer();
343 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
344 Event acl((char*)&httpr, (Module*)HttpModule, "httpd_acl");
345 acl.Send(this->Instance);
348 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
349 e.Send(this->Instance);
362 Instance->Logs->Log("m_httpd",DEBUG,"OnWriteReady()");
366 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
368 SendHeaders(n->str().length(), response, *hheaders);
369 this->Write(n->str());
370 this->FlushWriteBuffer();
376 Instance->Logs->Log("m_httpd",DEBUG,"SetWrite()");
377 this->WaitingForWriteEvent = true;
378 Instance->SE->WantWrite(this);
382 class ModuleHttpServer : public Module
384 std::vector<HttpServerSocket*> httpsocks;
392 std::string indexfile;
394 HttpServerSocket* http;
395 ConfigReader c(ServerInstance);
399 for (int i = 0; i < c.Enumerate("http"); i++)
401 host = c.ReadValue("http", "host", i);
402 bindip = c.ReadValue("http", "ip", i);
403 port = c.ReadInteger("http", "port", i, true);
404 indexfile = c.ReadValue("http", "index", i);
405 index = new FileReader(ServerInstance, indexfile);
406 if (!index->Exists())
407 throw ModuleException("Can't read index file: "+indexfile);
408 http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
409 httpsocks.push_back(http);
413 ModuleHttpServer(InspIRCd* Me) : Module(Me)
417 Implementation eventlist[] = { I_OnRequest };
418 ServerInstance->Modules->Attach(eventlist, this, 1);
421 virtual const char* OnRequest(Request* request)
424 HTTPDocument* doc = (HTTPDocument*)request->GetData();
425 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
426 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
431 virtual ~ModuleHttpServer()
433 for (size_t i = 0; i < httpsocks.size(); i++)
435 ServerInstance->SE->DelFd(httpsocks[i]);
436 httpsocks[i]->Close();
437 delete httpsocks[i]->GetIndex();
439 ServerInstance->BufferedSocketCull();
442 virtual Version GetVersion()
444 return Version(1,2,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
448 MODULE_INIT(ModuleHttpServer)