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 */
23 static ModuleHttp* HttpModule;
26 /** HTTP socket states
31 HTTP_SERVE_WAIT_REQUEST = 1,
32 HTTP_SERVE_RECV_POSTDATA = 2,
33 HTTP_SERVE_SEND_DATA = 3
38 /** This class is used to handle HTTP socket timeouts
40 class HTTPTimeout : public InspTimer
43 /** HttpSocket we are attached to
46 /** Socketengine the file descriptor is in
50 /** Attach timeout to HttpSocket
52 HTTPTimeout(HttpSocket* sock, SocketEngine* engine);
55 void Tick(time_t TIME);
58 /** A socket used for HTTP transport
60 class HttpSocket : public InspSocket
63 HttpState InternalState;
64 std::stringstream headers;
66 std::string request_type;
68 std::string http_version;
69 unsigned int postsize;
74 HttpSocket(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 SI->Log(DEBUG,"HttpSocket constructor");
77 InternalState = HTTP_LISTEN;
81 HttpSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0)
83 InternalState = HTTP_SERVE_WAIT_REQUEST;
84 Timeout = new HTTPTimeout(this, Instance->SE);
85 Instance->Timers->AddTimer(Timeout);
88 FileReader* GetIndex()
95 if (Instance->Time() < Timeout->GetTimer())
98 Instance->Timers->DelTimer(Timeout);
103 virtual int OnIncomingConnection(int newsock, char* ip)
105 if (InternalState == HTTP_LISTEN)
107 HttpSocket* s = new HttpSocket(this->Instance, newsock, ip, index);
108 s = s; /* Stop GCC whining */
113 virtual void OnClose()
117 std::string Response(int response)
124 return "SWITCHING PROTOCOLS";
132 return "NON-AUTHORITATIVE INFORMATION";
136 return "RESET CONTENT";
138 return "PARTIAL CONTENT";
140 return "MULTIPLE CHOICES";
142 return "MOVED PERMENANTLY";
148 return "NOT MODIFIED";
152 return "TEMPORARY REDIRECT";
154 return "BAD REQUEST";
156 return "UNAUTHORIZED";
158 return "PAYMENT REQUIRED";
164 return "METHOD NOT ALLOWED";
166 return "NOT ACCEPTABLE";
168 return "PROXY AUTHENTICATION REQUIRED";
170 return "REQUEST TIMEOUT";
176 return "LENGTH REQUIRED";
178 return "PRECONDITION FAILED";
180 return "REQUEST ENTITY TOO LARGE";
182 return "REQUEST-URI TOO LONG";
184 return "UNSUPPORTED MEDIA TYPE";
186 return "REQUESTED RANGE NOT SATISFIABLE";
188 return "EXPECTATION FAILED";
190 return "INTERNAL SERVER ERROR";
192 return "NOT IMPLEMENTED";
194 return "BAD GATEWAY";
196 return "SERVICE UNAVAILABLE";
198 return "GATEWAY TIMEOUT";
200 return "HTTP VERSION NOT SUPPORTED";
208 void SendHeaders(unsigned long size, int response, const std::string &extraheaders)
210 time_t local = this->Instance->Time();
211 struct tm *timeinfo = gmtime(&local);
212 this->Write("HTTP/1.1 "+ConvToStr(response)+" "+Response(response)+"\r\nDate: ");
213 this->Write(asctime(timeinfo));
214 if (extraheaders.empty())
216 this->Write("Content-Type: text/html\r\n");
220 this->Write(extraheaders);
222 this->Write("Server: InspIRCd/m_httpd.so/1.1\r\nContent-Length: "+ConvToStr(size)+
223 "\r\nConnection: close\r\n\r\n");
226 virtual bool OnDataReady()
228 char* data = this->Read();
230 /* Check that the data read is a valid pointer and it has some content */
235 if (headers.str().find("\r\n\r\n") != std::string::npos)
237 if (request_type == "")
239 headers >> request_type;
241 headers >> http_version;
243 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
244 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
247 if ((InternalState == HTTP_SERVE_WAIT_REQUEST) && (request_type == "POST"))
249 /* Do we need to fetch postdata? */
251 InternalState = HTTP_SERVE_RECV_POSTDATA;
252 std::string header_item;
253 while (headers >> header_item)
255 if (header_item == "Content-Length:")
257 headers >> header_item;
258 postsize = atoi(header_item.c_str());
263 InternalState = HTTP_SERVE_SEND_DATA;
264 SendHeaders(0, 400, "");
265 Timeout = new HTTPTimeout(this, Instance->SE);
266 Instance->Timers->AddTimer(Timeout);
270 Instance->Log(DEBUG,"%d bytes to read for POST",postsize);
271 std::string::size_type x = headers.str().find("\r\n\r\n");
272 postdata = headers.str().substr(x+4, headers.str().length());
273 /* Get content length and store */
274 Instance->Log(DEBUG,"Initial postdata: '%s'", postdata.c_str());
275 if (postdata.length() >= postsize)
279 else if (InternalState == HTTP_SERVE_RECV_POSTDATA)
281 /* Add postdata, once we have it all, send the event */
282 postdata.append(data);
283 if (postdata.length() >= postsize)
302 /* Headers are complete */
303 InternalState = HTTP_SERVE_SEND_DATA;
305 Instance->Timers->DelTimer(Timeout);
308 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
310 SendHeaders(0, 505, "");
314 if ((request_type == "GET") && (uri == "/"))
316 SendHeaders(index->ContentSize(), 200, "");
317 this->Write(index->Contents());
322 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
323 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
324 e.Send(this->Instance);
327 SendHeaders(0, 404, "");
328 Instance->Log(DEBUG,"Page not claimed, 404");
332 Timeout = new HTTPTimeout(this, Instance->SE);
333 Instance->Timers->AddTimer(Timeout);
336 void Page(std::stringstream* n, int response, std::string& extraheaders)
338 Instance->Log(DEBUG,"Sending page");
339 SendHeaders(n->str().length(), response, extraheaders);
340 this->Write(n->str());
344 HTTPTimeout::HTTPTimeout(HttpSocket* sock, SocketEngine* engine) : InspTimer(60, time(NULL)), s(sock), SE(engine)
348 void HTTPTimeout::Tick(time_t TIME)
355 class ModuleHttp : public Module
357 std::vector<HttpSocket*> httpsocks;
365 std::string indexfile;
368 ConfigReader c(ServerInstance);
372 for (int i = 0; i < c.Enumerate("http"); i++)
374 host = c.ReadValue("http", "host", i);
375 bindip = c.ReadValue("http", "ip", i);
376 port = c.ReadInteger("http", "port", i, true);
377 indexfile = c.ReadValue("http", "index", i);
378 index = new FileReader(ServerInstance, indexfile);
379 http = new HttpSocket(ServerInstance, bindip, port, true, 0, index);
380 httpsocks.push_back(http);
384 ModuleHttp(InspIRCd* Me) : Module::Module(Me)
389 void OnEvent(Event* event)
393 char* OnRequest(Request* request)
395 ServerInstance->Log(DEBUG,"Got HTTPDocument object");
397 HTTPDocument* doc = (HTTPDocument*)request->GetData();
398 HttpSocket* sock = (HttpSocket*)doc->sock;
399 sock->Page(doc->GetDocument(), doc->GetResponseCode(), doc->GetExtraHeaders());
403 void Implements(char* List)
405 List[I_OnEvent] = List[I_OnRequest] = 1;
408 virtual ~ModuleHttp()
410 for (size_t i = 0; i < httpsocks.size(); i++)
412 ServerInstance->SE->DelFd(httpsocks[i]);
413 delete httpsocks[i]->GetIndex();
418 virtual Version GetVersion()
420 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
425 class ModuleHttpFactory : public ModuleFactory
436 virtual Module * CreateModule(InspIRCd* Me)
438 HttpModule = new ModuleHttp(Me);
444 extern "C" void * init_module( void )
446 return new ModuleHttpFactory;