Beispiel #1
0
void BaseSessionStore::destroySession(Poco::Net::HTTPServerRequest& request,
                                      Poco::Net::HTTPServerResponse& response)
{
    // Get the cookies from the client.
    Poco::Net::NameValueCollection cookies;

    // Get the cookies
    request.getCookies(cookies);

    // Try to find a cookie with our session key name.
    Poco::Net::NameValueCollection::ConstIterator cookieIter = cookies.begin();

    while (cookieIter != cookies.end())
    {
        if (0 == cookieIter->first.compare(_sessionKeyName))
        {
            // Destroy the session data.
            destroySession(cookieIter->second);

            // Invalidate the cookies.
            Poco::Net::HTTPCookie cookie(_sessionKeyName, cookieIter->second);

            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }

        ++cookieIter;
    }
}
Beispiel #2
0
Poco::Net::NameValueCollection HTTPUtils::splitAndURLDecode(const std::string& encoded)
{
    // TODO use code from Poco::Net::HTMLForm

    Poco::Net::NameValueCollection nvc;

    auto arguments = ofSplitString(encoded, "&", true);

    for (const auto& argument: arguments)
    {
        std::vector<std::string> tokens = ofSplitString(argument, "=", true);

        if (tokens.size() > 0)
        {
            std::string key;
            std::string value;

            Poco::URI::decode(tokens[0], key);

            if (tokens.size() > 1)
            {
                Poco::URI::decode(tokens[1], value);
            }

            nvc.add(key, value);
        }
    }

    return nvc;
}
Beispiel #3
0
    TestResult testWebSocketWithCookie()
    {
        HTTPResponse response;
        HTTPRequest request(HTTPRequest::HTTP_GET, "/lool/adminws/");
        std::unique_ptr<HTTPClientSession> session(helpers::createSession(_uri));

        // set cookie
        assert(_jwtCookie != "");
        HTTPCookie cookie("jwt", _jwtCookie);
        Poco::Net::NameValueCollection nvc;
        nvc.add("jwt", _jwtCookie);
        request.setCookies(nvc);

        bool authorized = true;
        try
        {
            _adminWs = std::make_shared<Poco::Net::WebSocket>(*session, request, response);
        }
        catch (const Poco::Net::WebSocketException& exc)
        {
            Log::info() << "Admin websocket: Not authorized " << Log::end;
            authorized = false;
        }

        TestResult res = TestResult::TEST_FAILED;
        if (authorized)
            res = TestResult::TEST_OK;

        Log::info(std::string("testWebSocketWithCookie: ") + (res == TestResult::TEST_OK ? "OK" : "FAIL"));
        return res;
    }
Beispiel #4
0
void MultiPartParser::handlePart(const Poco::Net::MessageHeader &header, std::istream &stream)
{
	QueryVar qv;
	std::string data;

	if(header.has("Content-Disposition"))
	{
		std::string disp;
		Poco::Net::NameValueCollection nvc;
		Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"],disp,nvc);
		qv.SetName(nvc.get("name",""));
		qv.SetFileName(nvc.get("filename",""));
		if(header.has("Content-Type"))
		{
			qv.SetContentType(header["Content-Type"]);
		}
		else
		{
			qv.SetContentType("");
		}

		Poco::StreamCopier::copyToString(stream,data);
		qv.SetData(data);

		m_vars[qv.GetName()]=qv;
	}
}
Beispiel #5
0
// Converts the vector of HTTPCookie objects into a NameValueCollection
Poco::Net::NameValueCollection RemoteJobManager::getCookies() {
  Poco::Net::NameValueCollection nvc;
  std::vector<Poco::Net::HTTPCookie>::const_iterator it = m_cookies.begin();
  while (it != m_cookies.end()) {
    nvc.add((*it).getName(), (*it).getValue());
    ++it;
  }
  return nvc;
}
Beispiel #6
0
AbstractSession& BaseSessionStore::getSession(Poco::Net::HTTPServerRequest& request,
                                              Poco::Net::HTTPServerResponse& response)
{
    // Get the cookies from the client.
    Poco::Net::NameValueCollection cookies;

    // Get the cookies
    request.getCookies(cookies);

    // Try to find a cookie with our session key name.
    Poco::Net::NameValueCollection::ConstIterator cookieIter = cookies.begin();

    std::string sessionId;

    while (cookieIter != cookies.end())
    {
        if (0 == cookieIter->first.compare(_sessionKeyName))
        {
            if (sessionId.empty())
            {
                sessionId = cookieIter->second;
            }
            else
            {
                Poco::Net::HTTPCookie cookie(_sessionKeyName);
                cookie.setMaxAge(0); // Invalidate the cookie.
                response.addCookie(cookie);
            }
        }

        ++cookieIter;
    }

    if (hasSession(sessionId))
    {
        return getSession(sessionId);
    }
    else
    {
        // Create a new sesssion and return a reference.
        AbstractSession& session = createSession();

        // Create a cookie with the session id.
        Poco::Net::HTTPCookie cookie(_sessionKeyName, session.getId());

        // Send our cookie with the response.
        response.addCookie(cookie);

        return session;
    }
}
	void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream)
	{
		_type = header.get("Content-Type", "(unspecified)");
		if (header.has("Content-Disposition"))
		{
			std::string disp;
			Poco::Net::NameValueCollection params;
			Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, params);
			_name = params.get("name", "(unnamed)");
			_fileName = params.get("filename", "(unnamed)");
		}

		Poco::CountingInputStream istr(stream);
		Poco::NullOutputStream ostr;
		Poco::StreamCopier::copyStream(istr, ostr);
		_length = istr.chars();
	}
Beispiel #8
0
std::string HTTPUtils::makeQueryString(const Poco::Net::NameValueCollection& query)
{
    std::stringstream ostr;

    Poco::Net::NameValueCollection::ConstIterator it = query.begin();

    while (it != query.end())
    {
        if (it != query.begin())
            ostr << "&";

        std::string name;
        Poco::URI::encode(it->first, "=&+;", name);
        std::string value;
        Poco::URI::encode(it->second, "=&+;", value);
        ostr << name << "=" << value;
        ++it;
    }

    return ostr.str();
}
Beispiel #9
0
Poco::Net::NameValueCollection HTTPUtils::splitTextPlainPost(const std::string& textPlain)
{
    Poco::Net::NameValueCollection nvc;
    std::string result;
    std::stringstream ss;

    ss << textPlain;

    while (std::getline(ss, result))
    {
        std::size_t pos = result.find("=");

        if (pos != std::string::npos)
        {
            std::string key = result.substr(0, pos);
            std::string value = result.substr(pos + 1);
            nvc.add(key, value);
        }
    }

    return nvc;
}
void PostRouteFileHandler::handlePart(const Poco::Net::MessageHeader& header,
                                      std::istream& stream)
{
    if(header.has("Content-Type"))
    {
        std::string contentType = header["Content-Type"];

        if(!_parent.getSettings().getValidContentTypes().empty() && !isContentTypeValid(contentType))
        {
            ofLogError("PostRouteFileHandler::handlePart") << "Invalid content type: " << contentType;
            return; // reject
        }
    }
    else
    {
        ofLogError("PostRouteFileHandler::handlePart") << "No Content-Type header.";
        return;
    }


    // is this an uploaded file?
    if(header.has("Content-Disposition"))// && header.has("form-data"))
    {
        std::string contentDisposition = header["Content-Disposition"];

        Poco::Net::NameValueCollection parameters;

        Poco::Net::MessageHeader::splitParameters(contentDisposition.begin(),
                                                  contentDisposition.end(),
                                                  parameters);

        std::string formFileName = parameters.get("filename", "");
        std::string formFieldName = parameters.get("name", "");

        if(!formFileName.empty())
        {
            try
            {
                std::stringstream ss;

                ss << _parent.getSettings().getUploadFolder();
                ss << "/";
                ss << Poco::UUIDGenerator::defaultGenerator().createOne().toString();
                ss << ".";
                ss << Poco::Path(formFileName).getExtension();

                std::string newFilename = ofToDataPath(ss.str(), true);

                ofFile file(newFilename, ofFile::WriteOnly);

                Poco::Net::MediaType contentType(header["Content-Type"]);

                PostUploadEventArgs args(_sessionUUID,
                                         _request,
                                         _formUUID,
                                         formFieldName,
                                         formFileName,
                                         newFilename,
                                         contentType,
                                         0,
                                         PostUploadEventArgs::UPLOAD_STARTING);

                ofNotifyEvent(_parent.events.onHTTPUploadEvent, args, &_parent);

                ofLogVerbose("PostRouteFileHandler::handlePart") << "Writing file to absolute path : " << file.getAbsolutePath();

                // The section below is from StreamCopier::copyStream,
                // and might be used for upload progress feedback

                Poco::Buffer<char> buffer(_parent.getSettings().getWriteBufferSize());

                std::streamsize sz = 0;

                stream.read(buffer.begin(), _parent.getSettings().getWriteBufferSize());

                std::streamsize n = stream.gcount();

                while (n > 0)
                {
                    if (sz > _parent.getSettings().getMaximumFileUploadSize())
                    {
                        ofLogError("PostRouteFileHandler::handlePart") << "File upload size exceeded.  Removing file.";
                        file.close();
                        ofFile::removeFile(newFilename, false);

                        return;
                    }

                    sz += n;
                    
                    file.write(buffer.begin(), n);

                    if (stream && file)
                    {
                        stream.read(buffer.begin(),
                                    _parent.getSettings().getWriteBufferSize());
                        
                        n = stream.gcount();
                    }
                    else
                    {
                        n = 0;
                    }

                    PostUploadEventArgs args(_sessionUUID,
                                             _request,
                                             _formUUID,
                                             formFieldName,
                                             formFileName,
                                             newFilename,
                                             contentType,
                                             sz,
                                             PostUploadEventArgs::UPLOAD_PROGRESS);

                    ofNotifyEvent(_parent.events.onHTTPUploadEvent,
                                  args,
                                  &_parent);
                }

                file.close();

                PostUploadEventArgs finishedArgs(_sessionUUID,
                                                 _request,
                                                 _formUUID,
                                                 formFieldName,
                                                 formFileName,
                                                 newFilename,
                                                 contentType,
                                                 sz,
                                                 PostUploadEventArgs::UPLOAD_FINISHED);

                ofNotifyEvent(_parent.events.onHTTPUploadEvent,
                              finishedArgs,
                              &_parent);

            }
            catch (const Poco::Exception& exc)
            {
                ofLogError("PostRouteFileHandler::handlePart") << exc.displayText();
            }
            catch (const std::exception& exc)
            {
                ofLogError("PostRouteFileHandler::handlePart") << exc.what();
            }
            catch ( ... )
            {
                ofLogError("PostRouteFileHandler::handlePart") << "Uncaught thread exception: Unknown exception.";
            }
        }
        else
        {
            ofLogError("PostRouteFileHandler::handlePart") << "No filename in header.";
        }
    }
}