The InspIRCd Project
Home | Developers | Wiki | Forums | Bug Tracker | SVN | Download
Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members

m_httpd.cpp

Go to the documentation of this file.
00001 /*       +------------------------------------+
00002  *       | Inspire Internet Relay Chat Daemon |
00003  *       +------------------------------------+
00004  *
00005  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
00006  * See: http://www.inspircd.org/wiki/index.php/Credits
00007  *
00008  * This program is free but copyrighted software; see
00009  *            the file COPYING for details.
00010  *
00011  * ---------------------------------------------------
00012  */
00013 
00014 #include "inspircd.h"
00015 #include "httpd.h"
00016 
00017 /* $ModDesc: Provides HTTP serving facilities to modules */
00018 /* $ModDep: httpd.h */
00019 
00020 class ModuleHttpServer;
00021 
00022 static ModuleHttpServer* HttpModule;
00023 static bool claimed;
00024 
00027 enum HttpState
00028 {
00029         HTTP_LISTEN = 0,
00030         HTTP_SERVE_WAIT_REQUEST = 1, /* Waiting for a full request */
00031         HTTP_SERVE_RECV_POSTDATA = 2, /* Waiting to finish recieving POST data */
00032         HTTP_SERVE_SEND_DATA = 3 /* Sending response */
00033 };
00034 
00037 class HttpServerSocket : public BufferedSocket
00038 {
00039         FileReader* index;
00040         HttpState InternalState;
00041 
00042         HTTPHeaders headers;
00043         std::string reqbuffer;
00044         std::string postdata;
00045         unsigned int postsize;
00046         std::string request_type;
00047         std::string uri;
00048         std::string http_version;
00049 
00050  public:
00051 
00052         HttpServerSocket(InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, FileReader* index_page) : BufferedSocket(SI, shost, iport, listening, maxtime), index(index_page), postsize(0)
00053         {
00054                 InternalState = HTTP_LISTEN;
00055         }
00056 
00057         HttpServerSocket(InspIRCd* SI, int newfd, char* ip, FileReader* ind) : BufferedSocket(SI, newfd, ip), index(ind), postsize(0)
00058         {
00059                 InternalState = HTTP_SERVE_WAIT_REQUEST;
00060         }
00061 
00062         FileReader* GetIndex()
00063         {
00064                 return index;
00065         }
00066 
00067         ~HttpServerSocket()
00068         {
00069         }
00070 
00071         virtual int OnIncomingConnection(int newsock, char* ip)
00072         {
00073                 if (InternalState == HTTP_LISTEN)
00074                 {
00075                         new HttpServerSocket(this->Instance, newsock, ip, index);
00076                 }
00077                 return true;
00078         }
00079 
00080         virtual void OnClose()
00081         {
00082         }
00083 
00084         std::string Response(int response)
00085         {
00086                 switch (response)
00087                 {
00088                         case 100:
00089                                 return "CONTINUE";
00090                         case 101:
00091                                 return "SWITCHING PROTOCOLS";
00092                         case 200:
00093                                 return "OK";
00094                         case 201:
00095                                 return "CREATED";
00096                         case 202:
00097                                 return "ACCEPTED";
00098                         case 203:
00099                                 return "NON-AUTHORITATIVE INFORMATION";
00100                         case 204:
00101                                 return "NO CONTENT";
00102                         case 205:
00103                                 return "RESET CONTENT";
00104                         case 206:
00105                                 return "PARTIAL CONTENT";
00106                         case 300:
00107                                 return "MULTIPLE CHOICES";
00108                         case 301:
00109                                 return "MOVED PERMENANTLY";
00110                         case 302:
00111                                 return "FOUND";
00112                         case 303:
00113                                 return "SEE OTHER";
00114                         case 304:
00115                                 return "NOT MODIFIED";
00116                         case 305:
00117                                 return "USE PROXY";
00118                         case 307:
00119                                 return "TEMPORARY REDIRECT";
00120                         case 400:
00121                                 return "BAD REQUEST";
00122                         case 401:
00123                                 return "UNAUTHORIZED";
00124                         case 402:
00125                                 return "PAYMENT REQUIRED";
00126                         case 403:
00127                                 return "FORBIDDEN";
00128                         case 404:
00129                                 return "NOT FOUND";
00130                         case 405:
00131                                 return "METHOD NOT ALLOWED";
00132                         case 406:
00133                                 return "NOT ACCEPTABLE";
00134                         case 407:
00135                                 return "PROXY AUTHENTICATION REQUIRED";
00136                         case 408:
00137                                 return "REQUEST TIMEOUT";
00138                         case 409:
00139                                 return "CONFLICT";
00140                         case 410:
00141                                 return "GONE";
00142                         case 411:
00143                                 return "LENGTH REQUIRED";
00144                         case 412:
00145                                 return "PRECONDITION FAILED";
00146                         case 413:
00147                                 return "REQUEST ENTITY TOO LARGE";
00148                         case 414:
00149                                 return "REQUEST-URI TOO LONG";
00150                         case 415:
00151                                 return "UNSUPPORTED MEDIA TYPE";
00152                         case 416:
00153                                 return "REQUESTED RANGE NOT SATISFIABLE";
00154                         case 417:
00155                                 return "EXPECTATION FAILED";
00156                         case 500:
00157                                 return "INTERNAL SERVER ERROR";
00158                         case 501:
00159                                 return "NOT IMPLEMENTED";
00160                         case 502:
00161                                 return "BAD GATEWAY";
00162                         case 503:
00163                                 return "SERVICE UNAVAILABLE";
00164                         case 504:
00165                                 return "GATEWAY TIMEOUT";
00166                         case 505:
00167                                 return "HTTP VERSION NOT SUPPORTED";
00168                         default:
00169                                 return "WTF";
00170                         break;
00171 
00172                 }
00173         }
00174 
00175         void SendHTTPError(int response)
00176         {
00177                 HTTPHeaders empty;
00178                 std::string data = "<html><head></head><body>Server error "+ConvToStr(response)+": "+Response(response)+"<br>"+
00179                                    "<small>Powered by <a href='http://www.inspircd.org'>InspIRCd</a></small></body></html>";
00180 
00181                 SendHeaders(data.length(), response, empty);
00182                 this->Write(data);
00183                 this->FlushWriteBuffer();
00184         }
00185 
00186         void SendHeaders(unsigned long size, int response, HTTPHeaders &rheaders)
00187         {
00188 
00189                 this->Write(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n");
00190 
00191                 time_t local = this->Instance->Time();
00192                 struct tm *timeinfo = gmtime(&local);
00193                 char *date = asctime(timeinfo);
00194                 date[strlen(date) - 1] = '\0';
00195                 rheaders.CreateHeader("Date", date);
00196 
00197                 rheaders.CreateHeader("Server", "InspIRCd/m_httpd.so/1.2");
00198                 rheaders.SetHeader("Content-Length", ConvToStr(size));
00199 
00200                 if (size)
00201                         rheaders.CreateHeader("Content-Type", "text/html");
00202                 else
00203                         rheaders.RemoveHeader("Content-Type");
00204 
00205                 /* Supporting Connection: keep-alive causes a whole world of hurt syncronizing timeouts,
00206                  * so remove it, its not essential for what we need.
00207                  */
00208                 rheaders.SetHeader("Connection", "Close");
00209 
00210                 this->Write(rheaders.GetFormattedHeaders());
00211                 this->Write("\r\n");
00212         }
00213 
00214         virtual bool OnDataReady()
00215         {
00216                 const char* data = this->Read();
00217 
00218                 /* Check that the data read is a valid pointer and it has some content */
00219                 if (!data || !*data)
00220                         return false;
00221 
00222                 if (InternalState == HTTP_SERVE_RECV_POSTDATA)
00223                 {
00224                         postdata.append(data);
00225                         if (postdata.length() >= postsize)
00226                                 ServeData();
00227                 }
00228                 else
00229                 {
00230                         reqbuffer.append(data);
00231 
00232                         if (reqbuffer.length() >= 8192)
00233                         {
00234                                 Instance->Logs->Log("m_httpd",DEBUG, "m_httpd dropped connection due to an oversized request buffer");
00235                                 reqbuffer.clear();
00236                                 return false;
00237                         }
00238 
00239                         if (InternalState == HTTP_SERVE_WAIT_REQUEST)
00240                                 CheckRequestBuffer();
00241                 }
00242 
00243                 return true;
00244         }
00245 
00246         void CheckRequestBuffer()
00247         {
00248                 std::string::size_type reqend = reqbuffer.find("\r\n\r\n");
00249                 if (reqend == std::string::npos)
00250                         return;
00251 
00252                 // We have the headers; parse them all
00253                 std::string::size_type hbegin = 0, hend;
00254                 while ((hend = reqbuffer.find("\r\n", hbegin)) != std::string::npos)
00255                 {
00256                         if (hbegin == hend)
00257                                 break;
00258 
00259                         if (request_type.empty())
00260                         {
00261                                 std::istringstream cheader(std::string(reqbuffer, hbegin, hend - hbegin));
00262                                 cheader >> request_type;
00263                                 cheader >> uri;
00264                                 cheader >> http_version;
00265 
00266                                 if (request_type.empty() || uri.empty() || http_version.empty())
00267                                 {
00268                                         SendHTTPError(400);
00269                                         SetWrite();
00270                                         return;
00271                                 }
00272 
00273                                 hbegin = hend + 2;
00274                                 continue;
00275                         }
00276 
00277                         std::string cheader = reqbuffer.substr(hbegin, hend - hbegin);
00278 
00279                         std::string::size_type fieldsep = cheader.find(':');
00280                         if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1))
00281                         {
00282                                 SendHTTPError(400);
00283                                 SetWrite();
00284                                 return;
00285                         }
00286 
00287                         headers.SetHeader(cheader.substr(0, fieldsep), cheader.substr(fieldsep + 2));
00288 
00289                         hbegin = hend + 2;
00290                 }
00291 
00292                 reqbuffer.erase(0, reqend + 4);
00293 
00294                 std::transform(request_type.begin(), request_type.end(), request_type.begin(), ::toupper);
00295                 std::transform(http_version.begin(), http_version.end(), http_version.begin(), ::toupper);
00296 
00297                 if ((http_version != "HTTP/1.1") && (http_version != "HTTP/1.0"))
00298                 {
00299                         SendHTTPError(505);
00300                         SetWrite();
00301                         return;
00302                 }
00303 
00304                 if (headers.IsSet("Content-Length") && (postsize = atoi(headers.GetHeader("Content-Length").c_str())) != 0)
00305                 {
00306                         InternalState = HTTP_SERVE_RECV_POSTDATA;
00307 
00308                         if (reqbuffer.length() >= postsize)
00309                         {
00310                                 postdata = reqbuffer.substr(0, postsize);
00311                                 reqbuffer.erase(0, postsize);
00312                         }
00313                         else if (!reqbuffer.empty())
00314                         {
00315                                 postdata = reqbuffer;
00316                                 reqbuffer.clear();
00317                         }
00318 
00319                         if (postdata.length() >= postsize)
00320                                 ServeData();
00321 
00322                         return;
00323                 }
00324 
00325                 ServeData();
00326         }
00327 
00328         void ServeData()
00329         {
00330                 InternalState = HTTP_SERVE_SEND_DATA;
00331 
00332                 if ((request_type == "GET") && (uri == "/"))
00333                 {
00334                         HTTPHeaders empty;
00335                         SendHeaders(index->ContentSize(), 200, empty);
00336                         this->Write(index->Contents());
00337                         this->FlushWriteBuffer();
00338                         SetWrite();
00339                 }
00340                 else
00341                 {
00342                         claimed = false;
00343                         HTTPRequest httpr(request_type,uri,&headers,this,this->GetIP(),postdata);
00344                         Event acl((char*)&httpr, (Module*)HttpModule, "httpd_acl");
00345                         acl.Send(this->Instance);
00346                         if (!claimed)
00347                         {
00348                                 Event e((char*)&httpr, (Module*)HttpModule, "httpd_url");
00349                                 e.Send(this->Instance);
00350                                 if (!claimed)
00351                                 {
00352                                         SendHTTPError(404);
00353                                         SetWrite();
00354                                 }
00355                         }
00356                 }
00357         }
00358 
00359 
00360         bool OnWriteReady()
00361         {
00362                 Instance->Logs->Log("m_httpd",DEBUG,"OnWriteReady()");
00363                 return false;
00364         }
00365 
00366         void Page(std::stringstream* n, int response, HTTPHeaders *hheaders)
00367         {
00368                 SendHeaders(n->str().length(), response, *hheaders);
00369                 this->Write(n->str());
00370                 this->FlushWriteBuffer();
00371                 SetWrite();
00372         }
00373 
00374         void SetWrite()
00375         {
00376                 Instance->Logs->Log("m_httpd",DEBUG,"SetWrite()");
00377                 this->WaitingForWriteEvent = true;
00378                 Instance->SE->WantWrite(this);
00379         }
00380 };
00381 
00382 class ModuleHttpServer : public Module
00383 {
00384         std::vector<HttpServerSocket*> httpsocks;
00385  public:
00386 
00387         void ReadConfig()
00388         {
00389                 int port;
00390                 std::string host;
00391                 std::string bindip;
00392                 std::string indexfile;
00393                 FileReader* index;
00394                 HttpServerSocket* http;
00395                 ConfigReader c(ServerInstance);
00396 
00397                 httpsocks.clear();
00398 
00399                 for (int i = 0; i < c.Enumerate("http"); i++)
00400                 {
00401                         host = c.ReadValue("http", "host", i);
00402                         bindip = c.ReadValue("http", "ip", i);
00403                         port = c.ReadInteger("http", "port", i, true);
00404                         indexfile = c.ReadValue("http", "index", i);
00405                         index = new FileReader(ServerInstance, indexfile);
00406                         if (!index->Exists())
00407                                 throw ModuleException("Can't read index file: "+indexfile);
00408                         http = new HttpServerSocket(ServerInstance, bindip, port, true, 0, index);
00409                         httpsocks.push_back(http);
00410                 }
00411         }
00412 
00413         ModuleHttpServer(InspIRCd* Me) : Module(Me)
00414         {
00415                 ReadConfig();
00416                 HttpModule = this;
00417                 Implementation eventlist[] = { I_OnRequest };
00418                 ServerInstance->Modules->Attach(eventlist, this, 1);
00419         }
00420 
00421         virtual const char* OnRequest(Request* request)
00422         {
00423                 claimed = true;
00424                 HTTPDocument* doc = (HTTPDocument*)request->GetData();
00425                 HttpServerSocket* sock = (HttpServerSocket*)doc->sock;
00426                 sock->Page(doc->GetDocument(), doc->GetResponseCode(), &doc->headers);
00427                 return NULL;
00428         }
00429 
00430 
00431         virtual ~ModuleHttpServer()
00432         {
00433                 for (size_t i = 0; i < httpsocks.size(); i++)
00434                 {
00435                         ServerInstance->SE->DelFd(httpsocks[i]);
00436                         httpsocks[i]->Close();
00437                         delete httpsocks[i]->GetIndex();
00438                 }
00439                 ServerInstance->BufferedSocketCull();
00440         }
00441 
00442         virtual Version GetVersion()
00443         {
00444                 return Version("$Id: m_httpd.cpp 10291 2008-08-25 20:35:51Z w00t $", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
00445         }
00446 };
00447 
00448 MODULE_INIT(ModuleHttpServer)