Ejemplo n.º 1
0
	void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
	{
		response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);

		if (request.getContentType() == "application/soap+xml")
		{
      assert(false);
      //std::string req(std::istreambuf_iterator<char>(request.stream()), std::istreambuf_iterator<char>());

			//tinyxml2::XMLDocument reqDoc;
			//reqDoc.Parse(req.c_str());

			//tinyxml2::XMLDocument respDoc;
			//respDoc.LoadFile(m_wsdl.c_str());

			//cout << "Sending wsdl via soap" << endl << flush;

			//m_outbuf = "";
			//m_soapProtocol.SendResponse(reqDoc, respDoc, respDoc.FirstChildElement(), "http://www.w3.org/2005/08/addressing/anonymous");
			//response.sendBuffer(m_outbuf.c_str(), m_outbuf.size());

			//m_outbuf = "";
		}
		else
		{
			cout << "Sending wsdl via http" << endl << flush;
			response.sendFile(m_wsdl.c_str(), "text/xml");
		}		
	}
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;
		}
	}
}
Ejemplo n.º 3
0
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;
}
Ejemplo n.º 4
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;
}
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
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();
}
Ejemplo n.º 7
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);
    }
}
Ejemplo n.º 8
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();
		}
Ejemplo n.º 9
0
void ReplicasStatusHandler::handleRequest(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response)
{
	try
	{
		HTMLForm params(request);

		/// Даже в случае, когда отставание небольшое, выводить подробную информацию об отставании.
		bool verbose = params.get("verbose", "") == "1";

		const MergeTreeSettings & settings = context.getMergeTreeSettings();

		bool ok = true;
		std::stringstream message;

		auto databases = context.getDatabases();

		/// Перебираем все реплицируемые таблицы.
		for (const auto & db : databases)
		{
			for (auto iterator = db.second->getIterator(); iterator->isValid(); iterator->next())
			{
				auto & table = iterator->table();
				StorageReplicatedMergeTree * table_replicated = typeid_cast<StorageReplicatedMergeTree *>(table.get());

				if (!table_replicated)
					continue;

				time_t absolute_delay = 0;
				time_t relative_delay = 0;

				table_replicated->getReplicaDelays(absolute_delay, relative_delay);

				if ((settings.min_absolute_delay_to_close && absolute_delay >= static_cast<time_t>(settings.min_absolute_delay_to_close))
					|| (settings.min_relative_delay_to_close && relative_delay >= static_cast<time_t>(settings.min_relative_delay_to_close)))
					ok = false;

				message << backQuoteIfNeed(db.first) << "." << backQuoteIfNeed(iterator->name())
					<< ":\tAbsolute delay: " << absolute_delay << ". Relative delay: " << relative_delay << ".\n";
			}
		}

		setResponseDefaultHeaders(response);

		if (ok && !verbose)
		{
			const char * data = "Ok.\n";
			response.sendBuffer(data, strlen(data));
		}
		else
		{
			response.send() << message.rdbuf();
		}
	}
	catch (...)
	{
		tryLogCurrentException("ReplicasStatusHandler");

		try
		{
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);

			if (!response.sent())
			{
				/// Ещё ничего не отправляли, и даже не знаем, нужно ли сжимать ответ.
				response.send() << getCurrentExceptionMessage(false) << std::endl;
			}
		}
		catch (...)
		{
			LOG_ERROR((&Logger::get("ReplicasStatusHandler")), "Cannot send exception to client");
		}
	}
}
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);
    }
}
Ejemplo n.º 11
0
void RESTHandler::error_black_list(Poco::Net::HTTPServerResponse &response) {
    response.setStatusAndReason(Poco::Net::HTTPServerResponse::HTTP_NOT_FOUND, "Resource in blacklist");
    response.send() << "Requested resource is in black-list" << std::flush;
}
Ejemplo n.º 12
0
void RESTHandler::error_timeout(Poco::Net::HTTPServerResponse &response) {
    response.setStatusAndReason(Poco::Net::HTTPServerResponse::HTTP_REQUEST_TIMEOUT, "External system timeout");
    response.send() << "External system request timeout" << std::flush;
}
Ejemplo n.º 13
0
void RESTHandler::error_parse(Poco::Net::HTTPServerResponse &response) {
    response.setStatusAndReason(Poco::Net::HTTPServerResponse::HTTP_BAD_REQUEST, "Parse failed");
    response.send() << "Invalid JSON arguments" << std::flush;
}
Ejemplo n.º 14
0
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);
    }
}