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 */
21 class ModuleHttpServer;
23 static ModuleHttpServer* HttpModule;
26 /** HTTP socket states
31 HTTP_SERVE_WAIT_REQUEST = 1,
32 HTTP_SERVE_RECV_POSTDATA = 2,
33 HTTP_SERVE_SEND_DATA = 3
36 class HttpServerSocket;
38 /** This class is used to handle HTTP socket timeouts
40 class HttpServerTimeout : public InspTimer
43 /** HttpServerSocket we are attached to
46 /** Socketengine the file descriptor is in
50 /** Attach timeout to HttpServerSocket
52 HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine);
55 void Tick(time_t TIME);
58 /** A socket used for HTTP transport
60 class HttpServerSocket : public InspSocket
63 HttpState InternalState;
64 std::stringstream headers;
66 std::string request_type;
68 std::string http_version;
69 unsigned int postsize;
70 HttpServerTimeout* Timeout;
74 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)
76 InternalState = HTTP_LISTEN;
80 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0)
82 InternalState = HTTP_SERVE_WAIT_REQUEST;
83 Timeout = new HttpServerTimeout(this, Instance->SE);
84 Instance->Timers->AddTimer(Timeout);
87 FileReader* GetIndex()
96 if (Instance->Time() < Timeout->GetTimer())
97 Instance->Timers->DelTimer(Timeout);
102 virtual int OnIncomingConnection(int newsock, char* ip)
104 if (InternalState == HTTP_LISTEN)
106 HttpServerSocket* s = new HttpServerSocket(this->Instance, newsock, ip, index);
107 s = s; /* Stop GCC whining */
112 virtual void OnClose()
116 std::string Response(int response)
123 return "SWITCHING PROTOCOLS";
131 return "NON-AUTHORITATIVE INFORMATION";
135 return "RESET CONTENT";
137 return "PARTIAL CONTENT";
139 return "MULTIPLE CHOICES";
141 return "MOVED PERMENANTLY";
147 return "NOT MODIFIED";
151 return "TEMPORARY REDIRECT";
153 return "BAD REQUEST";
155 return "UNAUTHORIZED";
157 return "PAYMENT REQUIRED";
163 return "METHOD NOT ALLOWED";
165 return "NOT ACCEPTABLE";
167 return "PROXY AUTHENTICATION REQUIRED";
169 return "REQUEST TIMEOUT";
175 return "LENGTH REQUIRED";
177 return "PRECONDITION FAILED";
179 return "REQUEST ENTITY TOO LARGE";
181 return "REQUEST-URI TOO LONG";
183 return "UNSUPPORTED MEDIA TYPE";
185 return "REQUESTED RANGE NOT SATISFIABLE";
187 return "EXPECTATION FAILED";
189 return "INTERNAL SERVER ERROR";
191 return "NOT IMPLEMENTED";
193 return "BAD GATEWAY";
195 return "SERVICE UNAVAILABLE";
197 return "GATEWAY TIMEOUT";
199 return "HTTP VERSION NOT SUPPORTED";
207 void SendHeaders(unsigned long size, int response, const std::string &extraheaders)
209 time_t local = this->Instance->Time();
210 struct tm *timeinfo = gmtime(&local);
211 this->Write("HTTP/1.1 "+ConvToStr(response)+" "+Response(response)+"\r\nDate: ");
212 this->Write(asctime(timeinfo));
213 if (extraheaders.empty())
215 this->Write("Content-Type: text/html\r\n");
219 this->Write(extraheaders);
221 this->Write("Server: InspIRCd/m_httpd.so/1.1\r\nContent-Length: "+ConvToStr(size)+
222 "\r\nConnection: close\r\n\r\n");
225 virtual bool OnDataReady()
227 char* data = this->Read();
229 /* Check that the data read is a valid pointer and it has some content */
234 if (headers.str().find("\r\n\r\n") != std::string::npos)
236 if (request_type == "")
238 headers >> request_type;
240 headers >> http_version;
242 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
243 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
246 if ((InternalState == HTTP_SERVE_WAIT_REQUEST) && (request_type == "POST"))
248 /* Do we need to fetch postdata? */
250 InternalState = HTTP_SERVE_RECV_POSTDATA;
251 std::string header_item;
252 while (headers >> header_item)
254 if (header_item == "Content-Length:")
256 headers >> header_item;
257 postsize = atoi(header_item.c_str());
262 InternalState = HTTP_SERVE_SEND_DATA;
263 SendHeaders(0, 400, "");
264 Timeout = new HttpServerTimeout(this, Instance->SE);
265 Instance->Timers->AddTimer(Timeout);
269 std::string::size_type x = headers.str().find("\r\n\r\n");
270 postdata = headers.str().substr(x+4, headers.str().length());
271 /* Get content length and store */
272 if (postdata.length() >= postsize)
276 else if (InternalState == HTTP_SERVE_RECV_POSTDATA)
278 /* Add postdata, once we have it all, send the event */
279 postdata.append(data);
280 if (postdata.length() >= postsize)
299 /* Headers are complete */
300 InternalState = HTTP_SERVE_SEND_DATA;
302 Instance->Timers->DelTimer(Timeout);
305 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
307 SendHeaders(0, 505, "");
311 if ((request_type == "GET") && (uri == "/"))
313 SendHeaders(index->ContentSize(), 200, "");
314 this->Write(index->Contents());
319 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
320 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
321 e.Send(this->Instance);
324 SendHeaders(0, 404, "");
328 Timeout = new HttpServerTimeout(this, Instance->SE);
329 Instance->Timers->AddTimer(Timeout);
332 void Page(std::stringstream* n, int response, std::string& extraheaders)
334 SendHeaders(n->str().length(), response, extraheaders);
335 this->Write(n->str());
339 HttpServerTimeout::HttpServerTimeout(HttpServerSocket* sock, SocketEngine* engine) : InspTimer(60, time(NULL)), s(sock), SE(engine)
343 void HttpServerTimeout::Tick(time_t TIME)
350 class ModuleHttpServer : public Module
352 std::vector<HttpServerSocket*> httpsocks;
360 std::string indexfile;
362 HttpServerSocket* http;
363 ConfigReader c(ServerInstance);
367 for (int i = 0; i < c.Enumerate("http"); i++)
369 host = c.ReadValue("http", "host", i);
370 bindip = c.ReadValue("http", "ip", i);
371 port = c.ReadInteger("http", "port", i, true);
372 indexfile = c.ReadValue("http", "index", i);
373 index = new FileReader(ServerInstance, indexfile);
374 if (!index->Exists())
375 throw ModuleException("Can't read index file: "+indexfile);
376 http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
377 httpsocks.push_back(http);
381 ModuleHttpServer(InspIRCd* Me) : Module(Me)
386 void OnEvent(Event* event)
390 char* OnRequest(Request* request)
393 HTTPDocument* doc = (HTTPDocument*)request->GetData();
394 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
395 sock->Page(doc->GetDocument(), doc->GetResponseCode(), doc->GetExtraHeaders());
399 void Implements(char* List)
401 List[I_OnEvent] = List[I_OnRequest] = 1;
404 virtual ~ModuleHttpServer()
406 for (size_t i = 0; i < httpsocks.size(); i++)
408 ServerInstance->SE->DelFd(httpsocks[i]);
409 delete httpsocks[i]->GetIndex();
414 virtual Version GetVersion()
416 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
421 class ModuleHttpServerFactory : public ModuleFactory
424 ModuleHttpServerFactory()
428 ~ModuleHttpServerFactory()
432 virtual Module * CreateModule(InspIRCd* Me)
434 HttpModule = new ModuleHttpServer(Me);
440 extern "C" DllExport void * init_module( void )
442 return new ModuleHttpServerFactory;