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 class HttpServerSocket;
37 /** This class is used to handle HTTP socket timeouts
39 class HttpServerTimeout : public Timer
42 /** HttpServerSocket we are attached to
45 /** Socketengine the file descriptor is in
49 /** Attach timeout to HttpServerSocket
51 HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine);
54 void Tick(time_t TIME);
57 /** A socket used for HTTP transport
59 class HttpServerSocket : public BufferedSocket
62 HttpState InternalState;
65 std::string reqbuffer;
67 unsigned int postsize;
68 std::string request_type;
70 std::string http_version;
73 HttpServerTimeout* Timeout;
74 bool DataSinceLastTick;
75 friend class HttpServerTimeout;
79 HttpServerSocket(InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, FileReader* index_page) : BufferedSocket(SI, host, port, listening, maxtime), index(index_page), postsize(0)
81 InternalState = HTTP_LISTEN;
85 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : BufferedSocket(SI, newfd, ip), index(ind), postsize(0), keepalive(false), DataSinceLastTick(false)
87 InternalState = HTTP_SERVE_WAIT_REQUEST;
88 Timeout = new HttpServerTimeout(this, Instance->SE);
89 Instance->Timers->AddTimer(Timeout);
92 FileReader* GetIndex()
101 if (Instance->Time() < Timeout->GetTimer())
102 Instance->Timers->DelTimer(Timeout);
112 request_type.clear();
114 http_version.clear();
115 InternalState = HTTP_SERVE_WAIT_REQUEST;
117 if (reqbuffer.size())
118 CheckRequestBuffer();
121 virtual int OnIncomingConnection(int newsock, char* ip)
123 if (InternalState == HTTP_LISTEN)
125 new HttpServerSocket(this->Instance, newsock, ip, index);
130 virtual void OnClose()
134 std::string Response(int response)
141 return "SWITCHING PROTOCOLS";
149 return "NON-AUTHORITATIVE INFORMATION";
153 return "RESET CONTENT";
155 return "PARTIAL CONTENT";
157 return "MULTIPLE CHOICES";
159 return "MOVED PERMENANTLY";
165 return "NOT MODIFIED";
169 return "TEMPORARY REDIRECT";
171 return "BAD REQUEST";
173 return "UNAUTHORIZED";
175 return "PAYMENT REQUIRED";
181 return "METHOD NOT ALLOWED";
183 return "NOT ACCEPTABLE";
185 return "PROXY AUTHENTICATION REQUIRED";
187 return "REQUEST TIMEOUT";
193 return "LENGTH REQUIRED";
195 return "PRECONDITION FAILED";
197 return "REQUEST ENTITY TOO LARGE";
199 return "REQUEST-URI TOO LONG";
201 return "UNSUPPORTED MEDIA TYPE";
203 return "REQUESTED RANGE NOT SATISFIABLE";
205 return "EXPECTATION FAILED";
207 return "INTERNAL SERVER ERROR";
209 return "NOT IMPLEMENTED";
211 return "BAD GATEWAY";
213 return "SERVICE UNAVAILABLE";
215 return "GATEWAY TIMEOUT";
217 return "HTTP VERSION NOT SUPPORTED";
225 void SendHTTPError(int response)
228 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
229 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
231 SendHeaders(data.length(), response, empty);
238 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
241 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
243 time_t local = this->Instance->Time();
244 struct tm *timeinfo = gmtime(&local);
245 char *date = asctime(timeinfo);
246 date[strlen(date) - 1] = '\0';
247 rheaders.CreateHeader("Date", date);
249 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.1");
250 rheaders.SetHeader("Content-Length", ConvToStr(size));
253 rheaders.CreateHeader("Content-Type", "text/html");
255 rheaders.RemoveHeader("Content-Type");
257 if (rheaders.GetHeader("Connection") == "Close")
259 else if (rheaders.GetHeader("Connection") == "Keep-Alive" && !headers.IsSet("Connection"))
261 else if (!rheaders.IsSet("Connection") && !keepalive)
262 rheaders.SetHeader("Connection", "Close");
264 this->Write(rheaders.GetFormattedHeaders());
267 if (!size && keepalive)
271 virtual bool OnDataReady()
273 char* data = this->Read();
275 /* Check that the data read is a valid pointer and it has some content */
279 DataSinceLastTick = true;
281 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
283 postdata.append(data);
284 if (postdata.length() >= postsize)
289 reqbuffer.append(data);
291 if (reqbuffer.length() >= 8192)
293 Instance->Log(DEBUG, "m_httpd dropped connection due to an oversized request buffer");
298 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
299 CheckRequestBuffer();
305 void CheckRequestBuffer()
307 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
308 if (reqend == std::string::npos)
311 // We have the headers; parse them all
312 std::string::size_type hbegin = 0, hend;
313 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
318 if (request_type.empty())
320 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
321 cheader >> request_type;
323 cheader >> http_version;
325 if (request_type.empty() || uri.empty() || http_version.empty())
335 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
337 std::string::size_type fieldsep = cheader.find(':');
338 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
344 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
349 reqbuffer.erase(0, reqend + 4);
351 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
352 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
354 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
360 if (strcasecmp(headers.GetHeader("Connection").c_str(), "keep-alive") == 0)
363 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
365 InternalState = HTTP_SERVE_RECV_POSTDATA;
367 if (reqbuffer.length() >= postsize)
369 postdata = reqbuffer.substr(0, postsize);
370 reqbuffer.erase(0, postsize);
372 else if (!reqbuffer.empty())
374 postdata = reqbuffer;
378 if (postdata.length() >= postsize)
389 InternalState = HTTP_SERVE_SEND_DATA;
391 if ((request_type == "GET") && (uri == "/"))
394 SendHeaders(index->ContentSize(), 200, empty);
395 this->Write(index->Contents());
400 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
401 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
402 e.Send(this->Instance);
410 void Page(std::stringstream* n, int response, HTTPHeaders *headers)
412 SendHeaders(n->str().length(), response, *headers);
413 this->Write(n->str());
417 Instance->SE->DelFd(this);
421 this->ResetRequest();
425 HttpServerTimeout::HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine) : Timer(15, time(NULL), true), s(sock), SE(engine)
429 void HttpServerTimeout::Tick(time_t TIME)
431 if (!s->DataSinceLastTick)
436 this->CancelRepeat();
439 s->DataSinceLastTick = false;
442 class ModuleHttpServer : public Module
444 std::vector<HttpServerSocket*> httpsocks;
452 std::string indexfile;
454 HttpServerSocket* http;
455 ConfigReader c(ServerInstance);
459 for (int i = 0; i < c.Enumerate("http"); i++)
461 host = c.ReadValue("http", "host", i);
462 bindip = c.ReadValue("http", "ip", i);
463 port = c.ReadInteger("http", "port", i, true);
464 indexfile = c.ReadValue("http", "index", i);
465 index = new FileReader(ServerInstance, indexfile);
466 if (!index->Exists())
467 throw ModuleException("Can't read index file: "+indexfile);
468 http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
469 httpsocks.push_back(http);
473 ModuleHttpServer(InspIRCd* Me) : Module(Me)
477 Implementation eventlist[] = { I_OnRequest };
478 ServerInstance->Modules->Attach(eventlist, this, 1);
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);
491 virtual ~ModuleHttpServer()
493 for (size_t i = 0; i < httpsocks.size(); i++)
495 ServerInstance->SE->DelFd(httpsocks[i]);
496 httpsocks[i]->Close();
497 delete httpsocks[i]->GetIndex();
499 ServerInstance->BufferedSocketCull();
502 virtual Version GetVersion()
504 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
508 MODULE_INIT(ModuleHttpServer)