示例#1
0
/**
* Calls a web service to get a full path to a file.
* Only returns a full path string if the file exists
* @param fName :: The file name.
* @return The path to the file or an empty string in case of error/non-existing
* file.
*/
std::string ISISDataArchive::getPath(const std::string &fName) const {
  g_log.debug() << "ISISDataArchive::getPath() - fName=" << fName << "\n";
  if (fName.empty())
    return ""; // Avoid pointless call to service

  URI uri(URL_PREFIX + fName);
  std::string path(uri.getPathAndQuery());

  HTTPClientSession session(uri.getHost(), uri.getPort());
  HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
  session.sendRequest(req);

  HTTPResponse res;
  std::istream &rs = session.receiveResponse(res);
  const HTTPResponse::HTTPStatus status = res.getStatus();
  g_log.debug() << "HTTP response=" << res.getStatus() << "\n";
  if (status == HTTPResponse::HTTP_OK) {
    std::ostringstream os;
    Poco::StreamCopier::copyStream(rs, os);
    os << Poco::Path::separator() << fName;
    try {
      const std::string expectedPath = os.str();
      if (Poco::File(expectedPath).exists())
        return expectedPath;
    } catch (Poco::Exception &) {
    }
  }
  return "";
}
int main(int argc, char **argv) { 
  // using `web` as provider
  URI uri("https://yboss.yahooapis.com/ysearch/web?q=cat");

  // init the creds, I think the empty token and token secret are important
  OAuth10Credentials creds(
      "dj0yJmk9eGx5RzFQOVAwcDZpJmQ9WVdrOWVVUkhWamhwTkdVbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wYw--", 
      "2bf8a4682c4948fb4f7add9598eef5f86b57cf93", "", "");
  
  HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPathEtc());
  
  // put the `q` as param
  HTMLForm params;
  params.set("q", "cat");

  creds.authenticate(request, uri, params);
  std::string auth = request.get("Authorization");
  std::cout << auth << std::endl;

  const Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
  HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
  session.sendRequest(request);

  HTTPResponse response;
  std::istream& rs = session.receiveResponse(response);
  std::cout << response.getStatus() << " " << response.getReason() << std::endl;
  StreamCopier::copyStream(rs, std::cout);
  return 0;
}
示例#3
0
	void fetchAccountPage(HTTPSClientSession& clientSession, NameValueCollection& cookies)
	{
		HTTPRequest request(HTTPRequest::HTTP_GET, "/royalgreenwich/account", HTTPMessage::HTTP_1_1);
		request.setCookies(cookies);
		HTTPResponse response;

		std::ostream& ostr = clientSession.sendRequest(request);
		std::istream& rs = clientSession.receiveResponse(response);

		int statusCode = response.getStatus();

		poco_information_f1(logger(), "Status %d", statusCode);

		std::vector<HTTPCookie> newCookies;
		response.getCookies(newCookies);
		for (HTTPCookie cookie : newCookies)
		{
			poco_information_f1(logger(), "Cookie %s", cookie.toString());
			if (cookies.has(cookie.getName()))
			{
				cookies.set(cookie.getName(), cookie.getValue());
			}
			else
			{
				cookies.add(cookie.getName(), cookie.getValue());
			}
		}
		StreamCopier::copyStream(rs, std::cout);
	}
示例#4
0
文件: http.cpp 项目: pniekamp/leap
//|//////////////////// TestClient //////////////////////////////////////////
void TestClient()
{
  threadlib::ThreadControl tc;

  HTTPServer server;

  server.sigRespond.attach([&](HTTPServer::socket_t socket, HTTPRequest const &request) {
    cout << "  ServerReceive: " << request.method() << " " << request.location() << endl;

    server.send(socket, HTTPResponse("<HTML>OK</HTML>"));
  });

  server.start(1202);

  HTTPResponse response;

  HTTPClient::execute(HTTPRequest("GET", "http://127.0.0.1:1202/objects"), &response);
//  HTTPClient::execute(HTTPRequest("GET", "http://www.websocket.org/echo.html"), &response);

  if (response.status() == 200)
  {
    cout << "  ClientReceive: " << string(response.payload().begin(), response.payload().end()) << "\n";
  }
  else
    cout << "  ** No Data\n";

  tc.join_threads();

  cout << endl;
}
示例#5
0
 void runDelete(){
     try{
         std::string result;
         URI uri("http://jsonplaceholder.typicode.com/posts/" + std::to_string(request->getPostID()) );
         std::string path(uri.getPathAndQuery());
         HTTPClientSession session(uri.getHost(), uri.getPort());
         HTTPRequest hrequest(HTTPRequest::HTTP_DELETE, path, HTTPMessage::HTTP_1_1);
         HTTPResponse response;
         session.sendRequest(hrequest);
         std::istream& rs = session.receiveResponse(response);
         if(response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK){
             Response *res = new Response;
             res->setReqID(reqID);
             res->setHTTPStatus(HTTPResponse::HTTP_OK);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
         else {
             Response *res = new Response;
             res->setHTTPStatus(response.getStatus());
             res->setReqID(reqID);
             observer.responseQueue.enqueueNotification(new ResponseNotification(res));
             {
                 FastMutex::ScopedLock lock(Observer::observerMutex);
                 observer.setResponseAvailable(true);
             }
         }
     }
     catch(Exception& exc){
         std::cerr<< exc.displayText() << std::endl;
     }
 }
示例#6
0
	void fetchLoginPage(HTTPSClientSession& clientSession, NameValueCollection& cookies)
	{
		HTTPRequest request(HTTPRequest::HTTP_GET, "/royalgreenwich/login?message=borrowerservices_notloggedin&referer=https%3A%2F%2Fcapitadiscovery.co.uk%2Froyalgreenwich%2Faccount", HTTPMessage::HTTP_1_1);
		request.setCookies(cookies);
		HTTPResponse response;

		std::ostream& ostr = clientSession.sendRequest(request);
		std::istream& rs = clientSession.receiveResponse(response);

		int statusCode = response.getStatus();

		poco_information_f1(logger(), "Status %d", statusCode);

		std::vector<HTTPCookie> newCookies;
		response.getCookies(newCookies);
		for (HTTPCookie cookie : newCookies)
		{
			poco_information_f1(logger(), "Cookie %s", cookie.toString());
			if (cookies.has(cookie.getName()))
			{
				cookies.set(cookie.getName(), cookie.getValue());
			}
			else
			{
				cookies.add(cookie.getName(), cookie.getValue());
			}
		}
	}
示例#7
0
void HTTPCredentialsTest::testAuthenticationParams()
{
	const std::string authInfo("nonce=\"212573bb90170538efad012978ab811f%lu\", realm=\"TestDigest\", response=\"40e4889cfbd0e561f71e3107a2863bc4\", uri=\"/digest/\", username=\"user\"");
	HTTPAuthenticationParams params(authInfo);
	
	assert (params["nonce"] == "212573bb90170538efad012978ab811f%lu");
	assert (params["realm"] == "TestDigest");
	assert (params["response"] == "40e4889cfbd0e561f71e3107a2863bc4");
	assert (params["uri"] == "/digest/");
	assert (params["username"] == "user");
	assert (params.size() == 5);
	assert (params.toString() == authInfo);
	
	params.clear();
	HTTPRequest request;
	request.set("Authorization", "Digest " + authInfo);
	params.fromRequest(request);

	assert (params["nonce"] == "212573bb90170538efad012978ab811f%lu");
	assert (params["realm"] == "TestDigest");
	assert (params["response"] == "40e4889cfbd0e561f71e3107a2863bc4");
	assert (params["uri"] == "/digest/");
	assert (params["username"] == "user");
	assert (params.size() == 5);

	params.clear();
	HTTPResponse response;
	response.set("WWW-Authenticate", "Digest realm=\"TestDigest\", nonce=\"212573bb90170538efad012978ab811f%lu\"");	
	params.fromResponse(response);
	
	assert (params["realm"] == "TestDigest");
	assert (params["nonce"] == "212573bb90170538efad012978ab811f%lu");
	assert (params.size() == 2);
}
示例#8
0
void HTTPSClientSessionTest::testPostLargeChunkedKeepAlive()
{
	SecureServerSocket svs(32322);
	HTTPServer srv(new TestRequestHandlerFactory(), svs, new HTTPServerParams());
	srv.start();
	try
	{
		HTTPSClientSession s("localhost", srv.port());
		s.setKeepAlive(true);
		for (int i = 0; i < 10; ++i)
		{
			HTTPRequest request(HTTPRequest::HTTP_POST, "/keepAlive", HTTPMessage::HTTP_1_1);
			std::string body(16000, 'x');
			request.setChunkedTransferEncoding(true);
			s.sendRequest(request) << body;
			HTTPResponse response;
			std::istream& rs = s.receiveResponse(response);
			assert (response.getChunkedTransferEncoding());
			assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
			std::ostringstream ostr;
			StreamCopier::copyStream(rs, ostr);
			assert (ostr.str() == body);
		}
		srv.stop();
	}
	catch (...)
	{
		srv.stop();
		throw;
	}
}
示例#9
0
ofxHttpResponse ofxHttpUtils::getUrl(string url){

   ofxHttpResponse response;
   try{
		URI uri(url.c_str());
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPClientSession session(uri.getHost(), uri.getPort());
		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		if(auth.getUsername()!="") auth.authenticate(req);
		session.setTimeout(Poco::Timespan(timeoutSeconds,0));
		session.sendRequest(req);
		HTTPResponse res;
		istream& rs = session.receiveResponse(res);

		response=ofxHttpResponse(res, rs, path);

		if(response.status>=300 && response.status<400){
			Poco::URI uri(req.getURI());
			uri.resolve(res.get("Location"));
			response.location = uri.toString();
		}

		ofNotifyEvent( newResponseEvent, response, this );

		//std::cout << res.getStatus() << " " << res.getReason() << std::endl;
		//StreamCopier::copyStream(rs, std::cout);

	}catch (Exception& exc){
		std::cerr << exc.displayText() << "\n";
	}
	return response;

}
示例#10
0
uHTTP::HTTP::StatusCode TestDevice::httpRequestRecieved(HTTPRequest *httpReq)
{
	ParameterList paramList;
	httpReq->getParameterList(paramList);
	for (int n=0; n<paramList.size(); n++) {
		Parameter *param = paramList.getParameter(n);
		cout << "["<< n << "] : "<< param->getName() << "= "<< param->getValue() << endl;
	}

	string uri;
	httpReq->getURI(uri);
	if (uri.find(PRESENTATION_URI) == string::npos)  {
		return Device::httpRequestRecieved(httpReq);
	}
			 
	string contents;
	contents = "<HTML><BODY><H1>";
	contents += "";
	contents += "</H1></BODY></HTML>";
		
	HTTPResponse httpRes;
	httpRes.setStatusCode(HTTP::OK_REQUEST);
	httpRes.setContent(contents);
	return httpReq->post(&httpRes);
}
void GalaxyFDSClient::refreshObject(const string& bucketName, const string&
    objectName) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      _emptySubResources);
  uri += "?refresh";
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_PUT, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_PUT, "", _emptyStream,
    *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Prefetch object failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
示例#12
0
	void submitLoginPage(HTTPSClientSession& clientSession, NameValueCollection& cookies)
	{
		HTTPRequest request(HTTPRequest::HTTP_POST, "/royalgreenwich/sessions", HTTPMessage::HTTP_1_1);
		request.setCookies(cookies);
		HTTPResponse response;
		HTMLForm loginForm;
		loginForm.add("barcode", "28028005913354");
		loginForm.add("pin", "3347");
		loginForm.prepareSubmit(request);

		std::ostream& ostr = clientSession.sendRequest(request);
		loginForm.write(ostr);
		std::istream& rs = clientSession.receiveResponse(response);

		int statusCode = response.getStatus();

		poco_information_f1(logger(), "Status %d", statusCode);

		std::vector<HTTPCookie> newCookies;
		response.getCookies(newCookies);
		for (HTTPCookie cookie : newCookies)
		{
			poco_information_f1(logger(), "Cookie %s", cookie.toString());
			if (cookies.has(cookie.getName()))
			{
				cookies.set(cookie.getName(), cookie.getValue());
			}
			else
			{
				cookies.add(cookie.getName(), cookie.getValue());
			}
		}
	}
bool GalaxyFDSClient::doesObjectExist(const string& bucketName, const string&
    objectName) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      _emptySubResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_HEAD, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_HEAD, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() == HTTPResponse::HTTP_OK) {
    return true;
  } else if (response.getStatus() == HTTPResponse::HTTP_NOT_FOUND) {
    return false;
  } else {
    stringstream msg;
    msg << "Check object existence failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
void GalaxyFDSClient::setObjectAcl(const string& bucketName, const string&
    objectName, const AccessControlList& acl) {
  vector<string> subResources;
  subResources.push_back(SubResource::ACL);
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      subResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_PUT, uri, HTTPMessage::HTTP_1_1);
  stringstream ss(AccessControlList::serialize(acl));
  prepareRequestHeaders(uri, HTTPRequest::HTTP_PUT, "application/json", ss,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  StreamCopier::copyStream(ss, os);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Set Object acl failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }
}
shared_ptr<FDSObjectMetadata> GalaxyFDSClient::getObjectMetadata(const string&
    bucketName, const string& objectName) {
  vector<string> subResources;
  subResources.push_back(SubResource::METADATA);
  string uri = formatUri(_pConfig->getBaseUri(), bucketName + "/" + objectName,
      subResources);
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry->createClientSession(
        pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "Get object metadata failed, status=" << response.getStatus()
      << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return parseMetadata(response);
}
shared_ptr<FDSObjectListing> GalaxyFDSClient::listObjects(const string&
    bucketName, const string& prefix, const string& delimiter) {
  string uri = formatUri(_pConfig->getBaseUri(), bucketName, _emptySubResources);
  uri += "?prefix=" + prefix + "&delimiter=" + delimiter;
  URI pocoUri(uri);

  shared_ptr<HTTPClientSession> pSession(_pSessionFacotry
      ->createClientSession(pocoUri));
  pSession->setHost(pocoUri.getHost());
  pSession->setPort(pocoUri.getPort());
  HTTPRequest request(HTTPRequest::HTTP_GET, uri, HTTPMessage::HTTP_1_1);
  prepareRequestHeaders(uri, HTTPRequest::HTTP_GET, "", _emptyStream,
      *_pEmptyMetadata, request);
  HTTPResponse response;

  ostream& os = pSession->sendRequest(request);
  istream& rs = pSession->receiveResponse(response);

  if (response.getStatus() != HTTPResponse::HTTP_OK) {
    stringstream msg;
    msg << "List objects failed, status=" << response.getStatus() << ", reason=";
    StreamCopier::copyStream(rs, msg);
    throw GalaxyFDSClientException(response.getStatus(), msg.str());
  }

  return FDSObjectListing::deserialize(rs);
}
示例#17
0
bool
EarthFile::readXML( const std::string& location )
{
    bool success = false;

    if ( osgDB::containsServerAddress( location ) )
    {
        HTTPResponse response = HTTPClient::get( location );
        if ( response.isOK() && response.getNumParts() > 0 )
        {
            success = readXML( response.getPartStream( 0 ), location );
        }
    }
    else
    {
        if (osgDB::fileExists(location) && (osgDB::fileType(location) == osgDB::REGULAR_FILE))
        {
            std::ifstream in( location.c_str() );
            success = readXML( in, location );
        }
    }

    if ( success )
    {
        std::string filename = location;
        if (!osgDB::containsServerAddress(filename))
        {
            filename = osgDB::getRealPath( location );
        }
        _map->setReferenceURI( filename );
    }

    return success;
}
示例#18
0
int main(int argc, char** argv)
{
	if (argc != 2)
	{
		Path p(argv[0]);
		std::cout << "usage: " << p.getBaseName() << " <uri>" << std::endl;
		std::cout << "       fetches the resource identified by <uri> and print it to the standard output" << std::endl;
		return 1;
	}

	try
	{
		URI uri(argv[1]);
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPClientSession session(uri.getHost(), uri.getPort());
		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		session.sendRequest(req);
		HTTPResponse res;
		std::istream& rs = session.receiveResponse(res);
		std::cout << res.getStatus() << " " << res.getReason() << std::endl;
		StreamCopier::copyStream(rs, std::cout);
	}
	catch (Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
		return 1;
	}
	return 0;
}
示例#19
0
// Sends a file to the server
void sendFile(HTTPClient* client, string filename) 
{
    HTTPRequest request;
    HTTPResponse response;

    // Send a HEAD request 
    request.method = "HEAD";
    request.path = "/" + filename;
    response = client->send(request);

    if (response.status == 200) {
        // The file exists. Compare MD5 checksums
        // TODO: Make a local MD5 checksums cache when this get's multithreaded.            
        if (WebUtil::MD5(filename) == response.getHeader("Content-MD5")) {
            return;        
        }
    }

    request.method = "PUT";
    request.path = "/" + filename;
    FILE* f = fopen(filename.c_str(),"r");
    if (f == NULL) {
        throw_exception("Couldn't read " + filename);        
    }
    request.setBody(f);

    request.addHeader("Content-type", WebUtil::pathToMimetype(filename));
    request.addHeader("Content-length", WebUtil::filesize(filename));
    response = client->send(request);
    fclose(f);
}
示例#20
0
	/// checks the validity of the HTTP response
	void checkResponse(const HTTPResponse& http_response)
	{
		BOOST_REQUIRE(http_response.getStatusCode() == 200);
		BOOST_CHECK(! http_response.hasHeader(HTTPTypes::HEADER_CONTENT_LENGTH));
		BOOST_REQUIRE(http_response.getContentLength() == BIG_BUF_SIZE);
		BOOST_CHECK_EQUAL(memcmp(http_response.getContent(), m_big_buf, BIG_BUF_SIZE), 0);
	}
示例#21
0
bool
HTTPClient::doDownload(const std::string& url, const std::string& filename)
{
    initialize();

    // download the data
    HTTPResponse response = this->doGet( HTTPRequest(url) );

    if ( response.isOK() )
    {
        unsigned int part_num = response.getNumParts() > 1? 1 : 0;
        std::istream& input_stream = response.getPartStream( part_num );

        std::ofstream fout;
        fout.open(filename.c_str(), std::ios::out | std::ios::binary);

        input_stream.seekg (0, std::ios::end);
        int length = input_stream.tellg();
        input_stream.seekg (0, std::ios::beg);

        char *buffer = new char[length];
        input_stream.read(buffer, length);
        fout.write(buffer, length);
        delete[] buffer;
        fout.close();
        return true;
    }
    else
    {
        OE_WARN << LC << "Error downloading file " << filename
            << " (" << response.getCode() << ")" << std::endl;
        return false;
    } 
}
Node *Parser::parse(uHTTP::URL *url) {
  LogInfo("parse,TID(0x%04x): %s\n", GetCurrentThreadId(), url->getSting()); 
  HTTPRequest httpReq;
  HTTPResponse *httpRes = NULL;
  {
      FUNCTION_BLOCK_NAME_TRACE("post", 100);

      const char *host = url->getHost();
      int port = url->getPort();
      std::string target = url->getTarget();

      httpReq.setMethod(HTTP::GET);
      httpReq.setURI(target);
      httpRes = httpReq.post(host, port);
      if (httpRes->isSuccessful() == false){
          return NULL;
      }
  }

  Node* pNode = NULL;
  {
      FUNCTION_BLOCK_NAME_TRACE("ParseContent", 100);
     const char *contents = httpRes->getContent();
     pNode = parse(contents);
  }
  
  return pNode;
}
示例#23
0
void HTTPResponseTest::testWrite1()
{
	HTTPResponse response;
	std::ostringstream ostr;
	response.write(ostr);
	std::string s = ostr.str();
	assert (s == "HTTP/1.0 200 OK\r\n\r\n");
}
示例#24
0
void HTTPCredentialsTest::testProxyCredentialsBasic()
{
	HTTPCredentials creds("user", "s3cr3t");
	HTTPRequest request(HTTPRequest::HTTP_GET, "/basic/");
	HTTPResponse response;
	response.set("Proxy-Authenticate", "Basic realm=\"TestBasic\"");	
	creds.proxyAuthenticate(request, response);	
	assert (request.get("Proxy-Authorization") == "Basic dXNlcjpzM2NyM3Q=");
}
示例#25
0
void HTTPCredentialsTest::testProxyCredentialsDigest()
{
	HTTPCredentials creds("user", "s3cr3t");
	HTTPRequest request(HTTPRequest::HTTP_GET, "/digest/");
	HTTPResponse response;
	response.set("Proxy-Authenticate", "Digest realm=\"TestDigest\", nonce=\"212573bb90170538efad012978ab811f%lu\"");	
	creds.proxyAuthenticate(request, response);	
	assert (request.get("Proxy-Authorization") == "Digest username=\"user\", nonce=\"212573bb90170538efad012978ab811f%lu\", realm=\"TestDigest\", uri=\"/digest/\", response=\"40e4889cfbd0e561f71e3107a2863bc4\"");
}
示例#26
0
void WebServer::onClientMessage(TcpClient* client, char* buffer, size_t size)
{
    clearExpiredSessions();

    HTTPResponse* resp = 0;
    HTTPRequest* req = new HTTPRequest(buffer,size);
    HTTPAuth auth = req->getAuthorization();
    bool authOK = validateAuthentication(req,auth);
    if (authOK)
    {
        if (mpListener!=0)
        {
            resp = mpListener->processHTTPRequest(req);
            if (resp!=0 && auth.nonce!="" && mSessions.find(auth.nonce)!=mSessions.end())
            {
                std::string cookie = "session="+auth.nonce;
                resp->setCookie(cookie);
            }
            sendResponse(resp,client);
        }
        else
        {
            resp = HTTPProtocol::buildBufferedResponse(ServiceUnavailable,"","");
            sendResponse(resp,client);
        }
    }
    else
    {
        std::string nonce = "";
        WebSession ws;
        if (auth.nonce!="" && mSessions.find(auth.nonce) != mSessions.end())
        {
            nonce = auth.nonce;
            ws = mSessions[nonce];
        }
        else
        {
            nonce = generateNonce();
            ws.mNonce = nonce;
        }

        time_t t;
        time(&t);
        t+=mSessionExpires;
        ws.mExpires = t;
        mSessions[nonce] = ws;
        std::string content = "{\"status\" : \"Authorization needed\"}";
        std::string authHeader = "Digest realm=\"dumais\",nonce=\""+nonce+"\"";
        HTTPResponseCode code = Unauthorized;
        resp = HTTPProtocol::buildBufferedResponse(code,content,"application/json", authHeader);
        if (req->wantsAuthenticationHack()) resp->useAuthenticationHack();
        sendResponse(resp,client);
    }

    delete buffer;
}
示例#27
0
ofHttpResponse ofURLFileLoader::handleRequest(ofHttpRequest request) {
	try {
		URI uri(request.url);
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		HTTPResponse res;
		ofPtr<HTTPSession> session;
		istream * rs;
		if(uri.getScheme()=="https"){
			 //const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "rootcert.pem" ) );
			HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			httpsSession->setTimeout(Poco::Timespan(20,0));
			httpsSession->sendRequest(req);
			rs = &httpsSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpsSession);
		}else{
			HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
			httpSession->setTimeout(Poco::Timespan(20,0));
			httpSession->sendRequest(req);
			rs = &httpSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpSession);
		}
		if(!request.saveTo){
			return ofHttpResponse(request,*rs,res.getStatus(),res.getReason());
		}else{
			ofFile saveTo(request.name,ofFile::WriteOnly,true);
			char aux_buffer[1024];
			rs->read(aux_buffer, 1024);
			std::streamsize n = rs->gcount();
			while (n > 0){
				// we resize to size+1 initialized to 0 to have a 0 at the end for strings
				saveTo.write(aux_buffer,n);
				if (rs->good()){
					rs->read(aux_buffer, 1024);
					n = rs->gcount();
				}
				else n = 0;
			}
			return ofHttpResponse(request,res.getStatus(),res.getReason());
		}

	} catch (const Exception& exc) {
        ofLogError("ofURLFileLoader") << "handleRequest(): "+ exc.displayText();

        return ofHttpResponse(request,-1,exc.displayText());

    } catch (...) {
    	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
    }

	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
	
}	
int InternetHelper::processRelocation(const HTTPResponse &response,
                                      std::ostream &responseStream) {
  std::string newLocation = response.get("location", "");
  if (!newLocation.empty()) {
    g_log.information() << "url relocated to " << newLocation;
    return this->sendRequest(newLocation, responseStream);
  } else {
    g_log.warning("Apparent relocation did not give new location\n");
    return response.getStatus();
  }
}
示例#29
0
void HTTPCredentialsTest::testVerifyAuthInfoQoP()
{
	HTTPDigestCredentials creds("user", "s3cr3t");
	HTTPRequest request(HTTPRequest::HTTP_GET, "/digest/");
	HTTPResponse response;
	response.set("WWW-Authenticate", "Digest realm=\"TestDigest\", nonce=\"212573bb90170538efad012978ab811f%lu\", opaque=\"opaque\", qop=\"auth,auth-int\"");	
	creds.authenticate(request, response);
	assert (creds.verifyAuthInfo(request));
	
	request.set("Authorization", "Digest cnonce=\"f9c80ffd1c3bc4ee47ed92b704ba75a4\", nc=00000001, nonce=\"212573bb90170538efad012978ab811f%lu\", opaque=\"opaque\", qop=\"auth\", realm=\"TestDigest\", response=\"ff0e90b9aa019120ea0ed6e23ce95d9a\", uri=\"/digest/\", username=\"user\"");
	assert (!creds.verifyAuthInfo(request));
}
示例#30
0
TEST(HTTPClientSession, testHead)
{
	HTTPClientSession s("localhost", 80);
	HTTPRequest request(HTTPRequest::HTTP_HEAD, "/large");
	s.sendRequest(request);
	HTTPResponse response;
	std::istream& rs = s.receiveResponse(response);
	EXPECT_TRUE (response.getContentLength() > 0);
	EXPECT_TRUE (response.getContentType() == "text/plain");
	std::ostringstream ostr;
	EXPECT_TRUE (StreamCopier::copyStream(rs, ostr) == 0);
}