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;
80 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)
82 SI->Log(DEBUG,"HttpSocket constructor");
83 InternalState = HTTP_LISTEN;
87 HttpSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : InspSocket(SI, newfd, ip), index(ind), postsize(0)
89 InternalState = HTTP_SERVE_WAIT_REQUEST;
90 Timeout = new HTTPTimeout(this, Instance->SE);
91 Instance->Timers->AddTimer(Timeout);
94 FileReader* GetIndex()
101 if (Instance->Time() < Timeout->GetTimer())
104 Instance->Timers->DelTimer(Timeout);
109 virtual int OnIncomingConnection(int newsock, char* ip)
111 if (InternalState == HTTP_LISTEN)
113 HttpSocket* s = new HttpSocket(this->Instance, newsock, ip, index);
114 s = s; /* Stop GCC whining */
119 virtual void OnClose()
123 std::string Response(int response)
130 return "SWITCHING PROTOCOLS";
138 return "NON-AUTHORITATIVE INFORMATION";
142 return "RESET CONTENT";
144 return "PARTIAL CONTENT";
146 return "MULTIPLE CHOICES";
148 return "MOVED PERMENANTLY";
154 return "NOT MODIFIED";
158 return "TEMPORARY REDIRECT";
160 return "BAD REQUEST";
162 return "UNAUTHORIZED";
164 return "PAYMENT REQUIRED";
170 return "METHOD NOT ALLOWED";
172 return "NOT ACCEPTABLE";
174 return "PROXY AUTHENTICATION REQUIRED";
176 return "REQUEST TIMEOUT";
182 return "LENGTH REQUIRED";
184 return "PRECONDITION FAILED";
186 return "REQUEST ENTITY TOO LARGE";
188 return "REQUEST-URI TOO LONG";
190 return "UNSUPPORTED MEDIA TYPE";
192 return "REQUESTED RANGE NOT SATISFIABLE";
194 return "EXPECTATION FAILED";
196 return "INTERNAL SERVER ERROR";
198 return "NOT IMPLEMENTED";
200 return "BAD GATEWAY";
202 return "SERVICE UNAVAILABLE";
204 return "GATEWAY TIMEOUT";
206 return "HTTP VERSION NOT SUPPORTED";
214 void SendHeaders(unsigned long size, int response, const std::string &extraheaders)
216 time_t local = this->Instance->Time();
217 struct tm *timeinfo = gmtime(&local);
218 this->Write("HTTP/1.1 "+ConvToStr(response)+" "+Response(response)+"\r\nDate: ");
219 this->Write(asctime(timeinfo));
220 if (extraheaders.empty())
222 this->Write("Content-Type: text/html\r\n");
226 this->Write(extraheaders);
228 this->Write("Server: InspIRCd/m_httpd.so/1.1\r\nContent-Length: "+ConvToStr(size)+
229 "\r\nConnection: close\r\n\r\n");
232 virtual bool OnDataReady()
234 char* data = this->Read();
236 /* Check that the data read is a valid pointer and it has some content */
241 if (headers.str().find("\r\n\r\n") != std::string::npos)
243 if (request_type == "")
245 headers >> request_type;
247 headers >> http_version;
249 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
250 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
253 if ((InternalState == HTTP_SERVE_WAIT_REQUEST) && (request_type == "POST"))
255 /* Do we need to fetch postdata? */
258 InternalState = HTTP_SERVE_RECV_POSTDATA;
259 std::string header_item;
260 while (headers >> header_item)
262 if (header_item == "Content-Length:")
264 headers >> header_item;
265 postsize = atoi(header_item.c_str());
270 InternalState = HTTP_SERVE_SEND_DATA;
271 SendHeaders(0, 400, "");
272 Timeout = new HTTPTimeout(this, Instance->SE);
273 Instance->Timers->AddTimer(Timeout);
277 Instance->Log(DEBUG,"%d bytes to read for POST",postsize);
278 std::string::size_type x = headers.str().find("\r\n\r\n");
279 postdata = headers.str().substr(x+4, headers.str().length());
280 /* Get content length and store */
281 Instance->Log(DEBUG,"Initial postdata: '%s'", postdata.c_str());
282 if (postdata.length() >= postsize)
286 else if (InternalState == HTTP_SERVE_RECV_POSTDATA)
288 /* Add postdata, once we have it all, send the event */
289 amount += strlen(data);
290 postdata.append(data);
291 if (amount >= postsize)
310 /* Headers are complete */
311 InternalState = HTTP_SERVE_SEND_DATA;
313 Instance->Timers->DelTimer(Timeout);
316 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
318 SendHeaders(0, 505, "");
322 if ((request_type == "GET") && (uri == "/"))
324 SendHeaders(index->ContentSize(), 200, "");
325 this->Write(index->Contents());
330 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
331 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
332 e.Send(this->Instance);
335 SendHeaders(0, 404, "");
336 Instance->Log(DEBUG,"Page not claimed, 404");
340 Timeout = new HTTPTimeout(this, Instance->SE);
341 Instance->Timers->AddTimer(Timeout);
344 void Page(std::stringstream* n, int response, std::string& extraheaders)
346 Instance->Log(DEBUG,"Sending page");
347 SendHeaders(n->str().length(), response, extraheaders);
348 this->Write(n->str());
352 HTTPTimeout::HTTPTimeout(HttpSocket* sock, SocketEngine* engine) : InspTimer(60, time(NULL)), s(sock), SE(engine)
356 void HTTPTimeout::Tick(time_t TIME)
363 class ModuleHttp : public Module
365 std::vector<HttpSocket*> httpsocks;
373 std::string indexfile;
376 ConfigReader c(ServerInstance);
380 for (int i = 0; i < c.Enumerate("http"); i++)
382 host = c.ReadValue("http", "host", i);
383 bindip = c.ReadValue("http", "ip", i);
384 port = c.ReadInteger("http", "port", i, true);
385 indexfile = c.ReadValue("http", "index", i);
386 index = new FileReader(ServerInstance, indexfile);
387 http = new HttpSocket(ServerInstance, bindip, port, true, 0, index);
388 httpsocks.push_back(http);
392 ModuleHttp(InspIRCd* Me) : Module::Module(Me)
397 void OnEvent(Event* event)
401 char* OnRequest(Request* request)
403 ServerInstance->Log(DEBUG,"Got HTTPDocument object");
405 HTTPDocument* doc = (HTTPDocument*)request->GetData();
406 HttpSocket* sock = (HttpSocket*)doc->sock;
407 sock->Page(doc->GetDocument(), doc->GetResponseCode(), doc->GetExtraHeaders());
411 void Implements(char* List)
413 List[I_OnEvent] = List[I_OnRequest] = 1;
416 virtual ~ModuleHttp()
418 for (size_t i = 0; i < httpsocks.size(); i++)
420 ServerInstance->SE->DelFd(httpsocks[i]);
421 delete httpsocks[i]->GetIndex();
426 virtual Version GetVersion()
428 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
433 class ModuleHttpFactory : public ModuleFactory
444 virtual Module * CreateModule(InspIRCd* Me)
446 HttpModule = new ModuleHttp(Me);
452 extern "C" void * init_module( void )
454 return new ModuleHttpFactory;