Esempio n. 1
0
int main ()
{
   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET and POST Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("first_name");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "First name: " << **fi << endl;  
   }else{
      cout << "No text entered for first name" << endl;  
   }
   cout << "<br/>\n";
   fi = formData.getElement("last_name");  
   if( !fi->isEmpty() &&fi != (*formData).end()) {  
      cout << "Last name: " << **fi << endl;  
   }else{
      cout << "No text entered for last name" << endl;  
   }
   cout << "<br/>\n";

   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}
Esempio n. 2
0
int main (int , char *[]){

  Cgicc cgi;
  form_iterator dataIter = cgi.getElement("dataid");
  form_iterator mimetypeIter = cgi.getElement("mime");
  string errMessage("");
  
  if (dataIter == cgi.getElements().end() || dataIter->getValue() == "" ){

    errMessage += "Sorry, You did not provide a dataId.</br>";
  }
  if (errMessage == ""){

    try {

     cout << "Content-type: " << mimetypeIter->getValue() << "\n\n";     
      ShowEvidence showEv;
      showEv.showData(dataIter->getValue(), cout);
      return 0;
    } catch (ocfa::misc::OcfaException &e){
      e.logWhat();
      cerr << e.what(); 
    }
  } else {

    cout << "Content-type: text/html" << endl;
    cout << "<html><body><h1>" << errMessage << "</h1></body></html>";
    cout << endl;
  }
}
int main ()
{
   Cgicc formData;

   double tf = 2.5;
   double disc = 0.00001;
   double step = 0.01666;

   
   std::vector<double> ic = {9.8, 2.1, 1.2, 1.5, 0.9, 0.5, -0.5, 1.3, 1.2};
   std::vector<string> ic_str  = {"grav", "len1", "mass1", "len2", "mass2", "theta1", "theta2", "dtheta1", "dtheta2"};

   form_iterator fi; 
   for(int i = 0; i < ic.size(); i++) {
      fi = formData.getElement(ic_str[i]);  
      if( !fi->isEmpty() && fi != (*formData).end()) {  
         ic[i] = atof((**fi).c_str());  
      }
   }
   fi = formData.getElement("disc");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      disc = atof((**fi).c_str());  
   }

   fi = formData.getElement("step");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      step = atof((**fi).c_str());  
   }

   fi = formData.getElement("tf");  
   if( !fi->isEmpty() &&fi != (*formData).end()) {  
      tf = atof((**fi).c_str());  
   }
   
   cout << "Content-type:text/plain\r\n\r\n";

    DoublePendEquations dp(ic[0], ic[1], ic[2], ic[3], ic[4]);
    // FunctionWrapperRK4 * base_ptr = &dp;
    std::vector<double> in = {ic[5], -ic[6], ic[7], ic[8]};

    RK4 rk4(&dp);

    rk4.solve(disc, tf, in);

    auto ret = rk4.query(0, tf, step);

    // int it = 1; 
    // printf("theta1 Theta2 dTheta1 dTheta2\n");
    for(int i = 0; i < ret[0].size(); i++) {
        for(int j = 0; j < ret.size(); j++) {
          printf("%5.3f ", ret[j][i]);
        }
        printf("\n");
    }
   
   return 0;
}
Esempio n. 4
0
int
main(int /*argc*/, 
     char ** /*argv*/)
{
  try {
    Cgicc cgi;

    // Get the current time in the format Sun, 06 Nov 1994 08:49:37 GMT
    char current_date [30];
    time_t now = time(&now);
    strftime(current_date, 30, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now));

    // Build our own server string
    string server_string("GNU cgicc/");
    server_string += cgi.getVersion();

    // Tell the server not to parse our headers
    cout << HTTPResponseHeader("HTTP/1.1", 200, "OK")
      .addHeader("Date", current_date)
      .addHeader("Server", server_string)
      .addHeader("Content-Language", "en")
      .addHeader("Content-Type", "text/html");

    cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
    
    cout << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"DTD/xhtml1-strict.dtd\">" << endl;
    cout << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" << endl;

    cout << "<head>" << endl;

    // Output the style sheet portion of the header
    cout << "<style><!-- " << endl;
    cout << "   body { color: black; background-color: white; }" << endl;
    cout << "   span.red { color: red; }" << endl;
    cout << " --></style>" << endl;

    cout << "<title>GNU cgicc v" << cgi.getVersion() << "</title>" << endl;
    cout << "</head>" << endl;

    cout << "<body>" << endl;
    cout << "<h1>Hello, world from GNU cgi<span class=\"red\">cc</span> v";
    cout << cgi.getVersion() << "</h1>" << endl;
    cout << "</body></html>" << endl;
  }
  
  catch(const exception& e) {
    // handle error condition
  }
  
  return 0;
}
Esempio n. 5
0
int main(int argc, char **argv)
{

  
  Cgicc cgi;
    
  cout<<"Content-type: text/html"<<endl<<endl;
  cout<<"<html><head></head><body>"<<endl;
  cout<<"hello world"<<endl;
  DBconnector db;
  db.testConnection();

  const CgiEnvironment& env = cgi.getEnvironment();

  string pathInfo = env.getPathInfo();
  string var("");
  string secondary("");
  //parse_path_info(pathInfo);
  Punct_stream ps(pathInfo);
  ps.whitespace("/");
   vector<string> vars;
  while (ps>>var){
    vars.push_back(var);
  }

  for (int i = 0; i < vars.size(); i++)
    cout << vars[i];
  
  ServiceManager sm;
  sm.ServiceParser(vars);
  

  if (env.getRequestMethod() == POST_METHOD){
    cout << "POST";
    //get POST content
  }

  if (env.getRequestMethod() == GET_METHOD){
    cout << "GET";
    //get GET content
  }
  
  string post = env.getPathInfo();
  cout<<"<br>"<<endl;
  cout<<post << endl;
  cout<<"</body></html>"<<endl;
  return 0;
}
Esempio n. 6
0
int main (int , char *[]){

  Cgicc cgi;
  form_iterator metaIter = cgi.getElement("metaid");
  form_iterator xslIter = cgi.getElement("xsl");
  string metaId;
  string errMessage("");
  string xslSheet;
  if (metaIter == cgi.getElements().end() || metaIter->getValue() == "" ){

    errMessage += "Sorry, You did not provide a meta id.</br>";
  }
  if (xslIter == cgi.getElements().end() || xslIter->getValue() == ""){

    xslSheet = "/ocfa.xsl";
  }
  else {
    
    xslSheet = xslIter->getValue();
  }
  if (errMessage == ""){
    ShowEvidence *showEv;    
    cout << "Content-type: text/xml\n\n";
    cout << "<?xml version=\"1.0\"?>\n";
    cout << "<?xml-stylesheet type=\"text/xsl\" href=\"" << xslSheet <<  "\" ?>\n";
    try {

      showEv = new ShowEvidence();
      showEv->showXml(metaIter->getValue(), cout); 
      delete showEv;
    } catch (ocfa::misc::OcfaException &e){

      e.logWhat();
    }
  }
  else {
    
    cout << cgicc::HTTPHTMLHeader() << endl;
    cout << html() << body();
    cout << h1("Error");
    cout << errMessage << endl;
    cout << body() << html() << endl;
  }
}
Esempio n. 7
0
int main()
{
    Cgicc formData;

    cout << "Content-type:text/html\r\n\r\n";
    cout << "<html>\n";
    cout << "<head>\n";
    cout << "<title>Drop Down Box Data to CGI</title>\n";
    cout << "</head>\n";
    cout << "<body>\n";

    form_iterator fi = formData.getElement("dropdown");
    if( !fi->isEmpty() && fi != (*formData).end()) {
        cout << "Value Selected: " << **fi << endl;
    }

    cout << "<br/>\n";
    cout << "</body>\n";
    cout << "</html>\n";

    return 0;
}
Esempio n. 8
0
int main (int , char *[]){

  Cgicc cgi;
  form_iterator metaIter = cgi.getElement("metaid");
  form_iterator mimetypeIter = cgi.getElement("mime");
  string errMessage("");
  if (metaIter == cgi.getElements().end() || metaIter->getValue() == "" ){

    errMessage += "Sorry, you did not provide a metaId.</br>";
  }
  if (errMessage == ""){

    try {

     cout << "Content-type: " << mimetypeIter->getValue() << "\n\n";     
      ShowEvidence showEv;
      showEv.showData(metaIter->getValue(), cout);
      return 0;
    } catch (ocfa::misc::OcfaException &e){
      e.logWhat();
      cerr << e.what(); 
    }
  }
}
Esempio n. 9
0
int main (int , char *[]){

  Cgicc cgi;

  form_iterator caseIter = cgi.getElement("case");
  form_iterator sourceIter = cgi.getElement("src");
  form_iterator itemIter = cgi.getElement("item");
  form_iterator evidenceIter = cgi.getElement("id");
  form_iterator childIter = cgi.getElement("child");
  string evidenceID;
  string errMessage("");
  if (caseIter == cgi.getElements().end() || caseIter->getValue() == ""){
    
    errMessage += "Sorry, You did not provide an investigation.<br>";
  }
  if (sourceIter == cgi.getElements().end() || sourceIter->getValue() == ""){
    
    errMessage += "Sorry, You did not provide an evidence source.<br>";
  }
  if (itemIter == cgi.getElements().end() || itemIter->getValue() == "" ){

    errMessage += "Sorry, You did not provide an itam.<br>";
  }


  if (evidenceIter == cgi.getElements().end() || evidenceIter->getValue()==""){
    // if not child is given simply assume evidenceid is at the top.
    if (childIter == cgi.getElements().end() || childIter->getValue()== ""){
      
      // cout << "<!--  no child was given -->" << endl;
      evidenceID = "0";
    }
    else {

      // cout << "<!-- finding lastdotloc -->" << endl;
      // remove informatino after last dot of child to get to the father.
      string::size_type theLastDotLoc;
      evidenceID = childIter->getValue();
      theLastDotLoc = evidenceID.find_last_of('.');
      if (theLastDotLoc == string::npos){

	errMessage+="do not undestand  " + evidenceID + "<br/>";
      }
      else {
	
	evidenceID = evidenceID.substr(0, theLastDotLoc);
      }
      //cout << "evidenceID = " << evidenceID << endl; 
    }
   
    
  } else {
    
    evidenceID = evidenceIter->getValue();
  }
  if (errMessage == ""){
    ShowEvidence *showEv;    
    cout << "Content-type: text/xml\n\n";
    cout <<"<?xml version=\"1.0\"?>\n";
    cout << "<?xml-stylesheet type=\"text/xsl\" href=\"/ocfa.xsl\" ?>\n";
    try {
      showEv = new ShowEvidence();
      showEv->showXml(caseIter->getValue(), sourceIter->getValue(), 
		      itemIter->getValue(), evidenceID, cout); 
      delete showEv;
    } catch (ocfa::misc::OcfaException &e){

      e.logWhat();
    }
  }
  else {
    
    cout << cgicc::HTTPHTMLHeader() << endl;
    cout << html() << body();
    cout << h1("Error");
    cout << errMessage << endl;
    cout << body() << html() << endl;
  }
}
Esempio n. 10
0
int
main(int /*argc*/, 
     char ** /*argv*/)
{
  try {
    Cgicc cgi;
    const CgiEnvironment& env = cgi.getEnvironment();
    string remoteuser = env.getRemoteUser();
    string serversw = env.getServerSoftware();
    string clientsw = env.getUserAgent();
    string authtype = env.getAuthType();

    if(remoteuser.empty()) {
      if (serversw.find("Microsoft") != string::npos 
	  && clientsw.find("Win") != string::npos) {
	/*
	  Server and client are running on Microsoft OS, so we
	  probably can request NTLM authentication; the last test was
	  needed to prevent IE on Mac's from using NTLM, because it
	  seems to be broken on Macs 
	*/

     cout << HTTPResponseHeader("HTTP/1.1", 401, "Unauthorized")
	  .addHeader("WWW-Authenticate", "NTLM")
	  .addHeader("WWW-Authenticate",  "Basic realm=\"cgicc\"");
  
        /*
	  There is a bug in all version of Microsoft Internet Explorer
	  at least up to 5.5 by which the NTLM authentication scheme
	  MUST be declared first or it won't be selected. This goes
	  against RFC 2616, which recites "A user agent MUST choose to
	  use the strongest auth- scheme it understands" and NTLM, while
	  broken in many ways, is still worlds stronger than Basic.
        */
      }
      else {
	// we're not chatting fully MS: only support basic
        cout << HTTPResponseHeader("HTTP/1.1", 401, "Unauthorized")
	  .addHeader("WWW-Authenticate", "Basic realm=\"cgicc\"");
      }
      // do not add html data: browsers should not display this anyway
      //  they should request user/password from the user and re-emit
      //  the same request, only with the authentification info added
      //  to the request 
      cout << HTMLDoctype(HTMLDoctype::eStrict) << endl;
      cout << html().set("lang", "EN").set("dir", "LTR") << endl;
    
      cout << head() << endl;
      cout << title("401 Authorization Required")  << endl;
      cout << head() << endl;
    
      cout << body() << endl;
      cout << h1("401 Authorization Required") << endl;
      cout << p() << "This server could not verify that you are "
	   << "authorized to access the document requested. Either you "
	   << "supplied the wrong credentials (e.g., bad password), or "
	   << "your browser doesn't understand how to supply the "
	   << "credentials required." << p();

      cout << hr() << endl;
      cout << address() << "GNU cgicc \"server\" version " << cgi.getVersion()
	   << address() << endl;

      return 0;
    }
  
    // Output the HTTP headers 200 OK header for an HTML document, and
    // the HTML 4.0 DTD info
    cout << HTTPResponseHeader(env.getServerProtocol(), 200 ,"OK")
      .addHeader("Content-Type", "text/html");
    cout << HTMLDoctype(HTMLDoctype::eStrict) << endl;
    cout << html().set("lang", "EN").set("dir", "LTR") << endl;

    // Set up the page's header and title.
    cout << head() << endl;
    cout << title() << "GNU cgicc v" << cgi.getVersion() << title() << endl;
    cout << head() << endl;
    
    // Start the HTML body
    cout << body() << endl;

    // Print out a message
    cout << "Hello " << env.getRemoteUser() 
	 << " your login was accepted" << br() << endl;
    cout << "You were authenticated using authentication scheme : " 
	 << env.getAuthType() << br() << endl;
    cout << "Your server software is :" << serversw << br() << endl;
    cout << "Your browser software is :" << clientsw << br() << endl;
    // Close the document
    cout << body() << html();


  }
  
  catch(const exception& e) {
    // handle error condition
  }
  
  return 0;
}
Esempio n. 11
0
int main()
{
    Cgicc cgi;

    int caseId;
    QString username;
    QString password;

    form_iterator userIter = cgi.getElement("user");
    if (userIter != cgi.getElements().end())
    {
       username = QString((**userIter).c_str());
    }

    form_iterator passIter = cgi.getElement("pass");
    if (passIter != cgi.getElements().end())
    {
       password = QString((**passIter).c_str());
    }

    form_iterator caseIter = cgi.getElement("caseID");
    if (caseIter != cgi.getElements().end())
    {
       caseId = atoi((**caseIter).c_str());
    }

    cout << HTTPHTMLHeader();

    ConnectionFileReader connectionReader(QString("../Resources/connection.txt"));
    DatabaseConnection* conn = connectionReader.getDatabaseConnection();


    CaseManager manager(conn, caseId);
    if (!manager.authenticateCase(username, password))
    {
        cout << "Could not authenticate user" << endl;
        return 1;
    }

	char* programPath = "/home/zane/Documents/COS301/MainProject/build-QuantFacialRecognition-Desktop_Qt_5_3_0_GCC_64bit-Debug/app/app";

    pid_t pid = fork();
    stringstream ss;
    ss << caseId;
    string strCaseId;
    ss >> strCaseId;

    switch (pid)
    {
        case -1:
            cout << "Could not start new process" << "\n";
            exit(1);
        case 0:
            execl(programPath, strCaseId.c_str(), NULL);
            std::cerr << "Uh-Oh! execl() failed!";
            cout << "Could not start new process" << "\n";
            exit(1);
        default:
            std::cout << "1";

        return 0;
    }
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    try {
    	Cgicc formData;
    	const CgiEnvironment& cgienv = formData.getEnvironment();

    	string scommand, sparameter;
    	scommand = "";
    	sparameter = "";

    	string postdata =  cgienv.getPostData();
    	string encodedpostdata = cgicc::form_urldecode(postdata);

    	syslog( LOG_ERR, "EncodedPostData: %s",encodedpostdata.c_str());

       /* Commando find*/
       form_iterator command = formData.getElement("COMMAND");
       if((command != formData.getElements().end()))
       {
         scommand = (**command).c_str();
         // Checken to start the Daemon, thats a specail command
         if (scommand=="STARTDEAMON")
         {
        	 syslog( LOG_ERR, "Trying to start Deamon per web request...");
        	 execv(DEAMON_PATH,NULL);
         }
         // THE CGI VERSION INFO IS CALLED
         if (scommand=="MARELAB_CGI_VERSION")
         {
        	 cout << "content-type: text/html" << endl << endl;
        	 cout << "MARELAB_CGI_VERSION=" << marelab_cgi_version << endl;
        	 return 0;
          }
       }
       else
       {
          syslog( LOG_ERR, "Call without command...");
       }



       /*Getting all form Parameters of the request and
        * transforming it into a JSON string that
        * the deamon can understand...
        */
       vector <FormEntry> vf = formData.getElements();
       string parameterString;
       int trigger_comma = 0;
       for (unsigned int c=0; c < vf.size();c++ ){
			syslog(LOG_ERR, "POST ...[%s]-[%s]", vf[c].getName().c_str(),vf[c].getValue().c_str());
			if (vf[c].getName() == "PARAMETER") {
				if (trigger_comma == 0){
					parameterString = vf[c].getValue();
					trigger_comma = 1;
				}
				else{
					parameterString = parameterString +","+ vf[c].getValue();
				}
			}
			if ((vf[c].getName() != "PARAMETER") && (vf[c].getName() != "COMMAND")) {
				if (trigger_comma == 0) {
					parameterString = "\"" + vf[c].getName() + "\":\""+ vf[c].getValue() + "\"";
					trigger_comma = 1;
				}
				else{
					parameterString = parameterString + ",\"" + vf[c].getName() + "\":\""+ vf[c].getValue() + "\"";
				}
			}
       }

       cout << "CGI: " << parameterString << endl;
       /*
        * SENDING COMMAND & P	ARAMETER TO DEAMON AND WAIT
        * FOR RESPONSE OR TIMEOUT
        */
       string string2send;
       if (parameterString.compare(0,1,"[")==0)
    	   string2send = "{\"COMMAND\":\""+scommand+"\",\"PARAMETER\":"+parameterString+"}\0";
       else
    	   string2send = "{\"COMMAND\":\""+scommand+"\",\"PARAMETER\":{"+parameterString+"}}\0";
       cout << "CGI2DEAMON: " << string2send << endl;

       // Socket Communication
       ipccom sock;
       try
       {
    	   sock.openClient();
    	   syslog( LOG_ERR, "Client socket created successfull...");
    	   string msg;
    	   if (!sock.sendSock(string2send))
    		   syslog( LOG_ERR, "Client socket send failed...");
    	   else
    	   {
    		  syslog( LOG_ERR, "Client socket send [%s] ok...",string2send.c_str());
    		  if (sock.recvSockFromNucleus())
    		  {
    		  	syslog( LOG_ERR, "Recv return from server: OK");
    		  	cout << "content-type: text/html" << endl << endl;
    		  	cout << sock.getMsg().c_str();
    		  }
    	   }
    	   sock.closeServer();

       }
       catch(const char *Exception){
    	   	   	cout << "content-type: text/html" << endl << endl;
    	   	   	string errormsg = Exception;
    	   	   	cout << "{\"ERROR\":\"the server seems to be down reason: ["+errormsg+"] check the logs for more info\"}";
    	   		syslog( LOG_ERR, "the server seems to be down reason:  [%s] ... terminating",Exception );
    	   		sock.closeServer();
       }

       return 0;


    }
    catch(exception& e) {
       // handle any errors here.
       cout << "ERROR!!" << endl;
    }
    return 0;   // To avoid Apache errors.
}
int main(int argc, char *argv[]) {

    try {

        Cgicc cgicc;

        // Send HTTP header: Content-type: text/html
        cout << HTTPHTMLHeader() << endl;

        // Print: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
        cout << HTMLDoctype(HTMLDoctype::eStrict) << endl;

        // Print: <html lang="en" dir="LTR">
        cout << html().set("lang", "EN").set("dir", "LTR") << endl;

        // Set up the HTML document
        cout << html() << head() << title("Random Board") << head() << endl;
        cout << body().set("bgcolor","#cccccc").set("text","#000000").set("link","#0000ff").set("vlink","#000080") << endl;

        string queryString = cgicc.getEnvironment().getQueryString();

//        queryString = "rope=1&firepoker=1";
        if (queryString.length() > 0) {

//            cout << "QueryString : " << queryString << endl;

            BoardInputTransformer *transformer = BoardInputTransformer
                ::createTransformer(queryString, BoardInputTransformer
                ::WEB_QUERY_STRING, NULL);
            BoardInput* boardInput = transformer->transform();
            Board* board = BoardDistributor::distribute(boardInput);

            BoardPrinter* printer = BoardPrinter::createPrinter(BoardPrintType
                ::PRINT_TYPE_HTML, board);

            persist::BoardStoreManager::createStoreManager(
                persist::BoardStoreType::STORE_TYPE_MONGODB, board);

            board->initialise(boardInput);

            delete transformer;
            delete boardInput;
            delete printer;

        } else {

            form_iterator boardInput = cgicc.getElement("boardinput");
            if( !boardInput->isEmpty() && boardInput != (*cgicc).end()) {

                BoardInputTransformer *transformer = BoardInputTransformer
                    ::createTransformer(**boardInput, BoardInputTransformer
                    ::WEB_FORM_TEXTAREA, &cgicc);
                BoardInput* boardInput = transformer->transform();
                Board* board = BoardDistributor::distribute(boardInput);

                BoardPrinter* printer = BoardPrinter::createPrinter(
                    BoardPrintType::PRINT_TYPE_HTML, board);

                persist::BoardStoreManager::createStoreManager(
                    persist::BoardStoreType::STORE_TYPE_MONGODB, board);

                board->initialise(boardInput);

                delete transformer;
                delete boardInput;
                delete printer;

            } else {
                cout << "No text entered for boardinput" << endl;
            }

        }

        // Close the HTML document
        cout << body() << html();
    }
    catch(exception& e) {
        // handle any errors here.
        cout << "ERROR!!" << endl;
    }
    return 0;   // To avoid Apache errors.

    /*

	if (argc == 1) {

		cout << argc << endl; // prints Random Board!

	} else {

		if (argc > 1) {

	        BoardInputTransformer *transformer = BoardInputTransformer
                ::createTransformer(argv, argc, BoardInputTransformer::CONSOLE);
	        BoardInput* boardInput = transformer->transform();
	        Board* board = BoardDistributor::distribute(boardInput);

	        BoardPrinter* printer = BoardPrinter::createPrinter(BoardPrintType
                ::PRINT_TYPE_HTML, board);

	        board->initialise(boardInput);

	        delete transformer;
	        delete boardInput;
	        delete printer;

		}

	}

	bool printArguments = false;

	if (printArguments) {

        for (int i = 0; i < argc; ++i) {
            cout << argv[i] << endl;
        }

    }

	Logger* logger = Logger::getLogger("WeaponRandomBoard");
	logger->info("Done.");

	return 0;

	*/

}
Esempio n. 14
0
int main(int argc, char** argv){
    DB::connect();
    srand(getpid());

    if(!getenv("EQBEATS_DIR")){
        std::cerr << "Environment variable EQBEATS_DIR isn't set." << std::endl;
        return 1;
    }

    std::string logfile = eqbeatsDir()+"/eqbeats.log";
    freopen(logfile.c_str(),"a",stderr);

    Magick::InitializeMagick(NULL);

    FCGX_Request request;
    FCGX_Init();
    FCGX_InitRequest(&request, 0, 0);

    std::string path;
    int id;
    while(FCGX_Accept_r(&request) == 0){
        resetTimer();
        o.attach(&request);
        cgi = Cgicc(&o);
        path = getPath();

        // Nope
        if (cgi.getElementByValue("PHPE9568F34-D428-11d2-A769-00AA001ACF42") != cgi.getElements().end() ||
            cgi.getElementByValue("PHPE9568F35-D428-11d2-A769-00AA001ACF42") != cgi.getElements().end() ||
            cgi.getElementByValue("PHPE9568F36-D428-11d2-A769-00AA001ACF42") != cgi.getElements().end()){
            Http::redirect("http://youtu.be/gvdf5n-zI14");
        }
        // HTTPS redirect
        else if (getenv("EQBEATS_HTTPS") && !cgi.getEnvironment().usingHTTPS() && cgi.getElements().size() == 0)
            Http::redirect(eqbeatsUrl() + path);
        // Static
        else if((id = route("track", "original", path)))
            Http::downloadTrack(id, Track::Original);
        else if((id = route("track", "vorbis", path)))
            Http::downloadTrack(id, Track::Vorbis);
        else if((id = route("track", "mp3", path)))
            Http::downloadTrack(id, Track::MP3);
        else if((id = route("track", "art", path)))
            Http::trackArt(id);
        else if((id = route("track", "art/medium", path)))
            Http::trackArt(id, Art::Medium);
        else if((id = route("track", "art/thumb", path)))
            Http::trackArt(id, Art::Thumbnail);
        // Json
        else if((id = route("track", "json", path)))
            Json::track(id);
        else if((id = route("user", "json", path)))
            Json::artist(id);
        else if((id = route("user", "favorites/json", path)))
            Json::favorites(id);
        else if((id = route("playlist", "json", path)))
            Json::playlist(id);
        else if(path == "/tracks/search/json")
            Json::tracks(Track::search(cgi("q")));
        else if(path == "/tracks/search/exact/json")
            Json::tracks(Track::exactSearch(cgi("artist"),cgi("track")));
        else if(path == "/tracks/latest/json")
            Json::tracks(Track::latest(50));
        else if(path == "/tracks/random/json")
            Json::tracks(Track::random(50));
        else if(path == "/tracks/featured/json")
            Json::tracks(Track::featured(50));
        else if(path == "/artists/json")
            Json::users(User::listArtists(300));
        else if(path == "/users/search/json")
            Json::users(User::search(cgi("q")));
        // Feeds
        else if(path == "/tracks/latest/atom")
            Feed::latest(200);
        else if(path == "/tracks/featured/atom")
            Feed::featured(50);
        else if((id = route("user", "atom", path)))
            Feed::user(id);
        // oEmbed
        else if(path == "/oembed")
            oEmbed(cgi("url"), cgi("format")=="xml", number(cgi("maxwidth")));

        else{
        Session::start();
        // User
        if((id = route("user", path)))
            Html::userPage(id);
        else if((id = route("user", "comment", path)))
            Action::postComment(Comment::User, id);
        else if((id = route("user", "follow", path)))
            Action::follow(id, true);
        else if((id = route("user", "unfollow", path)))
            Action::follow(id, false);
        else if((id = route("user", "favorites", path)))
            Html::favorites(id);
        // Track
        else if((id = route("track", "embed", path)))
            Html::embedTrack(id);
        else if((id = route("track", "delete", path)))
            Action::deleteTrack(id);
        else if((id = route("track", "rename", path)))
            Action::renameTrack(id);
        else if((id = route("track", "notes", path)))
            Action::updateNotes(id);
        else if((id = route("track", "upload", path)))
            Action::uploadTrack(id);
        else if((id = route("track", "art/upload", path)))
            Action::uploadArt(id);
        else if((id = route("track", "publish", path)))
            Action::publishTrack(id);
        else if((id = route("track", "comment", path)))
            Action::postComment(Comment::Track, id);
        else if((id = route("track", "favorite", path)))
            Action::favorite(id, true);
        else if((id = route("track", "unfavorite", path)))
            Action::favorite(id, false);
        else if((id = route("track", "report", path)))
            Action::reportTrack(id);
        else if((id = route("track", "flags", path)))
            Action::setFlags(id);
        else if((id = route("track", "tags", path)))
            Action::setTags(id);
        else if((id = route("track", "license", path)))
            Action::setLicense(id);
        else if((id = route("track", "youtube_upload", path)))
            Action::youtubeUpload(id);
        else if((id = route("track",path)))
            Html::trackPage(id);
        else if(path == "/track/new")
            Action::newTrack();
        // Tracks
        else if(path == "/tracks")
            Http::redirect("/");
        else if(path == "/tracks/search")
            Html::trackSearch(cgi("q"));
        else if(path == "/tracks/latest")
            Html::latestTracks(15);
        else if(path == "/tracks/random")
            Html::tracksPage("Random tracks", Track::random(15));
        else if(path == "/tracks/featured")
            Html::tracksPage("Featured tracks", Track::featured(15));
        else if(path.substr(0,12) == "/tracks/tag/"){
            std::string tag = path.substr(12);
            Html::tracksPage(tag, Track::byTag(tag));
        }
        // News
        else if((id = route("news", path)))
            Http::newsRedirect(id);
        else if(path == "/news")
            Http::redirect("http://blog.eqbeats.org/");
        // Contests
        else if((id = route("contest", path)))
            Html::contest(id);
        else if((id = route("contest", "submit", path)))
            Action::contestSubmission(id);
        else if((id = route("contest", "vote", path)))
            Action::vote(id);
        // Playlists
        else if((id = route("playlist", path)))
            Html::playlistPage(id);
        else if((id = route("track", "playlist", path)))
            Action::playlistAdd(id);
        else if((id = route("playlist", "remove", path)))
            Action::playlistRemove(id);
        else if((id = route("playlist", "move", path)))
            Action::playlistMove(id);
        else if((id = route("playlist", "delete", path)))
            Action::deletePlaylist(id);
        else if((id = route("playlist", "edit", path)))
            Action::editPlaylist(id);
        else if(path == "/playlist/new")
            Action::createPlaylist();
        // Users
        else if(path == "/users/search")
            Html::userSearch(cgi("q"));
        else if(path == "/artists")
            Html::artistsPage(20);
        // Actions
        else if(path == "/register")
            Action::registration();
        else if(path == "/account")
            Action::account();
        else if(path == "/account/reset")
            Action::passwordReset();
        else if(path == "/account/license")
            Action::setLicense();
        else if(path == "/login")
            Action::login();
        else if(path == "/logout")
            Action::logout();
        else if(path == "/oauth/yt/unlink")
            Action::youtubeUnlink();
        else if(path == "/oauth/yt")
            Action::youtubeOauthCallback();
        // Static
        else if(path == "/quickstart")
            Html::quickStart();
        else if(path == "/faq")
            Html::faq();
        else if(path == "/credits")
            Html::credits();
        else if(path == "/api")
            Html::apiDoc();
        else if(path == "")
            Html::home();
        else
            Html::notFound();
        Session::destroy();
        }

        FCGX_Finish_r(&request);
        while(waitpid(-1, NULL, WNOHANG) > 0); // wait for zombies
    }

    DB::close();
    return 0;
}