Beispiel #1
0
    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());
        }
    }
Beispiel #2
0
void RESTHandler::handleRequest(Poco::Net::HTTPServerRequest &request,
                                Poco::Net::HTTPServerResponse &response) {
    if (verbose) {
        std::clog << "HTTP request " << request.getURI() << std::endl;
        std::clog << "Context id: " << client.context_id() << std::endl;
    }
    zmqpp::message msg, reply;
    /// Connect to broker if not connected
    client.connect(broker);
    Poco::URI url(request.getURI());
    Poco::Net::HTMLForm form(request);
    /// Filter by black list
    if (black_list.find(url.getPath()) != black_list.end()) {
        return error_black_list(response);
    }
    if (!build_message(request, form, url, msg)) {
        return error_parse(response);
    }
    if (!client.send_request(msg, reply, (form.has("timeout") ? std::stoi(form.get("timeout")) : timeout))) {
        return error_timeout(response);
    }
    /// Render response
    response.setStatus(Poco::Net::HTTPServerResponse::HTTPStatus::HTTP_OK);
    if (form.get("type", "json") == "json") {
        /// JSON in single line (FastWriter)
        std::string jsonp_callback = form.get("jsonp", form.get("callback", ""));
        Json::Value packet(Json::ValueType::arrayValue);
        response.setContentType("application/json");
        std::ostream &out = response.send();
        if (!jsonp_callback.empty())
            out << jsonp_callback << "(";
        for (size_t part = 0; part < reply.parts(); ++part)
            packet.append(reply.get(part));
        auto txt = writer.write(packet);
        if (txt[txt.size() - 1] == '\n') // Cheat for EOL in serialization
            txt = txt.substr(0, txt.size() - 1);
        out << txt << (!jsonp_callback.empty() ? ")" : "") << std::flush;
    } else {
        /// Plain text wihtout delimiters
        response.setContentType("text/plain");
        std::ostream &out = response.send();
        for (size_t part = 0; part < reply.parts(); ++part)
            out.write((char *) reply.raw_data(part), reply.size(part));
        out.flush();
    }


}
   /* virtual*/ void handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
    {
        resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK);       //Sets the HTTP status code, Why?
        resp.setContentType("text/html");                       // set the content type of the message

        ostream& out = resp.send();        //Returns an output stream for sending the response body. The returned stream is valid until the response object is destroyed.
        out << "<h1>Hello world!</h1>"     //Body of the repsonse
       // << "<p>Count: "  << ++count         << "</p>"
        << "<p>Host: "   << req.getHost()   << "</p>"       //Returns the value of the Host header field.
        << "<p>Method: " << req.getMethod() << "</p>"
        << "<p>URI: "    << req.getURI() << "</p>";
        out.flush();
        cout << endl
        //<< "Response sent for count=" << count
        << " Response sent for URI=" << req.getURI() << endl;
    }
Beispiel #4
0
void RootReqDispatcher::dispatch(const Poco::Net::HTTPServerRequest& procReq,
								 Poco::Net::HTTPServerResponse &out)
{
	using Poco::URI;
	using std::string;
	using std::vector;

	// Construyo una URI
	URI uri(procReq.getURI());

	// Obtengo los segmentos del path
	vector<string> pathSegs;
	uri.getPathSegments(pathSegs);
	if (pathSegs.size() == 0)
		pathSegs.push_back(""); // Por consistencia

	// Uso el primer segmento para determinar a donde despachar
	TDispatchMap::iterator itDisp = dispatchMap_.find(pathSegs[0]);
	
	// Si no encontré a donde mandarlo, es error
	if (itDisp == dispatchMap_.end())
	{
		pErrorReqProc_->process(URI("/error?code=404"), out);
		return;
	}

	// Lo mando a donde corresponda
	itDisp->second->process(procReq, out);
}
Beispiel #5
0
			void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) {
				jsonrpc::handleRequest(response, [&](){

					HttpServerHelpers::ReturnType ret = HttpServerHelpers::preprocess(p, request, response);
					if (ret == HttpServerHelpers::RequestFinished){
						return;
					}

					std::string serviceName = request.getURI();

					std::cout << "servicename before: " << serviceName << std::endl;

					if (serviceName.find('/') == 0) {
						serviceName = serviceName.substr(1);
					}
					std::string::size_type question = serviceName.find('?');
					if (question != std::string::npos) {
						serviceName = serviceName.substr(0, question);
					}

					std::cout << "servicename after: " << serviceName << std::endl;

					for (auto i = p.getRequestHandlers().begin(); i != p.getRequestHandlers().end(); i++){
						if ((*i)->canHandle(serviceName)){
							std::cout << "SPECIAL HANDLING of " << serviceName << std::endl;
							(*i)->handle(request, response);
							return;
						}
					}

					throw Poco::FileNotFoundException("File not found");

				});
			}
	virtual void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
	{
		if (request.getURI() == "/name")
		{
			response.setContentType("application/json");
			response.send() << " { \"hanwenfang\"} ";
		}
	}
Beispiel #7
0
			void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) {

				jsonrpc::handleRequest(response, [&](){

					HttpServerHelpers::ReturnType ret = HttpServerHelpers::preprocess(p, request, response);
					if (ret == HttpServerHelpers::RequestFinished){
						return;
					}

					std::string serviceName = request.getURI();

					std::cout << "servicename before: " << serviceName << std::endl;

					if (serviceName.find('/') == 0) {
						serviceName = serviceName.substr(1);
					}
					std::string::size_type question = serviceName.find('?');
					if (question != std::string::npos) {
						serviceName = serviceName.substr(0, question);
					}

					std::cout << "servicename after: " << serviceName << std::endl;

					for (auto i = p.getRequestHandlers().begin(); i != p.getRequestHandlers().end(); i++){
						if ((*i)->canHandle(serviceName)){
							std::cout << "SPECIAL HANDLING of " << serviceName << std::endl;
							(*i)->handle(request, response);
							return;
						}
					}

					//std::cout << "service name: " << serviceName << std::endl;

					std::istream& rs = request.stream();
					std::stringstream outstr;
					Poco::StreamCopier::copyStream(rs, outstr);
					std::string rsp;
					std::string req = outstr.str();

					//std::cout << "requset: " << req << std::endl;

					//this->handlerProvider.GetHandler()

					LTRACE("Json") << "request " << req << LE;

					if (auto sHandlerProvider = handlerProvider.lock()) {
						sHandlerProvider->getHandler(serviceName)->HandleRequest(req, rsp);
					} else {
						throw Poco::Exception("Request refused - server destroyed");
					}

					LTRACE("Json") << "response " << rsp << LE;
					//std::cout << "response: " << rsp << std::endl;

					response.setContentType("application/json");
					response.sendBuffer(rsp.data(), rsp.length());
				});
			}
void DefaultRequestHandler(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
  response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
  response.setContentType(Poco::Net::MediaType("text/plain"));
  response.setKeepAlive(true);
  auto& os = response.send();

  os << "It Works! " << request.getURI() << std::flush;
}
Beispiel #9
0
void FileRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    setContentType(request, response);
    std::ostream& ostr = response.send();
    try {
        Poco::Path basedir = Poco::Util::Application::instance().config().getString("application.dir");
        basedir.append("web");
        basedir.append(request.getURI());
        Poco::FileInputStream fis(basedir.toString());
        Poco::StreamCopier::copyStream(fis, ostr);
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
    }
    catch (Poco::Exception& ex) {
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND);
        ostr << ex.displayText();
        _logger.error("Request failed: %s: %s", request.getURI(), ex.displayText());
    }

}
Beispiel #10
0
void FileRequestHandler::setContentType(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    Poco::Path path(request.getURI());
    std::string extension = Poco::toLower(path.getExtension());
    if (extension == "css") {
        response.setContentType("text/css");
    }
    else if (extension == "js") {
        response.setContentType("application/javascript");
    }
    else {
        response.setContentType("text/html");
    }
}
Beispiel #11
0
    virtual bool filterHandleRequest(
                     TestRequest type,
                     Poco::Net::HTTPServerRequest& request,
                     Poco::Net::HTTPServerResponse& response) override
    {
        if (type == UnitWSD::TestRequest::TEST_REQ_PRISONER &&
            request.getURI().find(UNIT_URI) == 0)
        {
            auto ws = std::make_shared<Poco::Net::WebSocket>(request, response);
            _fontsBroker = readFontList(ws);
            check();
            return true;
        }

        return false;
    }
void FileSystemRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
        Poco::Net::HTTPServerResponse& response)
{
    Poco::Path dataFolder(ofToDataPath("",true));
    Poco::Path documentRoot(ofToDataPath(_parent.getSettings().getDocumentRoot(),true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // doc root validity check
    if(_parent.getSettings().getRequireDocumentRootInDataFolder() &&
            (documentRootString.length() < dataFolderString.length() ||
             documentRootString.substr(0,dataFolderString.length()) != dataFolderString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Document Root is not a sub directory of the data folder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
        return;
    }

    // check path

    Poco::URI uri(request.getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if(path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if(requestPath.getFileName().empty())
    {
        requestPath.append(_parent.getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if((requestPathString.length() < documentRootString.length() ||
            requestPathString.substr(0,documentRootString.length()) != documentRootString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Requested document not inside DocumentFolder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts

    try
    {
//        ofx::Media::MediaTypeMap mediaMap;
//        Poco::Net::MediaType mediaType = mediaMap.getMediaTypeForSuffix(file.getExtension());

        std::string mediaTypeString = "application/octet-stream";
        std::string ext = file.getExtension();


        if(ext == "json")
        {
            mediaTypeString = "application/json";
        }
        else if(ext == "html")
        {
            mediaTypeString = "text/html";
        }
        else if(ext == "jpg" || ext == "jpeg")
        {
            mediaTypeString = "image/jpeg";
        }
        else if(ext == "png")
        {
            mediaTypeString = "image/png";
        }
        else if(ext == "js")
        {
            mediaTypeString = "application/javascript";
        }
        else if(ext == "css")
        {
            mediaTypeString = "text/css";
        }
        else if(ext == "xml")
        {
            mediaTypeString = "application/xml";
        }
        else if(ext == "ico")
        {
            mediaTypeString = "image/x-icon";
        }

        response.sendFile(file.getAbsolutePath(), mediaTypeString); // will throw exceptions
        return;
    }
    catch (const Poco::FileNotFoundException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
    }
    catch (const Poco::OpenFileException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
    catch (const exception& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Unknown server error: " << ex.what();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
}
Beispiel #13
0
void AppRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	// Check for the favicon.ico request, we don't have one for now,
	// so set status code to HTTP_NOT_FOUND
	if ( request.getURI().compare("/favicon.ico") == 0 )
	{
		response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		response.send();
		return;
	}

	std::string lastModifiedHeader = request.get("If-Modified-Since", "");

	Poco::URI uri(request.getURI());

	Poco::Util::Application& app = Poco::Util::Application::instance();
	std::string staticPathname = app.config().getString("mq.web.app", "");
	if ( staticPathname.empty() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error("mq.web.app property not defined. Check your configuration.");
		response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
		response.send();
		return;
	}

	Poco::Path staticPath(staticPathname);
	staticPath.makeDirectory();

	std::vector<std::string> uriPathSegments;
	uri.getPathSegments(uriPathSegments);
	std::vector<std::string>::iterator it = uriPathSegments.begin();
	it++;
	for(; it != uriPathSegments.end(); ++it)
	{
		staticPath.append(*it);
	}
	if (staticPath.isDirectory())
	{
		staticPath.append("index.html");
	}

	Poco::File staticFile(staticPath);

	Poco::Logger& logger = Poco::Logger::get("mq.web.access");
	if ( staticFile.exists() )
	{
		if ( !lastModifiedHeader.empty() )
		{
			Poco::DateTime lastModifiedDate;
			int timeZoneDifferential = 0;
			if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) )
			{
				if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() )
				{
					logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString()));
					response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
					response.send();
					return;
				}
			}
		}

		logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString()));

		std::string mimeType;
		if ( staticPath.getExtension().compare("gif") == 0 )
		{
			mimeType = "image/gif";
		}
		else if ( staticPath.getExtension().compare("css") == 0 )
		{
			mimeType = "text/css";
		}
		else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0)
		{
			mimeType = "text/html";
		}
		else if ( staticPath.getExtension().compare("js") == 0 )
		{
			mimeType = "text/javascript";
		}
		else if ( staticPath.getExtension().compare("png") == 0 )
		{
			mimeType = "image/png";
		}
		else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0)
		{
			mimeType = "image/jpeg";
		}

		try
		{
			response.sendFile(staticPath.toString(), mimeType);
		}
		catch(Poco::FileNotFoundException&)
		{
			// We can't get here normally ... but you never know :)
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, Poco::Logger::format("Can't find file $0", staticPath.toString()));
		}
		catch(Poco::OpenFileException&)
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, Poco::Logger::format("Can't open file $0", staticPath.toString()));
		}
		return;
	}

	logger.error(Poco::Logger::format("$0 : HTTP_NOT_FOUND", staticFile.path()));
	response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
	response.send();
}
	void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
	{
		//Poco::Util::Application& app = Poco::Util::Application::instance();
		//app.logger().information("Request from " + request.clientAddress().toString());
        std::cout << "Request from " << request.clientAddress().toString() << std::endl;

        MyPartHandler partHandler;
        Poco::Net::HTMLForm form(request, request.stream(), partHandler);

        std::string spinToken, sceneString, nodeString, args;
        std::istringstream pathstream(request.getURI());
        pathstream.get(); // ignore leading slash
        getline(pathstream, spinToken, '/');
        getline(pathstream, sceneString, '/');
        getline(pathstream, nodeString, '?');

        if (sceneString.empty()) sceneString = "default";
        //if (nodeString.empty()) nodeString = "shp";
        if (form.empty()) args = "createNode shp ShapeNode";
        else args = form["args"];

        response.setChunkedTransferEncoding(true);
        response.setContentType("text/html");

        std::ostream& ostr = response.send();

        ostr <<
        "<html>\n"
        "<head>\n"
        "<title>SPIN Web Service</title>\n"
        "</head>\n"
        "<body>\n"
        "<h1>SPIN Web Service</h1>\n"
        "<h3>Enter a SPIN command in the form below:</h3>\n"
        "<table><tr><td nowrap=\"nowrap\">\n"
        "<form name=\"urlForm\" method=\"GET\" action=\"null\">\n"
        "/SPIN/"
        "<input type=\"text\" name=\"sceneID\" value=\"" << sceneString << "\" size=\"10\">\n"
        "/<input type=\"text\" name=\"nodeID\" value=\"" << nodeString << "\" size=\"10\">"
        "</form></td>\n"
        "<td nowrap=\"nowrap\">\n"
        "<form name=\"spinform\" method=\"GET\" action=\"null\">\n"
        "<input type=\"text\" name=\"args\" value=\"" << args << "\" size=\"20\">\n"
        "<input type=\"submit\" value=\"GO\" onclick=\"this.form.action='/SPIN/'+document.forms['urlForm']['sceneID'].value+'/'+document.forms['urlForm']['nodeID'].value\">\n"
        "</form>\n"
        "</tr></table>\n"
        "<p>(NOTE: you can send scene messages by leaving the node name blank)</p>\n"
        "\n";
        /*
        ostr <<
            "<html>\n"
            "<head>\n"
            "<title>SPIN Web Server Sample</title>\n"
            "</head>\n"
            "<body>\n"
            "<h1>SPIN Web Server Sample</h1>\n"
            "<h2>Tests:</h2>\n"
            "<form name=\"spinform\" method=\"GET\" action=\"null\">\n"
            "/SPIN/default/"
            "<input type=\"text\" name=\"nodeID\" value=\"shp\" size=\"15\">"
            "&nbsp;&nbsp;&nbsp;"
            "<input type=\"text\" name=\"method\" value=\"rotate\" size=\"15\">"
            " move<input type=\"text\" name=\"x\" value=\"0\" size=\"3\">"
            " <input type=\"text\" name=\"y\" value=\"0\" size=\"3\">"
            " <input type=\"text\" name=\"z\" value=\"10\" size=\"3\">\n"
            " <input type=\"submit\" value=\"GO\" onclick=\"this.form.action='/SPIN/default/'+this.form.nodeID.value\">\n"
            "</form>\n"
            "\n";
        ostr <<
            "<html>\n"
            "<head>\n"
            "<title>SPIN Web Server Sample</title>\n"
            "</head>\n"
            "<body>\n"
            "<h1>SPIN Web Server Sample</h1>\n"
            "<h2>GET Form</h2>\n"
            "<form method=\"GET\" action=\"/form\">\n"
            "<input type=\"text\" name=\"text\" size=\"31\">\n"
            "<input type=\"submit\" value=\"GET\">\n"
            "</form>\n"
            "<h2>POST Form</h2>\n"
            "<form method=\"POST\" action=\"/form\">\n"
            "<input type=\"text\" name=\"text\" size=\"31\">\n"
            "<input type=\"submit\" value=\"POST\">\n"
            "</form>\n"
            "<h2>File Upload</h2>\n"
            "<form method=\"POST\" action=\"/form\" enctype=\"multipart/form-data\">\n"
            "<input type=\"file\" name=\"file\" size=\"31\"> \n"
            "<input type=\"submit\" value=\"Upload\">\n"
            "</form>\n";
            */

        ostr << "<h2>Result</h2><p>\n";
        ostr << "Method: " << request.getMethod() << "<br>\n";
        ostr << "URI: " << request.getURI() << "<br>\n";
        Poco::Net::NameValueCollection::ConstIterator it = request.begin();
        Poco::Net::NameValueCollection::ConstIterator end = request.end();
        for (; it != end; ++it)
        {
            ostr << it->first << ": " << it->second << "<br>\n";
        }
        ostr << "</p>";
        /*
        if (!form.empty())
        {
            ostr << "<h2>Result</h2><p>\n";
            it = form.begin();
            end = form.end();
            for (; it != end; ++it)
            {
                ostr << it->first << ": " << it->second << "<br>\n";
            }
            ostr << "</p>";
        }
        */

        // --------parse

        introspect_invoke(request.getURI(), form);

        // ---------------

        if (!partHandler.name().empty())
        {
            ostr << "<h2>Upload</h2><p>\n";
            ostr << "Name: " << partHandler.name() << "<br>\n";
            ostr << "File Name: " << partHandler.fileName() << "<br>\n";
            ostr << "Type: " << partHandler.contentType() << "<br>\n";
            ostr << "Size: " << partHandler.length() << "<br>\n";
            ostr << "</p>";
        }
        ostr << "</body>\n";
    }
void FileSystemRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
                                           Poco::Net::HTTPServerResponse& response)
{
    Poco::Path dataFolder(ofToDataPath("", true));
    Poco::Path documentRoot(ofToDataPath(_parent.getSettings().getDocumentRoot(), true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // doc root validity check
    if(_parent.getSettings().getRequireDocumentRootInDataFolder() &&
       (documentRootString.length() < dataFolderString.length() ||
        documentRootString.substr(0,dataFolderString.length()) != dataFolderString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Document Root is not a sub directory of the data folder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
        return;
    }

    // check path

    Poco::URI uri(request.getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if(path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if(requestPath.getFileName().empty())
    {
        requestPath.append(_parent.getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if((requestPathString.length() < documentRootString.length() ||
        requestPathString.substr(0,documentRootString.length()) != documentRootString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Requested document not inside DocumentFolder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts
    std::string mediaTypeString = Media::MediaTypeMap::getDefault()->getMediaTypeForPath(file.path()).toString();

    try
    {
        // TODO: this is where we would begin to work honoring
        /// Accept-Encoding:gzip, deflate, sdch
        response.sendFile(file.getAbsolutePath(), mediaTypeString);
        return;
    }
    catch (const Poco::FileNotFoundException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
    }
    catch (const Poco::OpenFileException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
    catch (const exception& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Unknown server error: " << ex.what();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
}
Beispiel #16
0
void ShowFilePage::handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
{
	m_log->trace("ShowFilePage::handleRequest from "+request.clientAddress().toString());
	m_log->trace("ShowFilePage::handleRequest ContentType="+request.getContentType());
	m_log->trace("ShowFilePage::handleRequest TransferEncoding="+request.getTransferEncoding());
	m_log->trace("ShowFilePage::handleRequest URI="+request.getURI());

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

	CreateQueryVarMap(request,queryvars);

	std::string content="";
	if(queryvars.find("file")!=queryvars.end() && m_filewhitelist.find((*queryvars.find("file")).second.GetData())!=m_filewhitelist.end())
	{
		try
		{
			response.sendFile(global::basepath+(*queryvars.find("file")).second.GetData(),m_filewhitelist[(*queryvars.find("file")).second.GetData()]);
		}
		catch(Poco::FileNotFoundException &fnf)
		{
			m_log->error("ShowFilePage::handleRequest caught FileNotFound exception - "+fnf.message());
		}
		catch(Poco::OpenFileException &of)
		{
			m_log->error("ShowFilePage::handleRequest caught OpenFile exception - "+of.message());
		}
		catch(...)
		{
			m_log->error("ShowFilePage::handleRequest caught other exception");
		}
	}
	else if(request.getURI().size()>0 && request.getURI()[0]=='/' && m_filewhitelist.find(request.getURI().substr(1))!=m_filewhitelist.end())
	{
		try
		{
			response.sendFile(global::basepath+request.getURI().substr(1),m_filewhitelist[request.getURI().substr(1)]);
		}
		catch(Poco::FileNotFoundException &fnf)
		{
			m_log->error("ShowFilePage::handleRequest caught FileNotFound exception - "+fnf.message());
		}
		catch(Poco::OpenFileException &of)
		{
			m_log->error("ShowFilePage::handleRequest caught OpenFile exception - "+of.message());
		}
		catch(...)
		{
			m_log->error("ShowFilePage::handleRequest caught other exception");
		}		
	}
	else if(request.getURI().size()>0 && m_filewhitelist.find(request.getURI())!=m_filewhitelist.end())
	{
		try
		{
			response.sendFile(global::basepath+request.getURI(),m_filewhitelist[request.getURI()]);
		}
		catch(Poco::FileNotFoundException &fnf)
		{
			m_log->error("ShowFilePage::handleRequest caught FileNotFound exception - "+fnf.message());
		}
		catch(Poco::OpenFileException &of)
		{
			m_log->error("ShowFilePage::handleRequest caught OpenFile exception - "+of.message());
		}
		catch(...)
		{
			m_log->error("ShowFilePage::handleRequest caught other exception");
		}	
	}

}
Beispiel #17
0
void HttpPerf::handleRequest(Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp)
{
    URI uri(req.getURI());
    // std::string book = getParam(uri.getQueryParameters(), HttpParam::Book);
    send(resp, HTTPResponse::HTTP_BAD_REQUEST, "OK");
}
Beispiel #18
0
void ODBCHandler::handleRequest(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response)
{
    Poco::Net::HTMLForm params(request, request.stream());
    LOG_TRACE(log, "Request URI: " + request.getURI());

    auto process_error = [&response, this](const std::string & message)
    {
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        if (!response.sent())
            response.send() << message << std::endl;
        LOG_WARNING(log, message);
    };

    if (!params.has("query"))
    {
        process_error("No 'query' in request body");
        return;
    }

    if (!params.has("columns"))
    {
        process_error("No 'columns' in request URL");
        return;
    }

    if (!params.has("connection_string"))
    {
        process_error("No 'connection_string' in request URL");
        return;
    }

    UInt64 max_block_size = DEFAULT_BLOCK_SIZE;
    if (params.has("max_block_size"))
    {
        std::string max_block_size_str = params.get("max_block_size", "");
        if (max_block_size_str.empty())
        {
            process_error("Empty max_block_size specified");
            return;
        }
        max_block_size = parse<size_t>(max_block_size_str);
    }

    std::string columns = params.get("columns");
    std::unique_ptr<Block> sample_block;
    try
    {
        sample_block = parseColumns(std::move(columns));
    }
    catch (const Exception & ex)
    {
        process_error("Invalid 'columns' parameter in request body '" + ex.message() + "'");
        LOG_WARNING(log, ex.getStackTrace().toString());
        return;
    }

    std::string format = params.get("format", "RowBinary");
    std::string query = params.get("query");
    LOG_TRACE(log, "Query: " << query);

    std::string connection_string = params.get("connection_string");
    LOG_TRACE(log, "Connection string: '" << connection_string << "'");

    WriteBufferFromHTTPServerResponse out(request, response, keep_alive_timeout);
    try
    {
        BlockOutputStreamPtr writer = FormatFactory::instance().getOutput(format, out, *sample_block, *context);
        auto pool = getPool(connection_string);
        ODBCBlockInputStream inp(pool->get(), query, *sample_block, max_block_size);
        copyData(inp, *writer);
    }
    catch (...)
    {
        auto message = getCurrentExceptionMessage(true);
        response.setStatusAndReason(
            Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); // can't call process_error, bacause of too soon response sending
        writeStringBinary(message, out);
        tryLogCurrentException(log);
    }
}
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");
}
Beispiel #20
0
	RouteMatch(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
		: m_request(request), m_response(response), m_uri(request.getURI())
	{
	}
Beispiel #21
0
void HTTPHandler::processQuery(
    Poco::Net::HTTPServerRequest & request,
    HTMLForm & params,
    Poco::Net::HTTPServerResponse & response,
    Output & used_output)
{
    Context context = server.context();
    context.setGlobalContext(server.context());

    CurrentThread::QueryScope query_scope(context);

    LOG_TRACE(log, "Request URI: " << request.getURI());

    std::istream & istr = request.stream();

    /// Part of the query can be passed in the 'query' parameter and the rest in the request body
    /// (http method need not necessarily be POST). In this case the entire query consists of the
    /// contents of the 'query' parameter, a line break and the request body.
    std::string query_param = params.get("query", "");
    if (!query_param.empty())
        query_param += '\n';

    /// The user and password can be passed by headers (similar to X-Auth-*),
    /// which is used by load balancers to pass authentication information.
    std::string user = request.get("X-ClickHouse-User", "");
    std::string password = request.get("X-ClickHouse-Key", "");
    std::string quota_key = request.get("X-ClickHouse-Quota", "");

    if (user.empty() && password.empty() && quota_key.empty())
    {
        /// User name and password can be passed using query parameters
        /// or using HTTP Basic auth (both methods are insecure).
        if (request.hasCredentials())
        {
            Poco::Net::HTTPBasicCredentials credentials(request);

            user = credentials.getUsername();
            password = credentials.getPassword();
        }
        else
        {
            user = params.get("user", "default");
            password = params.get("password", "");
        }

        quota_key = params.get("quota_key", "");
    }
    else
    {
        /// It is prohibited to mix different authorization schemes.
        if (request.hasCredentials()
            || params.has("user")
            || params.has("password")
            || params.has("quota_key"))
        {
            throw Exception("Invalid authentication: it is not allowed to use X-ClickHouse HTTP headers and other authentication methods simultaneously", ErrorCodes::REQUIRED_PASSWORD);
        }
    }

    std::string query_id = params.get("query_id", "");
    context.setUser(user, password, request.clientAddress(), quota_key);
    context.setCurrentQueryId(query_id);

    /// The user could specify session identifier and session timeout.
    /// It allows to modify settings, create temporary tables and reuse them in subsequent requests.

    std::shared_ptr<Context> session;
    String session_id;
    std::chrono::steady_clock::duration session_timeout;
    bool session_is_set = params.has("session_id");
    const auto & config = server.config();

    if (session_is_set)
    {
        session_id = params.get("session_id");
        session_timeout = parseSessionTimeout(config, params);
        std::string session_check = params.get("session_check", "");

        session = context.acquireSession(session_id, session_timeout, session_check == "1");

        context = *session;
        context.setSessionContext(*session);
    }

    SCOPE_EXIT({
        if (session_is_set)
            session->releaseSession(session_id, session_timeout);
    });