Example #1
0
    void assertPutFileRequest(const Poco::Net::HTTPRequest& request) override
    {
        if (_savingPhase == SavingPhase::Unmodified)
        {
            // the document is not modified
            CPPUNIT_ASSERT_EQUAL(std::string("false"), request.get("X-LOOL-WOPI-IsModifiedByUser"));

            // but the save action is an explicit user's request
            CPPUNIT_ASSERT_EQUAL(std::string("false"), request.get("X-LOOL-WOPI-IsAutosave"));

            _finishedSaveUnmodified = true;
        }
        else if (_savingPhase == SavingPhase::Modified)
        {
            // the document is modified
            CPPUNIT_ASSERT_EQUAL(std::string("true"), request.get("X-LOOL-WOPI-IsModifiedByUser"));

            // and this test fakes that it's an autosave
            CPPUNIT_ASSERT_EQUAL(std::string("true"), request.get("X-LOOL-WOPI-IsAutosave"));

            _finishedSaveModified = true;
        }

        if (_finishedSaveUnmodified && _finishedSaveModified)
            exitTest(TestResult::Ok);
    }
Example #2
0
std::istream &RemoteJobManager::httpGet(const std::string &path,
                                        const std::string &query_str,
                                        const std::string &username,
                                        const std::string &password) {
  Poco::Net::HTTPRequest req;
  initGetRequest(req, path, query_str);

  if (username.length() > 0) {
    // Set the Authorization header (base64 encoded)
    std::ostringstream encodedAuth;
    Poco::Base64Encoder encoder(encodedAuth);
    encoder << username << ":" << password;
    encoder.close();
    req.setCredentials("Basic", encodedAuth.str());
  }

  m_session->sendRequest(req);

  std::istream &respStream = m_session->receiveResponse(m_response);

  // For as yet unknown reasons, we don't always get a session cookie back from
  // the
  // server. In that case, we don't want to overwrite the cookie we're currently
  // using...
  // Note: This won't work properly if we ever use cookies other than a
  // session cookie.
  std::vector<Poco::Net::HTTPCookie> newCookies;
  m_response.getCookies(newCookies);
  if (!newCookies.empty()) {
    m_cookies = newCookies;
  }

  return respStream;
}
Example #3
0
void HttpAssetTransfer::SendHttpGetAssetRequest(const std::string &resource_uri)
{
    if (http_session_.connected())
    {
        http_session_.abort();
        http_session_.detachSocket();
    }

    received_count_ = 0;

    Poco::URI uri(resource_uri);
    std::string path(uri.getPathAndQuery());
    if (path.empty())
        path = "/";

    http_session_.setHost(uri.getHost());
    http_session_.setPort(uri.getPort());
    Poco::Timespan time_out(HTTP_TIMEOUT_MS*1000);
    http_session_.setTimeout(time_out);

    Poco::Net::HTTPRequest request;
    request.setMethod(Poco::Net::HTTPRequest::HTTP_GET);
    request.setURI(path);
    request.setVersion(Poco::Net::HTTPMessage::HTTP_1_1);

    try
    {
        http_session_.sendRequest(request);
        std::istream &s = http_session_.receiveResponse(http_response_);
        Poco::Net::HTTPResponse::HTTPStatus status = http_response_.getStatus();
        switch (status)
        {
        case Poco::Net::HTTPResponse::HTTP_OK:
            response_stream_ = &s;
            response_size_ = http_response_.getContentLength();
            break;

        default:
            std::string reason = http_response_.getReasonForStatus(status);
            std::stringstream error;
            error << "Http GET failed for: ";
            error << resource_uri << std::endl;
            error << "Reason: " << reason;
            AssetModule::LogError(error.str());
            failed_ = true;
            return;
        }
    }
    catch (Poco::Exception e)
    {
        std::stringstream error;
        error << "Http GET failed for: ";
        error << resource_uri << std::endl;
        error << "Reason: " << e.displayText();
        AssetModule::LogError(error.str());
        failed_ = true;
        return;
    }
}
Example #4
0
bool doRequest(Poco::Net::HTTPClientSession & session, string requestBody, Poco::Net::HTTPRequest & request, Poco::Net::HTTPResponse & response)
{
	session.setKeepAlive(true);
	request.setKeepAlive(true);
	request.setContentType("application/x-www-form-urlencoded");
	request.setContentLength(requestBody.length());

	session.sendRequest(request) << requestBody;
	std::istream& rs = session.receiveResponse(response);
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;
	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		
		//std::ofstream ofs("Poco_banner.jpg", std::fstream::binary);
		//StreamCopier::copyStream(rs, ofs);
		// Print to standard output
		cout << "RECEIVED:" << endl;
		//std::copy(std::istream_iterator<char>(rs), std::istream_iterator<char>(), std::ostream_iterator<char>(std::cout));
		string received = "";
		string temp;
		//rec << rs.rdbuf();
		
		while (std::getline(rs, temp))
		{
			received += temp + "\n";
		}

		cout << received << endl;
		return true;
	}
	else
	{
		//it went wrong ?
		return false;
	}
}
Example #5
0
void FileServerRequestHandler::sendError(int errorCode, const Poco::Net::HTTPRequest& request,
                                         const std::shared_ptr<StreamSocket>& socket,
                                         const std::string& shortMessage, const std::string& longMessage,
                                         const std::string& extraHeader)
{
    Poco::URI requestUri(request.getURI());
    const std::string& path = requestUri.getPath();
    std::ostringstream oss;
    oss << "HTTP/1.1 " << errorCode << "\r\n"
        << "Content-Type: text/html charset=UTF-8\r\n"
        << "Date: " << Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
        << "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
        << extraHeader
        << "\r\n";
    if (!shortMessage.empty())
    {
        oss << "<h1>Error: " << shortMessage << "</h1>"
            << "<p>" << longMessage << " " << path << "</p>"
            << "<p>Please contact your system administrator.</p>";
    }
    socket->send(oss.str());
}
Example #6
0
std::istream &RemoteJobManager::httpPost(const std::string &path,
                                         const PostDataMap &postData,
                                         const PostDataMap &fileData,
                                         const std::string &username,
                                         const std::string &password) {
  Poco::Net::HTTPRequest req;
  initPostRequest(req, path);

  if (username.length() > 0) {
    // Set the Authorization header (base64 encoded)
    std::ostringstream encodedAuth;
    Poco::Base64Encoder encoder(encodedAuth);
    encoder << username << ":" << password;
    encoder.close();
    req.setCredentials("Basic", encodedAuth.str());
  }

  // We have to do a POST with multipart MIME encoding. MIME is rather picky
  // about
  // how the parts are delimited. See RFC 2045 & 2046 for details.

  char httpLineEnd[3] = {0x0d, 0x0a,
                         0x00}; // HTTP uses CRLF for its line endings

  // boundary can be almost anything (again, see RFC 2046). The important part
  // is that it
  // cannot appear anywhere in the actual data
  std::string boundary = "112233MantidHTTPBoundary44556677";
  std::string boundaryLine = "--" + boundary + httpLineEnd;
  std::string finalBoundaryLine = "--" + boundary + "--" + httpLineEnd;

  req.setContentType("multipart/form-data; boundary=" + boundary);

  // Need to be able to specify the content length, so build up the post body
  // here.
  std::ostringstream postBody;
  auto it = postData.cbegin();
  while (it != postData.cend()) {
    postBody << boundaryLine;
    postBody << "Content-Disposition: form-data; name=\"" << (*it).first
             << "\"";
    postBody << httpLineEnd << httpLineEnd;
    postBody << (*it).second;
    postBody << httpLineEnd;
    ++it;
  }

  // file data is treated the same as post data, except that we set the filename
  // field
  // in the Content-Disposition header and add the Content-Type header
  it = fileData.begin();
  while (it != fileData.end()) {
    postBody << boundaryLine;
    postBody << "Content-Disposition: form-data; name=\"" << (*it).first
             << "\"; filename=\"" << (*it).first << "\"";
    postBody << httpLineEnd;
    postBody << "Content-Type: application/octet-stream";
    postBody << httpLineEnd << httpLineEnd;
    postBody << (*it).second;
    postBody << httpLineEnd;
    ++it;
  }

  postBody << finalBoundaryLine;

  req.setContentLength(static_cast<int>(postBody.str().size()));

  std::ostream &postStream = m_session->sendRequest(req);

  // upload the actual HTTP body
  postStream << postBody.str() << std::flush;

  std::istream &respStream = m_session->receiveResponse(m_response);

  // For as yet unknown reasons, we don't always get a session cookie back from
  // the
  // server. In that case, we don't want to overwrite the cookie we're currently
  // using...
  // Note: This won't work properly if we ever use cookies other than a
  // session cookie.
  std::vector<Poco::Net::HTTPCookie> newCookies;
  m_response.getCookies(newCookies);
  if (!newCookies.empty()) {
    m_cookies = newCookies;
  }

  return respStream;
}
Example #7
0
void HttpAssetTransfer::SendHttpPostAssetRequest(const std::string &host, const std::string &json_data)
{
    std::string ASSET_UPLOADING_CONTENT_TYPE = "application/json";
    int content_length = json_data.length();
    std::istringstream stream(json_data);

    int send_count = 0; //\todo make member var

    Poco::URI uri(host);
    std::string path(uri.getPathAndQuery());
    if (path.empty())
        path = "/";

    http_session_.setHost(uri.getHost());
    http_session_.setPort(uri.getPort());

    Poco::Timespan time_out(HTTP_TIMEOUT_MS*1000);

    Poco::Net::HTTPRequest request;
    request.setMethod(Poco::Net::HTTPRequest::HTTP_POST);
    std::string t = uri.toString();
    request.setURI(uri.getPath());
    request.setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
    request.setContentType(ASSET_UPLOADING_CONTENT_TYPE);
    request.setContentLength(content_length);
    request.setKeepAlive(false);

    try
    {
        std::ostream &request_body = http_session_.sendRequest(request);
        request_body.write(json_data.c_str(), json_data.length());

        std::istream &s = http_session_.receiveResponse(http_response_);

        Poco::Net::HTTPResponse::HTTPStatus status = http_response_.getStatus();
        switch (status)
        {
        case Poco::Net::HTTPResponse::HTTP_OK:
            response_stream_ = &s;
            response_size_ = http_response_.getContentLength();
            break;

        default:
            std::string reason = http_response_.getReasonForStatus(status);
            std::stringstream error;
            error << "Http POST failed for: ";
            error << host << std::endl;
            error << "Reason: " << reason;
            AssetModule::LogError(error.str());
            failed_ = true;
            return;
        }
    }
    catch (Poco::Net::MessageException &e)
    {
        std::string u = request.getURI();
        std::string m = request.getMethod();
        std::string error = e.message();

    }
    catch (Poco::Exception &e)
    {
        std::stringstream error;
        error << "Http POST failed for: ";
        error << host << std::endl;
        error << "Reason: " << e.displayText();
        AssetModule::LogError(error.str());
        failed_ = true;
        return;
    }
}
Example #8
-1
void RemoteJobManager::initHTTPRequest(Poco::Net::HTTPRequest &req,
                                       const std::string &method,
                                       std::string extraPath,
                                       std::string queryString) {
  // Set up the session object
  if (m_session) {
    delete m_session;
    m_session = nullptr;
  }

  if (Poco::URI(m_serviceBaseUrl).getScheme() == "https") {
    // Create an HTTPS session
    // TODO: Notice that we've set the context to VERIFY_NONE. I think that
    // means we're not checking the SSL certificate that the server
    // sends to us. That's BAD!!
    Poco::Net::Context::Ptr context =
        new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "",
                               Poco::Net::Context::VERIFY_NONE, 9, false,
                               "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
    m_session = new Poco::Net::HTTPSClientSession(
        Poco::URI(m_serviceBaseUrl).getHost(),
        Poco::URI(m_serviceBaseUrl).getPort(), context);
  } else {
    // Create a regular HTTP client session.  (NOTE: Using unencrypted HTTP is a
    // really bad idea! We'll be sending passwords in the clear!)
    m_session =
        new Poco::Net::HTTPClientSession(Poco::URI(m_serviceBaseUrl).getHost(),
                                         Poco::URI(m_serviceBaseUrl).getPort());
  }

  Poco::URI uri(m_serviceBaseUrl);
  std::string path = uri.getPath();
  // Path should be something like "/mws/rest", append extraPath to it.
  path += extraPath;

  uri.setPath(path);
  if (method == Poco::Net::HTTPRequest::HTTP_GET && !queryString.empty()) {
    uri.setQuery(queryString);
  }

  req.setVersion(Poco::Net::HTTPRequest::HTTP_1_1);
  req.setMethod(method);
  req.setURI(uri.toString());

  // Attach any cookies we've got from previous responses
  req.setCookies(getCookies());
}