void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
    {
        if(request.getURI()=="/command") {
            EachInputValue(request, [&](const char *id, const char *command){
                wdmEventData tmp = {std::atoi(id), command};
                wdmSystem::getInstance()->addEvent(tmp);
            });
            response.setContentType("text/plain");
            response.setContentLength(2);
            std::ostream &ostr = response.send();
            ostr.write("ok", 3);
        }
        else if(request.getURI()=="/data") {
            std::vector<wdmID> nodes;
            nodes.push_back(_wdmGetRootNode()->getID());
            EachNodeValue(request, [&](const char *id){
                nodes.push_back(std::atoi(id));
            });

            wdmString json;
            wdmJSONRequest request = {false, false, &json, nodes.empty() ? NULL : &nodes[0], (uint32_t)nodes.size()};
            wdmSystem::getInstance()->requestJSON(request);
            while(!request.done) { Poco::Thread::sleep(2); }
            if(request.canceled) { json="[]"; }

            response.setContentType("application/json");
            response.setContentLength(json.size());
            std::ostream &ostr = response.send();
            ostr.write(&json[0], json.size());
        }
    }
void GenericFileHandler::handleRequest(Poco::Net::HTTPServerRequest & req, Poco::Net::HTTPServerResponse & resp) {

	std::ifstream file;

	try {
		file.open(fileName.c_str(), std::ifstream::in);
	} catch (...) {
	}

	if (!file.is_open()) {
		resp.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		resp.send();
		return;
	}

	std::string wsdl;
	while (!file.eof()) {
		std::string tmp;
		std::getline(file, tmp);
		wsdl += tmp;
	}
	file.close();

	resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
	resp.setContentType("application/xml");
	resp.setChunkedTransferEncoding(false);
	resp.setContentLength(wsdl.length());

	std::ostream & out = resp.send();
	out << wsdl << std::flush;
}
Exemple #3
0
void GetHighScoreDeleteForm::generateResponse(Poco::Net::HTTPServerRequest& inRequest, Poco::Net::HTTPServerResponse& outResponse)
{
    std::string body;
    ReadEntireFile("html/delete.html", body);
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
void ConsoleRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	try
	{
		std::string username;
		Poco::OSP::Web::WebSession::Ptr pSession;
		{
			Poco::OSP::ServiceRef::Ptr pWebSessionManagerRef = _pContext->registry().findByName(Poco::OSP::Web::WebSessionManager::SERVICE_NAME);
			if (pWebSessionManagerRef)
			{
				Poco::OSP::Web::WebSessionManager::Ptr pWebSessionManager = pWebSessionManagerRef->castedInstance<Poco::OSP::Web::WebSessionManager>();
				pSession = pWebSessionManager->find(_pContext->thisBundle()->properties().getString("websession.id"), request);
				username = pSession->getValue<std::string>("username", "");
			}
		}	
	
		if (!username.empty())
		{
			Poco::Net::WebSocket webSocket(request, response);
			_pContext->logger().information(Poco::format("Console WebSocket connection established with %s.", request.clientAddress().toString()));
			forwardMessages(webSocket);
		}
		else
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
			response.setContentLength(0);
			response.send();
		}
	}
	catch (Poco::Net::WebSocketException& exc)
	{
		_pContext->logger().log(exc);
		switch (exc.code())
		{
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
			response.set("Sec-WebSocket-Version", Poco::Net::WebSocket::WEBSOCKET_VERSION);
			// fallthrough
		case Poco::Net::WebSocket::WS_ERR_NO_HANDSHAKE:
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
		case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
			response.setContentLength(0);
			response.send();
			break;
		}
	}
}
Exemple #5
0
void ShowCaptchaPage::handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
{
	m_log->trace("ShowCaptchaPage::handleRequest from "+request.clientAddress().toString());

	std::map<std::string,QueryVar> queryvars;

	CreateQueryVarMap(request,queryvars);

	if(request.getVersion()==Poco::Net::HTTPRequest::HTTP_1_1)
	{
		response.setChunkedTransferEncoding(true);
	}

	std::string content="";
	if(queryvars.find("UUID")!=queryvars.end())
	{
		std::string uuid=(*queryvars.find("UUID")).second.GetData();
		SQLite3DB::Statement st=m_db->Prepare("SELECT MimeType,PuzzleData FROM tblIntroductionPuzzleRequests WHERE UUID=?;");
		st.Bind(0,uuid);
		st.Step();

		if(st.RowReturned())
		{
			std::string mime;
			std::string b64data;
			std::vector<unsigned char> data;

			st.ResultText(0,mime);
			st.ResultText(1,b64data);
			Base64::Decode(b64data,data);

			// mime type should be short and have a / in it - otherwise skip
			if(mime.size()<50 && mime.find('/')!=std::string::npos)
			{
				std::string fname(uuid);
				if(mime=="image/bmp")
				{
					fname+=".bmp";
				}
				else if(mime=="audio/x-wav")
				{
					fname+=".wav";
				}
				response.setContentType(mime);
				response.setContentLength(data.size());
				response.set("Content-Disposition","attachment; filename="+fname);
				content+=std::string(data.begin(),data.end());
			}
		}
	}

	std::ostream &ostr = response.send();
	ostr << content;
}
Exemple #6
0
bool Utility::isAuthenticated(Poco::OSP::Web::WebSession::Ptr pSession, Poco::Net::HTTPServerResponse& response)
{
    if (!pSession || !pSession->has("username"))
    {
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
        response.setContentLength(0);
        response.setChunkedTransferEncoding(false);
        response.send();
        return false;
    }
    return true;
}
Exemple #7
0
bool Utility::isAuthenticated(Poco::OSP::Web::WebSession::Ptr pSession, const Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	if (!pSession || !pSession->has("username") || request.get("X-XSRF-TOKEN", "") != pSession->csrfToken())
	{
		response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED);
		response.setContentLength(0);
		response.setChunkedTransferEncoding(false);
		response.send();
		return false;
	}
	return true;
}
Exemple #8
0
void PostHightScore::generateResponse(Poco::Net::HTTPServerRequest& inRequest,
                                      Poco::Net::HTTPServerResponse& outResponse)
{
    std::string requestBody;
    inRequest.stream() >> requestBody;

    Args args;
    GetArgs(requestBody, args);

    std::string name = URIDecode(GetArg(args, "name"));
    const std::string & score = GetArg(args, "score");

    Statement insert(getSession());
    insert << "INSERT INTO HighScores VALUES(NULL, strftime('%s', 'now'), ?, ?)", use(name), use(score);
    insert.execute();

    // Return an URL instead of a HTML page.
    // This is because the client is the JavaScript application in this case.
    std::string body = ResourceManager::Instance().getResourceLocation(GetResourceId());
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
Exemple #9
0
void DeleteHighScore::generateResponse(Poco::Net::HTTPServerRequest& inRequest,
                                       Poco::Net::HTTPServerResponse& outResponse)
{
    std::string requestBody;
    inRequest.stream() >> requestBody;

    GetLogger().information("Request body is: " + requestBody);

    std::string sql = Poco::replace<std::string>("DELETE FROM HighScores WHERE {{args}}",
                                                 "{{args}}",
                                                 Args2String(GetArgs(requestBody)));

    GetLogger().information("SQL statement is: " + sql);

    Statement insert(getSession());
    insert << sql;
    insert.execute();

    // Return a message indicating success.
    std::string body = "Succesfully performed the following SQL statement: " + sql;
    outResponse.setContentLength(body.size());
    outResponse.send() << body;
}
Exemple #10
0
void
BufferHandler::handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
{
    prepareResponse(resp);
    resp.set("ETag", etag);
    resp.set("Cache-Control", "max-age=300, private");

    if (req.get("If-None-Match", "") == etag) {
        // ETag matched. No content to send;
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
        resp.setReason("Not Modified");

        resp.send().flush();
        return;
    }

    resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
    resp.setContentType(contentType);
    resp.setContentLength(bufferLen);

    std::ostream & out = resp.send();
    out.write(reinterpret_cast<const char*>(buffer), bufferLen);
    out.flush();
};
Exemple #11
0
		void RedirectRequestHandler::handle(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response){
			response.set("Location", to);
			response.setStatusAndReason(Poco::Net::HTTPServerResponse::HTTP_SEE_OTHER);
			response.setContentLength(0);
			response.send();
		}
void ControllerRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	if (request.getURI() == "/favicon.ico")
	{
		return response.redirect("/images/favicon.ico", Poco::Net::HTTPResponse::HTTP_SEE_OTHER);
	}

	Poco::OSP::Web::WebSession::Ptr pSession = _pSessionManager->get(_sessionId, request, _sessionTimeout, context());

	const std::string loginPage = "/macchina/login";
	const std::string launcherPage = "/macchina/launcher";

	std::string message;
	std::string nextPage;
	std::string username;
	Poco::Net::HTMLForm form(request, request.stream());
	std::string action(form.get("action", ""));
	
	if (action == "login")
	{
		username = form.get("username", "");
		std::string password = form.get("password", "");
		if (_pAuthService->authenticate(username, password))
		{
			if (_logger.information())
			{
				_logger.information(format("User %s successfully logged in.", username));
			}
			nextPage = launcherPage;
			pSession->set("username", username);
		}
		else
		{
			if (_logger.warning())
			{
				_logger.warning(format("User %s failed authentication.", username));
			}
			message = "The given username is not known, the password is wrong or the account has been disabled.";
		}
	}
	else if (action == "logout")
	{
		username = pSession->getValue<std::string>("username", "");
		if (!username.empty())
		{
			if (_logger.information())
			{
				_logger.information(format("User %s logged out.", username));
			}
			_pSessionManager->remove(pSession);
		}
	}
	else
	{
		username = pSession->getValue<std::string>("username", "");
		if (!username.empty())
		{
			nextPage = launcherPage;
		}
	}
	
	if (!message.empty())
	{
		pSession->set("message", message);
	}
	else
	{
		pSession->erase("message");
	}
	
	if (nextPage.empty())
	{
		nextPage = loginPage;
	}
	response.setContentLength(0);
	response.redirect(nextPage, Poco::Net::HTTPResponse::HTTP_SEE_OTHER);
	response.set("Cache-Control", "no-cache");
}