1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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
29 HTTP_SERVE_WAIT_REQUEST = 0, /* Waiting for a full request */
30 HTTP_SERVE_RECV_POSTDATA = 1, /* Waiting to finish recieving POST data */
31 HTTP_SERVE_SEND_DATA = 2 /* Sending response */
34 /** A socket used for HTTP transport
36 class HttpServerSocket : public BufferedSocket
39 HttpState InternalState;
42 std::string reqbuffer;
44 unsigned int postsize;
45 std::string request_type;
47 std::string http_version;
51 HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : BufferedSocket(SI, newfd, ip), index(ind), postsize(0)
53 InternalState = HTTP_SERVE_WAIT_REQUEST;
56 FileReader* GetIndex()
65 virtual void OnClose()
69 std::string Response(int response)
76 return "SWITCHING PROTOCOLS";
84 return "NON-AUTHORITATIVE INFORMATION";
88 return "RESET CONTENT";
90 return "PARTIAL CONTENT";
92 return "MULTIPLE CHOICES";
94 return "MOVED PERMENANTLY";
100 return "NOT MODIFIED";
104 return "TEMPORARY REDIRECT";
106 return "BAD REQUEST";
108 return "UNAUTHORIZED";
110 return "PAYMENT REQUIRED";
116 return "METHOD NOT ALLOWED";
118 return "NOT ACCEPTABLE";
120 return "PROXY AUTHENTICATION REQUIRED";
122 return "REQUEST TIMEOUT";
128 return "LENGTH REQUIRED";
130 return "PRECONDITION FAILED";
132 return "REQUEST ENTITY TOO LARGE";
134 return "REQUEST-URI TOO LONG";
136 return "UNSUPPORTED MEDIA TYPE";
138 return "REQUESTED RANGE NOT SATISFIABLE";
140 return "EXPECTATION FAILED";
142 return "INTERNAL SERVER ERROR";
144 return "NOT IMPLEMENTED";
146 return "BAD GATEWAY";
148 return "SERVICE UNAVAILABLE";
150 return "GATEWAY TIMEOUT";
152 return "HTTP VERSION NOT SUPPORTED";
160 void SendHTTPError(int response)
163 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
164 "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
166 SendHeaders(data.length(), response, empty);
170 void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
173 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
175 time_t local = this->ServerInstance->Time();
176 struct tm *timeinfo = gmtime(&local);
177 char *date = asctime(timeinfo);
178 date[strlen(date) - 1] = '\0';
179 rheaders.CreateHeader("Date", date);
181 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.2");
182 rheaders.SetHeader("Content-Length", ConvToStr(size));
185 rheaders.CreateHeader("Content-Type", "text/html");
187 rheaders.RemoveHeader("Content-Type");
189 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
190 * so remove it, its not essential for what we need.
192 rheaders.SetHeader("Connection", "Close");
194 this->Write(rheaders.GetFormattedHeaders());
198 virtual bool OnDataReady()
200 const char* data = this->Read();
202 /* Check that the data read is a valid pointer and it has some content */
206 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
208 postdata.append(data);
209 if (postdata.length() >= postsize)
214 reqbuffer.append(data);
216 if (reqbuffer.length() >= 8192)
218 ServerInstance->Logs->Log("m_httpd",DEBUG, "m_httpd dropped connection due to an oversized request buffer");
223 if (InternalState == HTTP_SERVE_WAIT_REQUEST)
224 CheckRequestBuffer();
230 void CheckRequestBuffer()
232 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
233 if (reqend == std::string::npos)
236 // We have the headers; parse them all
237 std::string::size_type hbegin = 0, hend;
238 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
243 if (request_type.empty())
245 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
246 cheader >> request_type;
248 cheader >> http_version;
250 if (request_type.empty() || uri.empty() || http_version.empty())
260 std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
262 std::string::size_type fieldsep = cheader.find(':');
263 if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
269 headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
274 reqbuffer.erase(0, reqend + 4);
276 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
277 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
279 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
285 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
287 InternalState = HTTP_SERVE_RECV_POSTDATA;
289 if (reqbuffer.length() >= postsize)
291 postdata = reqbuffer.substr(0, postsize);
292 reqbuffer.erase(0, postsize);
294 else if (!reqbuffer.empty())
296 postdata = reqbuffer;
300 if (postdata.length() >= postsize)
311 InternalState = HTTP_SERVE_SEND_DATA;
313 if ((request_type == "GET") && (uri == "/"))
316 SendHeaders(index->ContentSize(), 200, empty);
317 this->Write(index->Contents());
322 HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
323 Event acl((char*)&httpr, (Module*)HttpModule, "httpd_acl");
324 acl.Send(this->ServerInstance);
327 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
328 e.Send(this->ServerInstance);
337 void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
339 SendHeaders(n->str().length(), response, *hheaders);
340 this->Write(n->str());
344 /** Spawn HTTP sockets from a listener
346 class HttpListener : public ListenSocketBase
351 HttpListener(InspIRCd* Instance, FileReader *idx, int port, const std::string &addr) : ListenSocketBase(Instance, port, addr)
356 virtual void OnAcceptReady(const std::string &ipconnectedto, int nfd, const std::string &incomingip)
358 new HttpServerSocket(ServerInstance, nfd, (char *)incomingip.c_str(), index); // ugly cast courtesy of bufferedsocket
362 class ModuleHttpServer : public Module
364 std::vector<HttpServerSocket *> httpsocks;
365 std::vector<HttpListener *> httplisteners;
373 std::string indexfile;
376 ConfigReader c(ServerInstance);
378 httpsocks.clear(); // XXX this will BREAK if this module is made rehashable
379 httplisteners.clear();
381 for (int i = 0; i < c.Enumerate("http"); i++)
383 host = c.ReadValue("http", "host", i);
384 bindip = c.ReadValue("http", "ip", i);
385 port = c.ReadInteger("http", "port", i, true);
386 indexfile = c.ReadValue("http", "index", i);
387 index = new FileReader(ServerInstance, indexfile);
388 if (!index->Exists())
389 throw ModuleException("Can't read index file: "+indexfile);
390 http = new HttpListener(ServerInstance, index, port, (char *)bindip.c_str()); // XXX this cast SUCKS.
391 httplisteners.push_back(http);
395 ModuleHttpServer(InspIRCd* Me) : Module(Me)
399 Implementation eventlist[] = { I_OnRequest };
400 ServerInstance->Modules->Attach(eventlist, this, 1);
403 virtual const char* OnRequest(Request* request)
406 HTTPDocument* doc = (HTTPDocument*)request->GetData();
407 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
408 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
413 virtual ~ModuleHttpServer()
415 for (size_t i = 0; i < httplisteners.size(); i++)
417 delete httplisteners[i];
420 for (size_t i = 0; i < httpsocks.size(); i++)
422 ServerInstance->SE->DelFd(httpsocks[i]);
423 httpsocks[i]->Close();
424 delete httpsocks[i]->GetIndex();
426 ServerInstance->BufferedSocketCull();
429 virtual Version GetVersion()
431 return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
435 MODULE_INIT(ModuleHttpServer)