HttpResponse FlexAppController::service(HttpRequest req)
{
    HttpResponse res;
    res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
    res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
    res.setContent("[{\"num\": 1,\"name\": \"Sumeet\", \"role\": \"Developer\"},{\"num\": 2,\"name\": \"Ravi\", \"role\": \"Quality Analyst\"},{\"num\": 3,\"name\": \"Amit\", \"role\": \"Web Designer\"}]");
    return res;
}
HttpResponseParser::HttpResponseParser(const std::string& vecstr, HttpResponse &response)
{
	std::vector<std::string> vec;
	StringUtil::split(vec, vecstr, ("\n"));
	if(vec.size()!=0)
	{
		this->content = "";
		std::string conten;
		bool contStarts = false;
		for(unsigned int i=0;i<vec.size();i++)
		{
			//logger << endl << "Reading line " << vec.at(i) << endl << std::flush;
			std::vector<std::string> temp,vemp,memp;
			if((vec.at(i)=="\r" || vec.at(i)==""|| vec.at(i)=="\r\n") && !contStarts)
			{
				contStarts = true;
				continue;
			}

			if(i==0)
			{
				StringUtil::replaceFirst(vec.at(i),"\r","");
				std::vector<std::string> httpst;
				StringUtil::split(httpst, vec.at(i), (" "));
				if(httpst.at(0).find("HTTP")==std::string::npos)
				{

				}
				else
				{
					response.httpVersion = httpst.at(0);
					response.setStatusCode(httpst.at(1));
					response.setStatusMsg(httpst.at(2));
				}
			}
			else if(vec.at(i).find_first_of(":")!=std::string::npos && !contStarts)
			{
				if(vec.at(i).find(":")==vec.at(i).find(": ")) {
					temp.push_back(StringUtil::toLowerCopy(vec.at(i).substr(0, vec.at(i).find_first_of(": "))));
					temp.push_back(vec.at(i).substr(vec.at(i).find_first_of(": ")+2));
				} else {
					temp.push_back(StringUtil::toLowerCopy(vec.at(i).substr(0, vec.at(i).find_first_of(":"))));
					temp.push_back(vec.at(i).substr(vec.at(i).find_first_of(":")+1));
				}
				//logger << temp.at(0) << " => " << temp.at(1) << std::endl;
				StringUtil::replaceFirst(temp.at(1),"\r","");
				response.addHeaderValue(temp.at(0), temp.at(1));
			}
			else if(contStarts)
			{
				conten.append(vec.at(i));
				if(i!=vec.size()-1)
					conten.append("\n");
			}
		}
		this->content = conten;
	}
}
示例#3
0
bool Http11Handler::writeResponse(void* req, void* res, void* context) {
	HttpRequest* request = (HttpRequest*)req;
	HttpResponse* response = (HttpResponse*)res;

	if(isClosed()) {
		if(request!=NULL) {
			delete request;
		}
		delete response;
		return true;
	}

	if(!response->isDone()) {
		response->updateContent(request, chunkSize);
	}

	if(response->getHeader(HttpRequest::Connection)=="")
	{
		if(StringUtil::toLowerCopy(request->getHeader(HttpRequest::Connection))!="keep-alive"
				|| CastUtil::lexical_cast<int>(response->getStatusCode())>307 || request->getHttpVers()<1.1)
		{
			response->addHeaderValue(HttpResponse::Connection, "close");
		}
		else
		{
			response->addHeaderValue(HttpResponse::Connection, "keep-alive");
		}
	}

	std::string data = response->generateOnlyHeaderResponse(request);
	if(!write(data)) {
		bool isFirst = true;
		while(response->hasContent && (data = response->getRemainingContent(request->getUrl(), isFirst)) != "") {
			isFirst = false;
			if(write(data)) {
				break;
			}
		}
	}
	if(request!=NULL) {
		delete request;
	}
	delete response;
	return true;
}
示例#4
0
HttpResponseParser::HttpResponseParser(string vecstr, HttpResponse &response)
{
	vector<string> vec;
	StringUtil::split(vec, vecstr, ("\n"));
	if(vec.size()!=0)
	{
		this->content = "";
		string conten;
		bool contStarts = false;
		for(unsigned int i=0;i<vec.size();i++)
		{
			//logger << endl << "Reading line " << vec.at(i) << endl << flush;
			vector<string> temp,vemp,memp;
			if((vec.at(i)=="\r" || vec.at(i)==""|| vec.at(i)=="\r\n") && !contStarts)
			{
				contStarts = true;
				continue;
			}
			StringUtil::split(temp, vec.at(i), (": "));
			if(temp.size()>1 && !contStarts)
			{
				//logger << temp.at(0) << " => " << temp.at(1) << endl;
				StringUtil::replaceFirst(temp.at(1),"\r","");
				response.addHeaderValue(temp.at(0), temp.at(1));
			}
			else
			{
				string tem = vec.at(i);
				if(!contStarts)
				{
					//logger << "line => " << vec.at(i) << endl;
					StringUtil::replaceFirst(tem,"\r","");
					vector<string> httpst;
					StringUtil::split(httpst, tem, (" "));
					if(httpst.at(0).find("HTTP")==string::npos)
					{

					}
					else
					{
						response.httpVersion = httpst.at(0);
						response.setStatusCode(httpst.at(1));
						response.setStatusMsg(httpst.at(2));
					}
				}
				else
				{
					conten.append(vec.at(i));
					if(i!=vec.size()-1)
						conten.append("\n");
				}
			}
		}
		this->content = conten;
	}
}
示例#5
0
void FviewHandler::handle(HttpRequest* req, HttpResponse& res, map<string, string> fviewmap)
{
	Logger logger = LoggerFactory::getLogger("FviewHandler");
	string content;
	logger << ("Inside fview " + req->getFile()) << endl;
	string file = req->getFile();
	StringUtil::replaceFirst(file,"fview","html");
	string ffile = req->getCntxt_root()+"/fviews/"+file;
	//logger << ffile << endl;
	ifstream infile(ffile.c_str(), ios::binary);
	string temp;
	if(infile.is_open())
	{
		content = "";
		while(getline(infile, temp))
		{
			if(temp.find("<?")==string::npos && temp.find("?>")==string::npos)
				content.append(temp);
		}
		int h = content.find("</head>");
		int ht = content.find("<html>");
		if(h!=(int)string::npos)
		{
			string st = content.substr(0,h-1);
			string en = content.substr(h);
			content = st + "<script type=\"text/javascript\" src=\"public/json2.js\"></script>";
			content += "<script type=\"text/javascript\" src=\"public/prototype.js\"></script>";
			content += "<script type=\"text/javascript\" src=\"public/afc.js\"></script>";
			content += "<script type=\"text/javascript\" src=\"public/_afc_Objects.js\"></script>";
			content += "<script type=\"text/javascript\" src=\"public/_afc_Interfaces.js\"></script>";
			content += "<script type=\"text/javascript\" src=\"public/"+fviewmap[file]+".js\"></script>" + en;
		}
		else
		{
			if(ht!=(int)string::npos)
			{
				string st = content.substr(0,ht+6);
				string en = content.substr(ht+6);
				content = st + "<script type=\"text/javascript\" src=\"public/json2.js\"></script>";
				content += "<script type=\"text/javascript\" src=\"public/prototype.js\"></script>";
				content += "<script type=\"text/javascript\" src=\"public/afc.js\"></script>";
				content += "<script type=\"text/javascript\" src=\"public/_afc_Objects.js\"></script>";
				content += "<script type=\"text/javascript\" src=\"public/_afc_Interfaces.js\"></script>";
				content += "<script type=\"text/javascript\" src=\"public/"+fviewmap[file]+".js\"></script>" + en;
			}
		}
		res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_SHTML);
		res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
		res.setContent(content);
		infile.close();
	}
	else
	{
		res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
	}
}
示例#6
0
bool ScriptHandler::handle(HttpRequest* req, HttpResponse& res, map<string, string> handoffs,
		string ext, map<string, string> props)
{
	bool skipit = false;
	string referer = req->getHeader(HttpRequest::Referer);
	if(referer.find("http://")!=string::npos)
	{
		string appl = referer.substr(referer.find("http://")+7);
		appl = appl.substr(referer.find("/")+1);
		if(appl.find(req->getCntxt_name())==0 && handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			if(appl==req->getCntxt_name()+"/"+handoffs[req->getCntxt_name()])
			{

			}
		}
	}
	if(ext==".php")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		string phpcnts = req->toPHPVariablesString(def);
		//logger << phpcnts << endl;
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".php";
		tmpf = req->getCntxt_root() + tmpf;

		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "php " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	else if(ext==".pl")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".pl";
		tmpf = req->getCntxt_root() + tmpf;
		string phpcnts = req->toPerlVariablesString();
		//logger << tmpf << endl;
		string plfile = req->getUrl();
		ifstream infile(plfile.c_str());
		string xml;
		if(infile.is_open())
		{
			while(getline(infile, xml))
			{
				phpcnts.append(xml+"\n");
			}
		}
		infile.close();
		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "perl " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	else if(ext==".rb")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		string phpcnts = req->toRubyVariablesString();
		//logger << phpcnts << endl;
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".rb";
		tmpf = req->getCntxt_root() + tmpf;

		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "ruby " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	else if(ext==".py")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".py";
		tmpf = req->getCntxt_root() + tmpf;
		string phpcnts = req->toPythonVariablesString();
		string plfile = req->getUrl();
		ifstream infile(plfile.c_str());
		string xml;
		if(infile.is_open())
		{
			while(getline(infile, xml))
			{
				phpcnts.append(xml+"\n");
			}
		}
		infile.close();
		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "python " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	else if(ext==".lua")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		string phpcnts = req->toLuaVariablesString();
		//logger << phpcnts << endl;
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".lua";
		tmpf = req->getCntxt_root() + tmpf;

		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "lua " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	else if(ext==".njs")
	{
		skipit = true;
		//int pipe[3];
		//int pid;
		string def;
		string tmpf = "/temp/";
		string filen;
		if(handoffs.find(req->getCntxt_name())!=handoffs.end())
		{
			def = handoffs[req->getCntxt_name()];
			tmpf = "/";
		}
		string phpcnts = req->toNodejsVariablesString();
		//logger << phpcnts << endl;
		filen = CastUtil::lexical_cast<string>(Timer::getCurrentTime()) + ".njs";
		tmpf = req->getCntxt_root() + tmpf;

		AfcUtil::writeTofile(tmpf+filen, phpcnts, true);

		string command = "node " + filen;
		string content = chdirExecute(command, tmpf, Constants::SCRIPT_EXEC_SHOW_ERRS);
		if((content.length()==0))
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
			//res.setContent_len("0");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, props[".html"]);
			res.setContent(content);
			//res.setContent_len(CastUtil::lexical_cast<string>(content.length()));
		}
	}
	return skipit;
}
示例#7
0
bool ExtHandler::handle(HttpRequest* req, HttpResponse& res, void* dlib, void* ddlib,string ext)
{
	string resourcePath = ConfigurationData::getInstance()->resourcePath;
	map<string, string> tmplMap = ConfigurationData::getInstance()->tmplMap;
	map<string, string> vwMap = ConfigurationData::getInstance()->vwMap;
	map<string, string> props = ConfigurationData::getInstance()->props;
	map<string, string> ajaxIntfMap = ConfigurationData::getInstance()->ajaxIntfMap;

	Logger logger = LoggerFactory::getLogger("ExtHandler");
	bool cntrlit = false;
	string content, claz;
	string acurl = req->getActUrl();
	StringUtil::replaceFirst(acurl,"//","/");
	if(acurl.length()>1)
		acurl = acurl.substr(1);
	if(acurl.find(req->getCntxt_name())!=0)
		acurl = req->getCntxt_name() + "/" + acurl;

	if(ajaxIntfMap[acurl]!="" && req->getMethod()=="POST" && req->getRequestParam("method")!="")
	{
		cntrlit = true;
		string claz = ajaxIntfMap[acurl];

		logger << "Inside Ajax Interface Execute" << endl;
		strVec vemp;
		string methName = req->getRequestParam("method");
		if(methName=="")
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
		}
		else
		{
			string temp = req->getRequestParam("paramsize");
			int paramSize = 0;
			if(temp!="")
			{
				try {
					paramSize = CastUtil::lexical_cast<int>(temp.c_str());
				} catch(...) {
					res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
					paramSize = -1;
				}
			}
			if(paramSize>=0)
			{
				logger << "Reading Ajax params" << endl;
				for(int i=0;i<paramSize;i++)
				{
					stringstream s;
					string ss;
					s << (i+1);
					s >> ss;
					ss = "param_" + ss;
					//logger << ss << flush;
					string tem = req->getRequestParam(ss);
					vemp.push_back(tem);
				}
				string libName = INTER_LIB_FILE;
				string funcName;
				string metn,re;
				StringUtil::replaceAll(claz, "::", "_");
				metn = req->getCntxt_name() + "invokeAjaxMethodFor"+claz+methName;
				void *mkr = dlsym(dlib, metn.c_str());
				if(mkr!=NULL)
				{
					typedef string (*Funptr2) (strVec);
					Funptr2 f2 = (Funptr2)mkr;
					logger << ("Calling method " + metn) << endl;
					re = f2(vemp);
					logger << "Completed method call" << endl;
					res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
					res.addHeaderValue(HttpResponse::ContentType, "text/plain");
					res.setContent(re);
				}
				else
				{
					res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
				}
			}
			else
			{
示例#8
0
HttpResponse OAUTHController::service(HttpRequest req)
{
	HttpResponse res;
	map<string,string> reqParams = req.getAllParams();

	string hostp = req.getHeader(HttpRequest::Host);
	int port = 8080;
	if(hostp.find(":")!=string::npos)
		port = CastUtil::lexical_cast<int>(hostp.substr(hostp.find(":")+1));

	if(req.getFile()=="login.auth")
	{
		if(reqParams["username"]!="" && reqParams["password"]!="")
		{
			FileAuthController fauthu(req.getCntxt_root()+"/users",":");
			string key;
			bool flag = fauthu.getPassword(reqParams["username"],key);
			if(flag)
			{
				res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
				res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
				res.setContent("Valid Login");
			}
			else
			{
				res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
				res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
				res.setContent("InValid Login");
			}
			cout << "inside oauth controller non empty credentials" << endl;
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Username and Password cannot be blank");
			cout << "inside oauth controller empty credentials" << endl;
		}
	}
	else if(req.getFile()=="requestToken.auth")
	{
		Client client;
		client.connection("localhost",port);
		string data = "GET /request.oauth?";
		data += "oauth_callback=http://"+hostp+"/oauthApp/calledback.auth&oauth_consumer_key=sumeet&oauth_nonce=&oauth_timestamp=0&oauth_token=&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&tusername="******"tusername"]+"&";
		string sig = "GET&" + CryptoHandler::urlEncode("http://"+hostp+"/request.oauth") + "&";
		sig += CryptoHandler::urlEncode("oauth_callback=http://"+hostp+"/oauthApp/calledback.auth&oauth_consumer_key=sumeet&oauth_nonce=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=0&oauth_token=&oauth_version=1.0&tusername="******"tusername"]);

		cout << sig << endl;

		char* resst = (char*)CryptoHandler::hmac_sha1((char*)sig.c_str(),"sumeet&",true);
		data += "oauth_signature=";
		string sign(resst);
		data.append(CryptoHandler::urlEncode(sign));

		data += " HTTP/1.1\r\nHost: "+hostp+"\r\nUser-Agent: Program\r\n\r\n";

		cout << data << endl;

		int bytes = client.sendData(data);
		string call,tot;
		while((call=client.getData())!="")
			tot.append(call);
		HttpResponseParser parser(tot, res);
		client.closeConnection();

		map<string,string> mapsd;
		vector<string> temp;
		string conte = parser.getContent();
		StringUtil::split(temp, conte, ("&"));
		//cout << conte << flush;
		for(unsigned int i=0;i<temp.size();i++)
		{
			vector<string> temp1;
			StringUtil::split(temp1, temp.at(i), ("="));
			mapsd[temp1.at(0)] = temp1.at(1);
			cout << temp1.at(0) << " = " << temp1.at(1) << endl;
		}
		if(mapsd["oauth_token"]!="" && mapsd["oauth_token_secret"]!="" && mapsd["tusername"]!="")
		{
			string filen = req.getCntxt_root()+"/"+reqParams["tusername"]+"-tokens-secrets";
			ofstream ofs(filen.c_str());
			string wrf = mapsd["tusername"] + ":" + mapsd["oauth_token"] + ":" + mapsd["oauth_token_secret"]+"\n";
			ofs.write(wrf.c_str(),wrf.length());
			ofs.close();
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Acquired request token");
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Could not get request token");
		}
	}
	else if(req.getFile()=="authorizeUser.auth")
	{
		FileAuthController fauthu(req.getCntxt_root()+"/"+reqParams["tusername"]+"-tokens-secrets",":");
		string key1 = "sumeet&",key;
		bool flag = fauthu.getPassword(reqParams["tusername"],key);
		if(reqParams["tusername"]!="" && flag)
		{
			string tok = key.substr(0,key.find(":"));
			key = key1 + key.substr(key.find(":")+1);

			string data = "http://"+hostp+"/login.oauth?";
			data += "oauth_token="+tok+"&username="******"tusername"];
			cout << data << endl;

			res.setHTTPResponseStatus(HTTPResponseStatus::MovedPermanently);
			res.addHeaderValue(HttpResponse::Location, data);
			cout << "redirecting to third party url" << endl;
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Invalid user");

		}

	}
	else if(req.getFile()=="calledback.auth")
	{
		FileAuthController fauthu(req.getCntxt_root()+"/"+reqParams["tusername"]+"-tokens-secrets",":");
		string key1 = "sumeet&",key;
		key = fauthu.get(reqParams["tusername"],2);
		string tok = fauthu.get(reqParams["tusername"],1);
		bool flag = (tok!="" && key!="");
		if(reqParams["tusername"]!="" && flag && reqParams["access"]=="true")
		{
			key = key1 + key;

			Client client;
			client.connection("localhost",port);
			string data = "GET /access.oauth?";
			data += "oauth_consumer_key=sumeet&oauth_nonce=&oauth_timestamp=0&oauth_token="+tok+"&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&tusername="******"tusername"]+"&";
			string sig = "GET&" + CryptoHandler::urlEncode("http://"+hostp+"/access.oauth") + "&";
			sig += CryptoHandler::urlEncode("oauth_consumer_key=sumeet&oauth_nonce=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=0&oauth_token="+tok+"&oauth_version=1.0&tusername="******"tusername"]);

			cout << sig << endl;
			cout << key << endl;
			char* resst = (char*)CryptoHandler::hmac_sha1((char*)sig.c_str(),(char*)key.c_str(),true);
			data += "oauth_signature=";
			string sign(resst);
			data.append(CryptoHandler::urlEncode(sign));

			data += " HTTP/1.1\r\nHost: "+hostp+"\r\nUser-Agent: Program\r\n\r\n";

			cout << data << endl;

			int bytes = client.sendData(data);
			string call,tot;
			while((call=client.getData())!="")
				tot.append(call);
			HttpResponseParser parser(tot, res);
			client.closeConnection();

			map<string,string> mapsd;
			vector<string> temp;
			string conte = parser.getContent();
			StringUtil::split(temp, conte, ("&"));
			//cout << conte << flush;
			for(unsigned int i=0;i<temp.size();i++)
			{
				vector<string> temp1;
				StringUtil::split(temp1, temp.at(i), ("="));
				mapsd[temp1.at(0)] = temp1.at(1);
				cout << temp1.at(0) << " = " << temp1.at(1) << endl;
			}
			if(mapsd["oauth_token"]!="" && mapsd["oauth_token_secret"]!="" && mapsd["tusername"]!="")
			{
				string filen = req.getCntxt_root()+"/"+reqParams["tusername"]+"-access-secrets";
				ofstream ofs(filen.c_str());
				string wrf = mapsd["tusername"] + ":" + mapsd["oauth_token"] + ":" + mapsd["oauth_token_secret"]+"\n";
				ofs.write(wrf.c_str(),wrf.length());
				ofs.close();
				res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
				res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_SHTML);
				string conte = "<html><head><script type='text/javascript' src='public/json2.js'></script><script type='text/javascript' src='public/prototype.js'></script><script type='text/javascript' src='public/oauth.js'></script></head>";
				conte += "File Name: <input id='resource' type='text'/><input type='submit' onclick='getResource(\"resource\",\""+reqParams["tusername"]+"\")'/></body>";
				conte += "</html>";
				res.setContent(conte);
			}
			else
			{
				res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
				res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
				res.setContent("Could not get access token");
			}
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Invalid user");
		}
	}
	else if(req.getFile()=="accessToken.auth")
	{

	}
	else if(req.getFile()=="getResource.auth")
	{
		FileAuthController fauthu(req.getCntxt_root()+"/"+reqParams["tusername"]+"-access-secrets",":");
		string key1 = "sumeet&",key;
		key = fauthu.get(reqParams["tusername"],2);
		string tok = fauthu.get(reqParams["tusername"],1);
		bool flag = (tok!="" && key!="");
		if(reqParams["tusername"]!="" && flag && reqParams["file"]!="")
		{
			key = key1 + key;

			Client client;
			client.connection("localhost",port);
			string data = "GET /getResource.oauth?file="+reqParams["file"];
			data += "&oauth_consumer_key=sumeet&oauth_nonce=&oauth_timestamp=0&oauth_token="+tok+"&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&tusername="******"tusername"]+"&";
			string sig = "GET&" + CryptoHandler::urlEncode("http://"+hostp+"/getResource.oauth") + "&";
			sig += CryptoHandler::urlEncode("file="+reqParams["file"]+"&oauth_consumer_key=sumeet&oauth_nonce=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=0&oauth_token="+tok+"&oauth_version=1.0&tusername="******"tusername"]);

			cout << sig << endl;
			cout << key << endl;
			char* resst = (char*)CryptoHandler::hmac_sha1((char*)sig.c_str(),(char*)key.c_str(),true);
			data += "oauth_signature=";
			string sign(resst);
			data.append(CryptoHandler::urlEncode(sign));

			data += " HTTP/1.1\r\nHost: "+hostp+"\r\nUser-Agent: Program\r\n\r\n";

			cout << data << endl;

			int bytes = client.sendData(data);
			string call,tot;
			while((call=client.getData())!="")
				tot.append(call);
			HttpResponseParser parser(tot, res);
			client.closeConnection();

			res.setContent(parser.getContent());
		}
		else
		{
			res.setHTTPResponseStatus(HTTPResponseStatus::Ok);
			res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
			res.setContent("Access denied");
		}
	}
	return res;
}
示例#9
0
bool ControllerHandler::handle(HttpRequest* req, HttpResponse& res, ConfigurationData configData,
		string ext, string pthwofile)
{
	map<string, string> urlpattMap = configData.urlpattMap;
	map<string, string> mappattMap = configData.mappattMap;
	resFuncMap rstCntMap = configData.rstCntMap;
	map<string, string> mapMap = configData.mapMap;
	map<string, string> urlMap = configData.urlMap;

	Logger logger = LoggerFactory::getLogger("ControllerHandler");
	bool isContrl = false;
	if((urlpattMap[req->getCntxt_name()+"*.*"]!="" || urlMap[req->getCntxt_name()+ext]!=""))
	{
		//logger << "Controller requested for " << req->getCntxt_name() << " name " << urlMap[req->getCntxt_name()+ext] << endl;
		string controller;
		if(urlpattMap[req->getCntxt_name()+"*.*"]!="")
			controller = urlpattMap[req->getCntxt_name()+"*.*"];
		else
			controller = urlMap[req->getCntxt_name()+ext];

		void *_temp = configData.ffeadContext->getBean("controller_"+req->getCntxt_name()+controller, req->getCntxt_name());
		Controller* thrd = static_cast<Controller*>(_temp);
		if(thrd!=NULL)
		{
			try{
				 logger << ("Controller " + controller + " called") << endl;
				 res = thrd->service(*req);
				 if(res.getStatusCode()!="")
					 isContrl = true;
				 ext = AuthHandler::getFileExtension(req->getUrl());
				 //delete mkr;
			}catch(...){
				logger << "Controller Exception occurred" << endl;
			}
			logger << "Controller call complete" << endl;
		}
		else
		{
			logger << "Invalid Controller" << endl;
			res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
			isContrl = true;
		}

	}
	else if((mappattMap[req->getCntxt_name()+"*.*"]!="" || mapMap[req->getCntxt_name()+ext]!=""))
	{
		string file = req->getFile();
		string fili = file.substr(0,file.find_last_of("."));
		if(mappattMap[req->getCntxt_name()+"*.*"]!="")
		{
			req->setFile(fili+mappattMap[req->getCntxt_name()+"*.*"]);
			logger << ("URL mapped from * to " + mappattMap[req->getCntxt_name()+"*.*"]) << endl;
		}
		else
		{
			req->setFile(fili+mapMap[req->getCntxt_name()+ext]);
			logger << ("URL mapped from " + ext + " to " + mapMap[req->getCntxt_name()+ext]) << endl;
		}
	}
	else
	{
		resFuncMap::iterator it;
		RestFunction rft;
		bool flag = false;
		int prsiz = 0;
		vector<string> valss;
		map<string, string> mapOfValues;
		//logger << pthwofile << endl;
		for (it=rstCntMap.begin();it!=rstCntMap.end();it++)
		{
			valss.clear();
			//logger << it->first << endl;
			//if(pthwofile.find(it->first)!=string::npos)
			{
				RestFunction ft = it->second;
				prsiz = ft.params.size();
				string pthwofiletemp(pthwofile);

				string baseUrl(it->first);
				strVec resturlparts;
				StringUtil::split(resturlparts, baseUrl, "/");

				strVec urlparts;
				StringUtil::split(urlparts, pthwofiletemp, "/");

				if(urlparts.size()!=resturlparts.size())
				{
					flag = false;
					//break;
				}
				else
				{
					flag = true;
				}
				if(flag)
				{
					bool fflag = true;
					for (int var = 0; var < (int)resturlparts.size(); var++)
					{
						//logger << "resturlparts.at(var) = " << resturlparts.at(var) << endl;
						if(resturlparts.at(var).find("{")!=string::npos && resturlparts.at(var).find("}")!=string::npos
								&& resturlparts.at(var).length()>2)
						{
							string paramname = resturlparts.at(var);
							string pref, suff;
							int st = paramname.find("{")+1;
							pref = paramname.substr(0, st-1);
							int len = paramname.find("}") - st;
							suff = paramname.substr(paramname.find("}")+1);
							paramname = paramname.substr(st, len);
							string paramvalue = urlparts.at(var);
							if(st>1)
							{
								int stpre = paramvalue.find(pref) + pref.length();
								int len = paramvalue.length() - pref.length() - suff.length();
								paramvalue = paramvalue.substr(stpre, len);
							}
							mapOfValues[paramname] = paramvalue;
							//logger << "mapOfValues(" << paramname << ") = "<< paramvalue << endl;
							logger << ("Restcontroller matched url : " + pthwofiletemp + ",param size: " + CastUtil::lexical_cast<string>(prsiz) +
										", against url: " + baseUrl) << endl;
						}
						else if(urlparts.at(var)!=resturlparts.at(var))
						{
							fflag = false;
							break;
						}
					}
					flag = fflag;
				}

				string lhs = StringUtil::toUpperCopy(ft.meth);
				string rhs = StringUtil::toUpperCopy(req->getMethod());
				//if(prsiz==(int)valss.size() && lhs==rhs)
				if(flag && lhs==rhs)
				{

					logger << "Encountered rest controller url/method match" << endl;
					rft = ft;
					flag = true;
					break;
				}
				else if(flag)
				{
					res.setHTTPResponseStatus(HTTPResponseStatus::InvalidMethod);
					return true;
				}
				else
				{
					res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
					//res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
					/*if(prsiz==valss.size())
						res.setContent("Invalid number of arguments");
					else
						res.setContent("Invalid HTTPMethod used");*/
					//logger << "Rest Controller Param/Method Error" << endl;
				}
			}
		}
		if(flag)
		{
			//logger << "inside restcontroller logic ..." << endl;
			Reflector ref;
			ClassInfo srv = ref.getClassInfo(rft.clas, req->getCntxt_name());
			void *_temp = configData.ffeadContext->getBean("restcontroller_"+req->getCntxt_name()+rft.clas, req->getCntxt_name());
			RestController* rstcnt = (RestController*)_temp;
			if(rstcnt==NULL)
			{
				logger << "Invalid Rest Controller" << endl;
				res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
				return true;
			}

			rstcnt->request = req;
			rstcnt->response = &res;

			args argus;
			vals valus;
			bool invValue = false;
			vector<ifstream*> allStreams;
			map<string, vector<ifstream*>* > mpvecstreams;
			for (int var = 0; var < prsiz; var++)
			{
				try
				{
					string icont = rft.icontentType;
					string ocont = rft.ocontentType;

					if(icont=="")
						icont = ContentTypes::CONTENT_TYPE_APPLICATION_JSON;
					else if(icont!=req->getHeader(HttpRequest::ContentType) && req->getHeader(HttpRequest::ContentType).find(icont)!=0)
					{
						res.setHTTPResponseStatus(HTTPResponseStatus::UnsupportedMedia);
						return true;
					}

					if(ocont=="")
						ocont = ContentTypes::CONTENT_TYPE_APPLICATION_JSON;

					req->addHeaderValue(HttpRequest::ContentType, icont);
					res.addHeaderValue(HttpResponse::ContentType, ocont);

					string pmvalue;
					if(rft.params.at(var).from=="path")
						pmvalue = mapOfValues[rft.params.at(var).name];
					else if(rft.params.at(var).from=="reqparam")
						pmvalue = req->getQueryParam(rft.params.at(var).name);
					else if(rft.params.at(var).from=="postparam")
						pmvalue = req->getRequestParam(rft.params.at(var).name);
					else if(rft.params.at(var).from=="header")
						pmvalue = req->getHeader(rft.params.at(var).name);
					else if(rft.params.at(var).from=="multipart-content")
					{
						MultipartContent mcont = req->getMultipartContent(rft.params.at(var).name);
						if(mcont.isValid())
						{
							if(mcont.isAFile())
							{
								if(rft.params.at(var).type=="filestream")
								{
									pmvalue = rft.params.at(var).name;
								}
								else if(rft.params.at(var).type!="vector-of-filestream")
								{
									logger << "File can only be mapped to ifstream" << endl;
									res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
									return true;
								}
							}
							else
							{
								pmvalue = mcont.getContent();
							}
						}
						else if(rft.params.at(var).type!="vector-of-filestream")
						{
							logger << "Invalid mapping specified in config, no multipart content found with name " + rft.params.at(var).name << endl;
							res.setHTTPResponseStatus(HTTPResponseStatus::InternalServerError);
							return true;
						}
					}
					else
					{
						if(prsiz>1)
						{
							logger << "Request Body cannot be mapped to more than one argument..." << endl;
							res.setHTTPResponseStatus(HTTPResponseStatus::BadRequest);
							return true;
						}
						pmvalue = req->getContent();
					}

					logger << ("Restcontroller parameter type/value = "  + rft.params.at(var).type + "/" + pmvalue) << endl;
					logger << ("Restcontroller content types input/output = " + icont + "/" + ocont) << endl;

					if(rft.params.at(var).type=="int")
					{
						argus.push_back(rft.params.at(var).type);
						int* ival = new int(CastUtil::lexical_cast<int>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="short")
					{
						argus.push_back(rft.params.at(var).type);
						short* ival = new short(CastUtil::lexical_cast<short>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="long")
					{
						argus.push_back(rft.params.at(var).type);
						long* ival = new long(CastUtil::lexical_cast<long>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="double")
					{
						argus.push_back(rft.params.at(var).type);
						double* ival = new double(CastUtil::lexical_cast<double>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="float")
					{
						argus.push_back(rft.params.at(var).type);
						float* ival = new float(CastUtil::lexical_cast<float>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="bool")
					{
						argus.push_back(rft.params.at(var).type);
						bool* ival = new bool(CastUtil::lexical_cast<bool>(pmvalue));
						valus.push_back(ival);
					}
					else if(rft.params.at(var).type=="string" || rft.params.at(var).type=="std::string")
					{
						argus.push_back(rft.params.at(var).type);
						string* sval = new string(pmvalue);
						valus.push_back(sval);
					}
					else if(rft.params.at(var).type=="filestream")
					{
						argus.push_back("ifstream*");
						MultipartContent mcont = req->getMultipartContent(pmvalue);
						if(mcont.isValid() && mcont.isAFile())
						{
							ifstream* ifs = new ifstream;
							ifs->open(mcont.getTempFileName().c_str());
							valus.push_back(ifs);
							allStreams.push_back(ifs);
						}
					}
					else if(rft.params.at(var).type=="vector-of-filestream")
					{
						vector<ifstream*> *vifs = NULL;
						if(mpvecstreams.find(rft.params.at(var).name)==mpvecstreams.end())
						{
							argus.push_back("vector<ifstream*>");
							vifs = new vector<ifstream*>;
							vector<MultipartContent> mcontvec = req->getMultiPartFileList(rft.params.at(var).name);
							for(int mci=0;mci<(int)mcontvec.size();mci++) {
								MultipartContent mcont = mcontvec.at(mci);
								if(mcont.isValid() && mcont.isAFile())
								{
									ifstream* ifs = new ifstream;
									ifs->open(mcont.getTempFileName().c_str());
									vifs->push_back(ifs);
									allStreams.push_back(ifs);
								}
							}
							mpvecstreams[rft.params.at(var).name] = vifs;
						}
						else
						{
							vifs = mpvecstreams[rft.params.at(var).name];
						}
						valus.push_back(vifs);
					}
					else if(rft.params.at(var).type.find("vector-of-")==0 || rft.params.at(var).type.find("list-of-")==0
							|| rft.params.at(var).type.find("deque-of-")==0 || rft.params.at(var).type.find("set-of-")==0
							|| rft.params.at(var).type.find("multiset-of-")==0 || rft.params.at(var).type.find("queue-of-")==0)
					{
						string stlcnt = rft.params.at(var).type;
						string stltype;
						string typp;
						if(rft.params.at(var).type.find("vector-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"vector-of-","");
							stltype = "std::vector";
							typp = "vector<" + stlcnt + ">";
						}
						else if(rft.params.at(var).type.find("list-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"list-of-","");
							stltype = "std::list";
							typp = "list<" + stlcnt + ">";
						}
						else if(rft.params.at(var).type.find("deque-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"deque-of-","");
							stltype = "std::deque";
							typp = "deque<" + stlcnt + ">";
						}
						else if(rft.params.at(var).type.find("set-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"set-of-","");
							stltype = "std::set";
							typp = "set<" + stlcnt + ">";
						}
						else if(rft.params.at(var).type.find("multiset-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"multiset-of-","");
							stltype = "std::multiset";
							typp = "multiset<" + stlcnt + ">";
						}
						else if(rft.params.at(var).type.find("queue-of-")==0)
						{
							StringUtil::replaceFirst(stlcnt,"queue-of-","");
							stltype = "std::queue";
							typp = "queue<" + stlcnt + ">";
						}
						StringUtil::replaceFirst(stlcnt," ","");
						logger << ("Restcontroller param body holds "+stltype+" of type "  + stlcnt) << endl;

						argus.push_back(typp);
						void* voidPvect = NULL;
						if(icont==ContentTypes::CONTENT_TYPE_APPLICATION_JSON)
						{
							voidPvect = JSONSerialize::unSerializeUnknown(pmvalue, stltype+"<"+stlcnt+">",req->getCntxt_name());
						}
#ifdef INC_XMLSER
						else
						{
							voidPvect = XMLSerialize::unSerializeUnknown(pmvalue, stltype+"<"+stlcnt+",",req->getCntxt_name());
						}
#endif
						if(voidPvect==NULL)
						{
							res.setHTTPResponseStatus(HTTPResponseStatus::BadRequest);
							return true;
						}
						valus.push_back(voidPvect);
					}
					else
					{
						argus.push_back(rft.params.at(var).type);
						void* voidPvect = NULL;
						if(icont==ContentTypes::CONTENT_TYPE_APPLICATION_JSON)
						{
							voidPvect = JSONSerialize::unSerializeUnknown(pmvalue, rft.params.at(var).type,req->getCntxt_name());
						}
#ifdef INC_XMLSER
						else
						{
							voidPvect = XMLSerialize::unSerializeUnknown(pmvalue, rft.params.at(var).type,req->getCntxt_name());
						}
#endif
						if(voidPvect==NULL)
						{
							res.setHTTPResponseStatus(HTTPResponseStatus::BadRequest);
							return true;
						}
						valus.push_back(voidPvect);
					}
				} catch (const char* ex) {
					logger << "Restcontroller exception occurred" << endl;
					logger << ex << endl;
					invValue= true;
					res.setHTTPResponseStatus(HTTPResponseStatus::BadRequest);
					return true;
				} catch (...) {
					logger << "Restcontroller exception occurred" << endl;
					invValue= true;
					res.setHTTPResponseStatus(HTTPResponseStatus::BadRequest);
					return true;
				}
			}

			Method meth = srv.getMethod(rft.name, argus);
			if(meth.getMethodName()!="" && !invValue)
			{
				ref.invokeMethodUnknownReturn(_temp,meth,valus);
				logger << "Successfully called restcontroller" << endl;
				//return;

				for(int i=0;i<(int)allStreams.size();++i) {
					if(allStreams.at(i)!=NULL) {
						if(allStreams.at(i)->is_open()) {
							allStreams.at(i)->close();
							allStreams.at(i)->clear();
						}
						delete allStreams.at(i);
					}
				}

				map<string, vector<ifstream*>* >::iterator it;
				for(it=mpvecstreams.begin();it!=mpvecstreams.end();++it) {
					delete it->second;
				}
			}
			else
			{
				res.setHTTPResponseStatus(HTTPResponseStatus::NotFound);
				//res.addHeaderValue(HttpResponse::ContentType, ContentTypes::CONTENT_TYPE_TEXT_PLAIN);
				logger << "Rest Controller Method Not Found" << endl;
				//return;
			}
		}
	}
	return isContrl;
}