1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
19 /* $ModDesc: Provides HTTP serving facilities to modules */
20 /* $ModDep: httpd.h */
22 class ModuleHttpServer;
24 static ModuleHttpServer* HttpModule;
27 /** HTTP socket states
32 HTTP_SERVE_WAIT_REQUEST = 1, /* Waiting for a full request */
33 HTTP_SERVE_RECV_POSTDATA = 2, /* Waiting to finish recieving POST data */
34 HTTP_SERVE_SEND_DATA = 3 /* Sending response */
37 class HttpServerSocket;
39 /** This class is used to handle HTTP socket timeouts
41 class HttpServerTimeout : public InspTimer
44 /** HttpServerSocket we are attached to
47 /** Socketengine the file descriptor is in
51 /** Attach timeout to HttpServerSocket
53 HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine);
56 void Tick(time_t TIME);
59 /** A socket used for HTTP transport
61 class HttpServerSocket : public InspSocket
64 HttpState InternalState;
67 std::string reqbuffer;
69 unsigned int postsize;
70 std::string request_type;
72 std::string http_version;
75 HttpServerTimeout* Timeout;
76 bool DataSinceLastTick;
77 friend class HttpServerTimeout;
81 HttpServerSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, FileReader* index_page) : InspSocket(SI, host, port, listening, maxtime), index(index_page), postsize(0)
83 InternalState = HTTP_LISTEN;
87 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0), keepalive(false), DataSinceLastTick(false)
89 InternalState = HTTP_SERVE_WAIT_REQUEST;
90 Timeout = new HttpServerTimeout(this, Instance->SE);
91 Instance->Timers->AddTimer(Timeout);
94 FileReader* GetIndex()
103 if (Instance->Time() < Timeout->GetTimer())
104 Instance->Timers->DelTimer(Timeout);
114 request_type.clear();
116 http_version.clear();
117 InternalState = HTTP_SERVE_WAIT_REQUEST;
119 if (reqbuffer.size())
120 CheckRequestBuffer();
123 virtual int OnIncomingConnection(int newsock, char* ip)
125 if (InternalState == HTTP_LISTEN)
127 new HttpServerSocket(this->Instance, newsock, ip, index);
132 virtual void OnClose()
136 std::string Response(int response)
143 return "SWITCHING PROTOCOLS";
151 return "NON-AUTHORITATIVE INFORMATION";
155 return "RESET CONTENT";
157 return "PARTIAL CONTENT";
159 return "MULTIPLE CHOICES";
161 return "MOVED PERMENANTLY";
167 return "NOT MODIFIED";
171 return "TEMPORARY REDIRECT";
173 return "BAD REQUEST";
175 return "UNAUTHORIZED";
177 return "PAYMENT REQUIRED";
183 return "METHOD NOT ALLOWED";
185 return "NOT ACCEPTABLE";
187 return "PROXY AUTHENTICATION REQUIRED";
189 return "REQUEST TIMEOUT";
195 return "LENGTH REQUIRED";
197 return "PRECONDITION FAILED";
199 return "REQUEST ENTITY TOO LARGE";
201 return "REQUEST-URI TOO LONG";
203 return "UNSUPPORTED MEDIA TYPE";
205 return "REQUESTED RANGE NOT SATISFIABLE";
207 return "EXPECTATION FAILED";
209 return "INTERNAL SERVER ERROR";
211 return "NOT IMPLEMENTED";
213 return "BAD GATEWAY";
215 return "SERVICE UNAVAILABLE";
217 return "GATEWAY TIMEOUT";
219 return "HTTP VERSION NOT SUPPORTED";
227 void SendHTTPError(int response)
230 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
231 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
233 SendHeaders(data.length(), response, empty);
240 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
243 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
245 time_t local = this->Instance->Time();
246 struct tm *timeinfo = gmtime(&local);
247 char *date = asctime(timeinfo);
248 date[strlen(date) - 1] = '\0';
249 rheaders.CreateHeader("Date", date);
251 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.1");
252 rheaders.SetHeader("Content-Length", ConvToStr(size));
255 rheaders.CreateHeader("Content-Type", "text/html");
257 rheaders.RemoveHeader("Content-Type");
259 if (rheaders.GetHeader("Connection") == "Close")
261 else if (rheaders.GetHeader("Connection") == "Keep-Alive" && !headers.IsSet("Connection"))
263 else if (!rheaders.IsSet("Connection") && !keepalive)
264 rheaders.SetHeader("Connection", "Close");
266 this->Write(rheaders.GetFormattedHeaders());
269 if (!size && keepalive)
273 virtual bool OnDataReady()
275 char* data = this->Read();
277 /* Check that the data read is a valid pointer and it has some content */
281 DataSinceLastTick = true;
283 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
285 postdata.append(data);
286 if (postdata.length() >= postsize)
291 reqbuffer.append(data);
293 if (reqbuffer.length() >= 8192)
295 Instance->Log(DEBUG, "m_httpd dropped connection due to an oversized request buffer");
300 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
301 CheckRequestBuffer();
307 void CheckRequestBuffer()
309 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
310 if (reqend == std::string::npos)
313 // We have the headers; parse them all
314 std::string::size_type hbegin = 0, hend;
315 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
320 if (request_type.empty())
322 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
323 cheader >> request_type;
325 cheader >> http_version;
327 if (request_type.empty() || uri.empty() || http_version.empty())
337 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
339 std::string::size_type fieldsep = cheader.find(':');
340 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
346 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
351 reqbuffer.erase(0, reqend + 4);
353 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
354 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
356 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
362 if (strcasecmp(headers.GetHeader("Connection").c_str(), "keep-alive") == 0)
365 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
367 InternalState = HTTP_SERVE_RECV_POSTDATA;
369 if (reqbuffer.length() >= postsize)
371 postdata = reqbuffer.substr(0, postsize);
372 reqbuffer.erase(0, postsize);
374 else if (!reqbuffer.empty())
376 postdata = reqbuffer;
380 if (postdata.length() >= postsize)
391 InternalState = HTTP_SERVE_SEND_DATA;
393 if ((request_type == "GET") && (uri == "/"))
396 SendHeaders(index->ContentSize(), 200, empty);
397 this->Write(index->Contents());
402 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
403 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
404 e.Send(this->Instance);
412 void Page(std::stringstream* n, int response, HTTPHeaders *headers)
414 SendHeaders(n->str().length(), response, *headers);
415 this->Write(n->str());
419 Instance->SE->DelFd(this);
423 this->ResetRequest();
427 HttpServerTimeout::HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine) : InspTimer(15, time(NULL), true), s(sock), SE(engine)
431 void HttpServerTimeout::Tick(time_t TIME)
433 if (!s->DataSinceLastTick)
438 this->CancelRepeat();
441 s->DataSinceLastTick = false;
444 class ModuleHttpServer : public Module
446 std::vector<HttpServerSocket*> httpsocks;
454 std::string indexfile;
456 HttpServerSocket* http;
457 ConfigReader c(ServerInstance);
461 for (int i = 0; i < c.Enumerate("http"); i++)
463 host = c.ReadValue("http", "host", i);
464 bindip = c.ReadValue("http", "ip", i);
465 port = c.ReadInteger("http", "port", i, true);
466 indexfile = c.ReadValue("http", "index", i);
467 index = new FileReader(ServerInstance, indexfile);
468 if (!index->Exists())
469 throw ModuleException("Can't read index file: "+indexfile);
470 http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
471 httpsocks.push_back(http);
475 ModuleHttpServer(InspIRCd* Me) : Module(Me)
481 char* OnRequest(Request* request)
484 HTTPDocument* doc = (HTTPDocument*)request->GetData();
485 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
486 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
490 void Implements(char* List)
492 List[I_OnRequest] = 1;
495 virtual ~ModuleHttpServer()
497 for (size_t i = 0; i < httpsocks.size(); i++)
499 ServerInstance->SE->DelFd(httpsocks[i]);
500 httpsocks[i]->Close();
501 delete httpsocks[i]->GetIndex();
503 ServerInstance->InspSocketCull();
506 virtual Version GetVersion()
508 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
512 MODULE_INIT(ModuleHttpServer)