1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
24 /* $ModDesc: Provides HTTP serving facilities to modules */
28 static ModuleHttp* HttpModule;
31 /** HTTP socket states
36 HTTP_SERVE_WAIT_REQUEST = 1,
37 HTTP_SERVE_RECV_POSTDATA = 2,
38 HTTP_SERVE_SEND_DATA = 3
43 /** This class is used to handle HTTP socket timeouts
45 class HTTPTimeout : public InspTimer
48 /** HttpSocket we are attached to
51 /** Socketengine the file descriptor is in
55 /** Attach timeout to HttpSocket
57 HTTPTimeout(HttpSocket* sock, SocketEngine* engine);
60 void Tick(time_t TIME);
63 /** A socket used for HTTP transport
65 class HttpSocket : public InspSocket
68 HttpState InternalState;
69 std::stringstream headers;
71 std::string request_type;
73 std::string http_version;
74 unsigned int postsize;
79 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)
81 SI->Log(DEBUG,"HttpSocket constructor");
82 InternalState = HTTP_LISTEN;
86 HttpSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0)
88 InternalState = HTTP_SERVE_WAIT_REQUEST;
89 Timeout = new HTTPTimeout(this, Instance->SE);
90 Instance->Timers->AddTimer(Timeout);
93 FileReader* GetIndex()
100 if (Instance->Time() < Timeout->GetTimer())
103 Instance->Timers->DelTimer(Timeout);
108 virtual int OnIncomingConnection(int newsock, char* ip)
110 if (InternalState == HTTP_LISTEN)
112 HttpSocket* s = new HttpSocket(this->Instance, newsock, ip, index);
113 s = s; /* Stop GCC whining */
118 virtual void OnClose()
122 std::string Response(int response)
129 return "SWITCHING PROTOCOLS";
137 return "NON-AUTHORITATIVE INFORMATION";
141 return "RESET CONTENT";
143 return "PARTIAL CONTENT";
145 return "MULTIPLE CHOICES";
147 return "MOVED PERMENANTLY";
153 return "NOT MODIFIED";
157 return "TEMPORARY REDIRECT";
159 return "BAD REQUEST";
161 return "UNAUTHORIZED";
163 return "PAYMENT REQUIRED";
169 return "METHOD NOT ALLOWED";
171 return "NOT ACCEPTABLE";
173 return "PROXY AUTHENTICATION REQUIRED";
175 return "REQUEST TIMEOUT";
181 return "LENGTH REQUIRED";
183 return "PRECONDITION FAILED";
185 return "REQUEST ENTITY TOO LARGE";
187 return "REQUEST-URI TOO LONG";
189 return "UNSUPPORTED MEDIA TYPE";
191 return "REQUESTED RANGE NOT SATISFIABLE";
193 return "EXPECTATION FAILED";
195 return "INTERNAL SERVER ERROR";
197 return "NOT IMPLEMENTED";
199 return "BAD GATEWAY";
201 return "SERVICE UNAVAILABLE";
203 return "GATEWAY TIMEOUT";
205 return "HTTP VERSION NOT SUPPORTED";
213 void SendHeaders(unsigned long size, int response, const std::string &extraheaders)
215 time_t local = this->Instance->Time();
216 struct tm *timeinfo = gmtime(&local);
217 this->Write("HTTP/1.1 "+ConvToStr(response)+" "+Response(response)+"\r\nDate: ");
218 this->Write(asctime(timeinfo));
219 if (extraheaders.empty())
221 this->Write("Content-Type: text/html\r\n");
225 this->Write(extraheaders);
227 this->Write("Server: InspIRCd/m_httpd.so/1.1\r\nContent-Length: "+ConvToStr(size)+
228 "\r\nConnection: close\r\n\r\n");
231 virtual bool OnDataReady()
233 char* data = this->Read();
235 /* Check that the data read is a valid pointer and it has some content */
240 if (headers.str().find("\r\n\r\n") != std::string::npos)
242 if (request_type == "")
244 headers >> request_type;
246 headers >> http_version;
248 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
249 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
252 if ((InternalState == HTTP_SERVE_WAIT_REQUEST) && (request_type == "POST"))
254 /* Do we need to fetch postdata? */
256 InternalState = HTTP_SERVE_RECV_POSTDATA;
257 std::string header_item;
258 while (headers >> header_item)
260 if (header_item == "Content-Length:")
262 headers >> header_item;
263 postsize = atoi(header_item.c_str());
268 InternalState = HTTP_SERVE_SEND_DATA;
269 SendHeaders(0, 400, "");
270 Timeout = new HTTPTimeout(this, Instance->SE);
271 Instance->Timers->AddTimer(Timeout);
275 Instance->Log(DEBUG,"%d bytes to read for POST",postsize);
276 std::string::size_type x = headers.str().find("\r\n\r\n");
277 postdata = headers.str().substr(x+4, headers.str().length());
278 /* Get content length and store */
279 Instance->Log(DEBUG,"Initial postdata: '%s'", postdata.c_str());
280 if (postdata.length() >= postsize)
284 else if (InternalState == HTTP_SERVE_RECV_POSTDATA)
286 /* Add postdata, once we have it all, send the event */
287 postdata.append(data);
288 if (postdata.length() >= postsize)
307 /* Headers are complete */
308 InternalState = HTTP_SERVE_SEND_DATA;
310 Instance->Timers->DelTimer(Timeout);
313 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
315 SendHeaders(0, 505, "");
319 if ((request_type == "GET") && (uri == "/"))
321 SendHeaders(index->ContentSize(), 200, "");
322 this->Write(index->Contents());
327 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
328 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
329 e.Send(this->Instance);
332 SendHeaders(0, 404, "");
333 Instance->Log(DEBUG,"Page not claimed, 404");
337 Timeout = new HTTPTimeout(this, Instance->SE);
338 Instance->Timers->AddTimer(Timeout);
341 void Page(std::stringstream* n, int response, std::string& extraheaders)
343 Instance->Log(DEBUG,"Sending page");
344 SendHeaders(n->str().length(), response, extraheaders);
345 this->Write(n->str());
349 HTTPTimeout::HTTPTimeout(HttpSocket* sock, SocketEngine* engine) : InspTimer(60, time(NULL)), s(sock), SE(engine)
353 void HTTPTimeout::Tick(time_t TIME)
360 class ModuleHttp : public Module
362 std::vector<HttpSocket*> httpsocks;
370 std::string indexfile;
373 ConfigReader c(ServerInstance);
377 for (int i = 0; i < c.Enumerate("http"); i++)
379 host = c.ReadValue("http", "host", i);
380 bindip = c.ReadValue("http", "ip", i);
381 port = c.ReadInteger("http", "port", i, true);
382 indexfile = c.ReadValue("http", "index", i);
383 index = new FileReader(ServerInstance, indexfile);
384 http = new HttpSocket(ServerInstance, bindip, port, true, 0, index);
385 httpsocks.push_back(http);
389 ModuleHttp(InspIRCd* Me) : Module::Module(Me)
394 void OnEvent(Event* event)
398 char* OnRequest(Request* request)
400 ServerInstance->Log(DEBUG,"Got HTTPDocument object");
402 HTTPDocument* doc = (HTTPDocument*)request->GetData();
403 HttpSocket* sock = (HttpSocket*)doc->sock;
404 sock->Page(doc->GetDocument(), doc->GetResponseCode(), doc->GetExtraHeaders());
408 void Implements(char* List)
410 List[I_OnEvent] = List[I_OnRequest] = 1;
413 virtual ~ModuleHttp()
415 for (size_t i = 0; i < httpsocks.size(); i++)
417 ServerInstance->SE->DelFd(httpsocks[i]);
418 delete httpsocks[i]->GetIndex();
423 virtual Version GetVersion()
425 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
430 class ModuleHttpFactory : public ModuleFactory
441 virtual Module * CreateModule(InspIRCd* Me)
443 HttpModule = new ModuleHttp(Me);
449 extern "C" void * init_module( void )
451 return new ModuleHttpFactory;