Beispiel #1
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setChunkedTransferEncoding(true);
		response.setContentType(request.getContentType());
		std::ostream& ostr = response.send();
		Poco::StreamCopier::copyStream(request.stream(), ostr);
	}
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		try
		{			
			std::string proto = request.get("Sec-WebSocket-Protocol", "");
			Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket;
			if (proto == "com.appinf.webtunnel.server/1.0")
			{
				response.set("Sec-WebSocket-Protocol", proto);
				pWebSocket = new Poco::Net::WebSocket(request, response);
				_portReflector.addServerSocket(pWebSocket, "ac9667bb-6032-4267-af61-9a7aafd40479");
			}
			else if (proto == "com.appinf.webtunnel.client/1.0")
			{
				response.set("Sec-WebSocket-Protocol", proto);
				std::string portStr = request.get("X-WebTunnel-RemotePort", "");
				unsigned port;
				if (!portStr.empty() && Poco::NumberParser::tryParseUnsigned(portStr, port) && port > 0 && port < 65536)
				{
					pWebSocket = new Poco::Net::WebSocket(request, response);
					try
					{
						_portReflector.addClientSocket(pWebSocket, "ac9667bb-6032-4267-af61-9a7aafd40479", static_cast<Poco::UInt16>(port));
					}
					catch (Poco::NotFoundException&)
					{
						pWebSocket->shutdown(Poco::Net::WebSocket::WS_UNEXPECTED_CONDITION, "No connection to target available");
					}
				}
				else
				{
					pWebSocket = new Poco::Net::WebSocket(request, response);
					pWebSocket->shutdown(Poco::Net::WebSocket::WS_UNEXPECTED_CONDITION, "Missing or invalid X-WebTunnel-RemotePort header");
				}
			}
			else
			{
				pWebSocket = new Poco::Net::WebSocket(request, response);
				pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
			}
		}
		catch (WebSocketException& exc)
		{
			app.logger().log(exc);
			switch (exc.code())
			{
			case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
				response.set("Sec-WebSocket-Version", 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(HTTPResponse::HTTP_BAD_REQUEST);
				response.setContentLength(0);
				response.send();
				break;
			}
		}
	}
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		app.logger().information("Request from " + request.clientAddress().toString());

		SecureStreamSocket socket = static_cast<HTTPServerRequestImpl&>(request).socket();
		if (socket.havePeerCertificate())
		{
			X509Certificate cert = socket.peerCertificate();
			app.logger().information("Client certificate: " + cert.subjectName());
		}
		else
		{
			app.logger().information("No client certificate available.");
		}
		
		Timestamp now;
		std::string dt(DateTimeFormatter::format(now, _format));

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

		std::ostream& ostr = response.send();
		ostr << "<html><head><title>HTTPTimeServer powered by POCO C++ Libraries</title>";
		ostr << "<meta http-equiv=\"refresh\" content=\"1\"></head>";
		ostr << "<body><p style=\"text-align: center; font-size: 48px;\">";
		ostr << dt;
		ostr << "</p></body></html>";
	}
Beispiel #4
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setChunkedTransferEncoding(true);
		
		URI uri(request.getURI());
		std::string path = uri.getPath();
		std::string sql = getSQL();
		std:: cout << "Executing;[" << sql << ']' << std::endl;
		Session session("SQLite", ROOT_DIR"simpsons.db");
		if (path == "/html")
		{
			response.setContentType("text/html");
			response.send() << RecordSet(session, sql, HTMLTableFormatter());
		}
		else if (path == "/xml")
		{
			response.setContentType("text/xml");
			response.send() << RecordSet(session, sql, XMLFormatter());
		}
	}
void PageRequestHandler::handleRequest( HTTPServerRequest& request, 
                                        HTTPServerResponse& response ) 
{
    response.setChunkedTransferEncoding(true);
    response.setContentType("text/html");
    std::ostream& ostr = response.send();
    ostr<<"<html>";
    ostr<<"<body>";
    ostr<<"Stub (HTML) output - insert JavaScript HERE";
    ostr<<"</body>";
    ostr<<"</html>";
}
 virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp){
   resp.setStatus(HTTPResponse::HTTP_OK);
   resp.setContentType("text/html");
   
   // Generate requested HTML file
   ostream& out = resp.send();
   out << "<h1>Hello world! This files name is " << req.getURI() << "</h1>"
       << "<p>Host: "           << req.getHost()   << "</p>"
       << "<p>Method: "         << req.getMethod() << "</p>";
   out.flush();
   
   cout << endl << "Client requested: =" << req.getURI() << endl;  
 }
//------------------------------------------------------------------------------
bool ofxWebServerBaseRouteHandler::isValidRequest(const Settings& settings,
                                                  HTTPServerRequest& request,
                                                  HTTPServerResponse& response) {
    
    string sessionId = "";
    
    // extract cookie from request
    NameValueCollection cookies;
    request.getCookies(cookies);
    NameValueCollection::ConstIterator it = cookies.find(settings.sessionCookieName);
    if (it != cookies.end()) {
        sessionId = it->second;
    } else {
        sessionId = ofxWebServerSessionManager::generateSessionKey(request);
        HTTPCookie cookie(settings.sessionCookieName,sessionId);
        cookie.setPath("/");
        // set no age, so it expires @ end of session
        response.addCookie(cookie);
    }
    
    // TODO: update session manager
    
    URI uri(request.getURI());
    
    const string path = uri.getPath(); // just get the path

    if(settings.requireAuthentication) {
        if(request.hasCredentials()) {
            HTTPBasicCredentials credentials(request);
            const string& user = credentials.getUsername();
            const string& pwd = credentials.getPassword();
            
            if(settings.username == credentials.getUsername() &&
               settings.password == credentials.getPassword()) {
                // add an authentication cookie?
                return true;
            } else {
                response.setStatusAndReason(HTTPResponse::HTTP_UNAUTHORIZED);
                sendErrorResponse(response);
                return false;
            }
        } else {
            response.requireAuthentication(settings.realm);
            response.setContentLength(0);
            response.send();
            return false;
        }
    } else {
        return true;
    }
}
//------------------------------------------------------------------------------
void ofxIpVideoServerRouteHandler::handleRequest(HTTPServerRequest& request,
                                                 HTTPServerResponse& response) {
    
    
    if(isValidRequest(settings.route,request,response)) {
        MediaType mediaType("multipart/x-mixed-replace");
        mediaType.setParameter("boundary", settings.boundary);

        string expires = DateTimeFormatter::format(Timestamp(0), // the beginning of time
                                                   DateTimeFormat::HTTP_FORMAT);
        
        response.set("Cache-control","no-cache");
        response.setContentType(mediaType);
        response.set("Expires",expires);
        response.set("Pragma","no-cache");
        
        std::ostream& ostr = response.send(); // get output stream

        bool stopStreaming = false;
        
        while(ostr.good() && !stopStreaming) {
            if(!queue.empty()) {
                ofxIpVideoServerFramePtr frame = queue.pop();
                    if(frame != NULL) {
                        ofBuffer* buffer = &frame.get()->buffer;
                        ostr << settings.boundary;
                        ostr << "\r\n";
                        ostr << "Content-Type: image/jpeg";
                        ostr << "\r\n";
                        ostr << "Content-Length: " << ofToString(buffer->size());
                        ostr << "\r\n";
                        ostr << "\r\n";
                        ostr << *buffer;
                    } else {
                        ofLogVerbose("ofxIpVideoServerRouteHandler::handleRequest") << "Null buffer.";
                    }
                } else {
                    ofLogVerbose("ofxIpVideoServerRouteHandler::handleRequest") << "Queue empty.";
                }
            
            Thread::sleep(50);
        }
        
        queue.setActive(false); // a desperate move 
        
        ofLogNotice("ofxIpVideoServerRouteHandler::handleRequest") << "Client disconneted.";
        
        //sendErrorResponse(response);
    }
}
Beispiel #9
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Timestamp now;
		std::string dt(DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT));

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

		std::ostream& ostr = response.send();
		ostr << "<html><head><title>TimeServer powered by POCO ApacheConnector</title>";
		ostr << "<meta http-equiv=\"refresh\" content=\"1\"></head>";
		ostr << "<body><p style=\"text-align: center; font-size: 48px;\">";
		ostr << dt;
		ostr << "</p></body></html>";
	}
//------------------------------------------------------------------------------
void ofxWebServerUploadRouteHandler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) {
    if(isValidRequest(settings.route, request, response)) {
        HTMLForm form(request, request.stream(), *this);
        
        if(!settings.uploadRedirect.empty()) {
            response.redirect(settings.uploadRedirect);
        } else {
            response.setStatusAndReason(HTTPResponse::HTTP_OK);
            response.setContentLength(0);
            response.send();
        }
    } else {
        return; // isValidRequest took care of the response
    }
}
Beispiel #11
0
 void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
 {
     Application& app = Application::instance();
     try
     {
         WebSocket ws(request, response);
         XDUTxtSetText(ID_CURRENT_STATUS, Convert::toQXStringRef(L"Выполнено подключение к плагину. Чтобы начать интерпретацию - кликните по соотвествующей кнопке плагина Вашего браузера."));
         char buffer[MAX_BUFFER_SIZE];
         int flags=0;
         int n=1;
         do
         {
             ZeroMemory(buffer, MAX_BUFFER_SIZE);
             n = ws.receiveFrame(buffer, sizeof(buffer), flags);
             wstring message = Convert::toUnicodeString(buffer);
             if (message == L"plugin-version") {
                 //Следующее сообщение передаст данные о плагине
                 n = ws.receiveBytes(buffer, sizeof(buffer), flags);
                 XDUTxtSetText(ID_BROWSER_PLUGIN_VERSION, Convert::toQXStringRef(Convert::toUnicodeString(buffer)));
             }
             if (message == L"exportSettings") {
                 n = ws.receiveBytes(buffer, sizeof(buffer), flags);
                 ImportSettings::globalSettings=Convert::jsonToSettings(Convert::toUnicodeString(buffer));
             }
             if (message == L"start-export") {
                 WebCore::getInstance().setSocket(&ws);
                 WebCore::startExport = true;
                 while (WebCore::startExport == true);
             }
         } while (n > 0);
     }
     catch (WebSocketException& exc)
     {
         switch (exc.code())
         {
         case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
             response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
         // fallthrough
         case WebSocket::WS_ERR_NO_HANDSHAKE:
         case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
         case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
             response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
             response.setContentLength(0);
             response.send();
             break;
         }
     }
 }
void ofxWebServerBaseRouteHandler::sendErrorResponse(HTTPServerResponse& response) {
    // we will assume that the sender has set the status and
    // reason appropriately before calling the sendErrorResponse()
    
    HTTPResponse::HTTPStatus status = response.getStatus();
    string reason = response.getReason();
    response.setChunkedTransferEncoding(true);
    response.setContentType("text/html");
    std::ostream& ostr = response.send(); // get output stream
    ostr << "<html>";
    ostr << "<head><title>" << status << "-" << reason << "</title></head>";
    ostr << "<body>";
    ostr << "<h1>" << status << "-" << reason << "</h1>";
    ostr << "</body>";
    ostr << "<html>";
}
Beispiel #13
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		try
		{
			WebSocket ws(request, response);
			app.logger().information("WebSocket connection established.");
			char buffer[BUFF_LEN];
			int flags;
			int n;
			do
			{	
				int recvLen = 0;
				while (recvLen < BUFF_LEN) {
					n = ws.receiveFrame(buffer, BUFF_LEN - recvLen, flags);
					recvLen += n;
				}
				
				app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", n, unsigned(flags)));
				
				String resp ("aaaaaaaaaa");
				
				ws.sendFrame(resp.getCStr(), resp.getLength(), flags);
			}
			while (n > 0 || (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
			app.logger().information("WebSocket connection closed.");
		}
		catch (WebSocketException& exc)
		{
			app.logger().log(exc);
			switch (exc.code())
			{
				case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
					response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
					// fallthrough
				case WebSocket::WS_ERR_NO_HANDSHAKE:
				case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
				case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
					response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
					response.setContentLength(0);
					response.send();
					break;
			}
		}
	}
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		app.logger().information("Request from " + request.clientAddress().toString());

		Timestamp now;
		std::string dt(DateTimeFormatter::format(now, _format));

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

		std::ostream& ostr = response.send();
		ostr << "<html><head><title>HTTPTimeServer powered by POCO C++ Libraries</title>";
		ostr << "<meta http-equiv=\"refresh\" content=\"1\"></head>";
		ostr << "<body><p style=\"text-align: center; font-size: 48px;\">";
		ostr << dt;
		ostr << "</p></body></html>";
	}
Beispiel #15
0
 void PageRequestHandler::handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp) {
   resp.setStatus(HTTPResponse::HTTP_OK);
   // std::cout << Poco::format("Received request %s", req.getURI()) << std::endl;
   string fileName = req.getURI() == "/" ? "index.html" : (req.getURI().substr(1));
   
   if (stringEndsWith(fileName, ".html")) {
     resp.setContentType("text/html");
   } else if (stringEndsWith(fileName, ".css")) {
     resp.setContentType("text/css");
   } else if (stringEndsWith(fileName, ".js")) {
     resp.setContentType("application/javascript");
   } else if (stringEndsWith(fileName, ".woff")) {
     resp.setContentType("font/woff");
   } else {
     resp.setContentType("text/html");
   }
   FileInputStream input(fileName);
   StreamCopier::copyStream(input, resp.send());
 }
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setChunkedTransferEncoding(true);
		response.setContentType("text/html");
		std::ostream& ostr = response.send();
		ostr << "<html>";
		ostr << "<head>";
		ostr << "<title>WebSocketServer</title>";
		ostr << "<script type=\"text/javascript\">";
		ostr << "function WebSocketTest()";
		ostr << "{";
		ostr << "  if (\"WebSocket\" in window)";
		ostr << "  {";
		ostr << "    var ws = new WebSocket(\"ws://" << request.serverAddress().toString() << "/ws\");";
		ostr << "    ws.onopen = function()";
		ostr << "      {";
		ostr << "        ws.send(\"Hello, world!\");";
		ostr << "      };";
		ostr << "    ws.onmessage = function(evt)";
		ostr << "      { ";
		ostr << "        var msg = evt.data;";
		ostr << "        alert(\"Message received: \" + msg);";
		ostr << "        ws.close();";
		ostr << "      };";
		ostr << "    ws.onclose = function()";
		ostr << "      { ";
		ostr << "        alert(\"WebSocket closed.\");";
		ostr << "      };";
		ostr << "  }";
		ostr << "  else";
		ostr << "  {";
		ostr << "     alert(\"This browser does not support WebSockets.\");";
		ostr << "  }";
		ostr << "}";
		ostr << "</script>";
		ostr << "</head>";
		ostr << "<body>";
		ostr << "  <h1>WebSocket Server</h1>";
		ostr << "  <p><a href=\"javascript:WebSocketTest()\">Run WebSocket Script</a></p>";
		ostr << "</body>";
		ostr << "</html>";
	}
Beispiel #17
0
    void handleRequest(HTTPServerRequest& request,
                       HTTPServerResponse& response)
    {
        StringTokenizer tok("/");
        StringVector tized;
        tok.tokenize(request.getURI(), tized);            
        if ( tized.size() == 4 )
        {
            int z = as<int>(tized[1], 0);
            int x = as<int>(tized[2], 0);
            unsigned int y = as<int>(osgDB::getNameLessExtension(tized[3]),0);
            std::string ext = osgDB::getFileExtension(tized[3]);

            OE_DEBUG << "z=" << z << std::endl;
            OE_DEBUG << "x=" << x << std::endl;
            OE_DEBUG << "y=" << y << std::endl;              
            OE_DEBUG << "ext=" << ext << std::endl;

            response.setChunkedTransferEncoding(true);

            osg::ref_ptr< osg::Image > image = _server->getTile(z, x, y);
            
            if (image)
            {
                osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(ext);
                if (rw)
                {
                    std::string mime = "image/png";
                    if (ext == "jpeg" || ext == "jpg")
                    {
                        mime = "image/jpeg";
                    }                    
                    response.setContentType(mime);
                    std::ostream& ostr = response.send();                 
                    rw->writeImage(*image.get(), ostr);                    
                }             

            }
        }
 
        response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);                
    }
Beispiel #18
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setContentType("text/html");
		response.setChunkedTransferEncoding(true);
		std::ostream& ostr = response.send();

		const std::string& softwareVersion = request.serverParams().getSoftwareVersion();
		LocalDateTime now;

		std::string osName = Environment::osName();
		std::string osDisplayName = Environment::osDisplayName();
		if (osDisplayName != osName)
		{
			osName += " (";
			osName += osDisplayName;
			osName += ")";
		}

		ostr << "<HTML><HEAD><TITLE>Server Information</TITLE>"
		        "<LINK REL=\"stylesheet\" HREF=\"css/styles.css\" TYPE=\"text/css\"/></HEAD><BODY>"
		        "<DIV CLASS=\"header\">"
				"<H1 CLASS=\"category\">Open Service Platform</h1>"
				"<H1 CLASS=\"title\">Server Information</H1>"
				"</DIV>"
		        "<DIV CLASS=\"body\">"
		        "<UL>";
		    
		ostr << "<LI><B>Host:</B> " << Environment::nodeName() << "</LI>"
		     << "<LI><B>Node ID:</B> " << Environment::nodeId() << "</LI>"
		     << "<LI><B>IP Addresses:</B> " << getHostAddresses() << "</LI>"
		     << "<LI><B>OS Name:</B> " << osName << "</LI>"
		     << "<LI><B>OS Version:</B> " << Environment::osVersion() << "</LI>"
		     << "<LI><B>OS Architecture:</B> " << Environment::osArchitecture() << "</LI>"
		     << "<LI><B>Processor Cores:</B> " << Environment::processorCount() << "</LI>"
		     << "<LI><B>Local Server Time:</B> " << DateTimeFormatter::format(now, DateTimeFormat::HTTP_FORMAT) << "</LI>"
		     << "<LI><B>Server Process ID:</B> " << Process::id() << "</LI>";
		   
		ostr << "</UL><HR><P>";
		ostr << htmlize(softwareVersion) << " at " << request.serverAddress().toString();
		ostr << "</P></DIV></BODY></HTML>";
	}
Beispiel #19
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
		/// Creates WebSocket and accepts the connection request from web client.
	{
		try
		{
			if (!_pWS)
			{
				_pWS = new WebSocket(request, response);
				Timespan ts(600, 0);
				_pWS->setReceiveTimeout(ts);
				_pWS->setSendTimeout(ts);
			}
			std::cout << std::endl << "WebSocket connection established." << std::endl << PROMPT;

			char buffer[1024];
			int n, count = 0;
			do
			{
				n = _pWS->receiveFrame(buffer, sizeof(buffer), _flags);
			}
			while (n > 0 || (_flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
				std::cout << "WebSocket connection closed." << std::endl;
		}
		catch (WebSocketException& exc)
		{
			std::cout << exc.displayText() << std::endl;
			switch (exc.code())
			{
			case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
				response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
				// fallthrough
			case WebSocket::WS_ERR_NO_HANDSHAKE:
			case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
			case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
				response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
				response.setContentLength(0);
				response.send();
				break;
			}
		}
	}
Beispiel #20
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setChunkedTransferEncoding(true);
		//response.setContentType("text/html");

		Path path(_file);
		if (File(path).exists())
		{
			std::string mime = "application/binary";
			std::string ext = path.getExtension();
			if (ext == "html" || ext == "htm" || ext == "js" || ext == "css" || ext == "xml")
				mime = "text/" + ext;
			
			response.sendFile(_file, mime);
		}
		else
		{
			response.setStatusAndReason(HTTPResponse::HTTP_NOT_FOUND);
			response.send();
		}
	}
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		try
		{
			WebSocket ws(request, response);
			printf("getReceiveTimeout %d\n", ws.getReceiveTimeout().totalSeconds());
			app.logger().information("WebSocket connection established.");
			char buffer[1024];
			int flags;
			int n;
			do
			{
				n = ws.receiveFrame(buffer, sizeof(buffer), flags);
				app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", n, unsigned(flags)));
				ws.sendFrame(buffer, n, flags);
			}
			while (n > 0 || (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
			app.logger().information("WebSocket connection closed.");
		}
		catch (WebSocketException& exc)
		{
			app.logger().log(exc);
			switch (exc.code())
			{
			case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
				response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
				// fallthrough
			case WebSocket::WS_ERR_NO_HANDSHAKE:
			case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
			case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
				response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
				response.setContentLength(0);
				response.send();
				break;
			}
		}

		app.logger().information("WebSocket connection terminated.");
	}
void client_request_handler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
  try
  {
    LOG("Request for client connection");
    
    // any exceptions thrown on WebSocket handshake or client validation
    // will lead to not registering client
    ws_t ws(new WebSocket(request, response));
    client_t h(new client(ws));
    h->init();
    
    CLIENTS.add(h);
  }
  catch (const WebSocketException& exc)
  {
    LOGERROR(exc.displayText());
    switch (exc.code())
    {
    case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
      response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
      // fallthrough
    case WebSocket::WS_ERR_NO_HANDSHAKE:
    case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
    case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
      response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
      response.setContentLength(0);
      response.send();
      break;
    }
  }
  catch (const Exception& e)
  {
    LOGERROR(e.displayText());
  }
  catch (const exception& e)
  {
    LOGERROR(e.what());
  }
}
 virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp){
   resp.setStatus(HTTPResponse::HTTP_OK);
   resp.setContentType("text/html");
   
   string fileName = req.getURI();
   
   ostream& out = resp.send();
   out << "<h1>Hello friend!</h1>"
       << "<p>Host: "     << req.getHost()   << "</p>"
       << "<p>Method: "   << req.getMethod() << "</p>"
       << "<p>Filename: " << req.getURI()    << "</p>";
   
   out.flush();
  
   /** Does not work
     StreamSocket strs = req.acceptConnection();
     SocketStream ostr(strs);
     std::string file("test.in");
     Poco::FileInputStream istr(file, std::ios::binary);
     StreamCopier::copyStream(istr, ostr);
   */
   
   cout << endl << "URI=" << req.getURI() << endl;  
 }
Beispiel #24
0
	void handleRequest (HTTPServerRequest &request, HTTPServerResponse &response)
	{
		Application& app = Application::instance();
		app.logger().information("Запрос от " + request.clientAddress().toString());
		
		
//		std::cout << request.getURI() << std::endl;
		
//		std::string filename(request.getURI().substr(0, request.getURI().find("?")));
//		app.logger().information("Файл: " + filename);
		
		/*
		if (opendir(std::string("www" + filename).c_str()) != NULL)
		{
			response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
			return;
		}
		
		if (filename != "balda.json")
		{
			ifstream fin(filename.c_str());
			
			if (fin.is_open())
			{
			
			}
			
			return;
		}
	*/	
		response.setChunkedTransferEncoding(true);
		std::ostream &ostr = response.send();

	//	try
	//	{
//			response.sendFile("/media/hdisk0/programming/project/anbal/2001/www" + filename, "text/plain");
//		}
	//	catch (...)
	//	{
//			ostr << "BAD" << std::endl;
	//	}
		
//		return;
	
		response.setContentType("text/javascript; charset=UTF-8");
		HTMLForm form(request, request.stream());
				
		if (!form.empty())
		{
			std::map < std::string , Glib::ustring > params;

			for (NameValueCollection::ConstIterator it = form.begin(); it != form.end(); ++it)
				params[it->first] = Glib::ustring(it->second);
			
			if (params["map"].length() != 25)
				return;
			
			std::vector < std::vector < SMyGUniChar > > char_map(5, std::vector < SMyGUniChar >(5));
			Glib::ustring u_map = params["map"];
			
			for (int i = 0, len = u_map.length(); i < len; ++i)
				char_map[i / 5][i % 5] = SMyGUniChar(u_map[i], i / 5, i % 5, u_map[i] == Glib::ustring(".")[0]);
			
			CBalda balda(*dictionary);
			std::vector < Glib::ustring > words = balda.calc(char_map);
			
			ostr << params["callback"] << "({\"word\": [\"" << cat(std::string("\", \""), words.begin(), words.end()) << "\"]})";
		}
	}
Beispiel #25
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		app.logger().information("Request from " + request.clientAddress().toString());

		MyPartHandler partHandler;
		HTMLForm form(request, request.stream(), partHandler);

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

		std::ostream& ostr = response.send();
		
		ostr <<
			"<html>\n"
			"<head>\n"
			"<title>POCO Form Server Sample</title>\n"
			"</head>\n"
			"<body>\n"
			"<h1>POCO Form 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>Request</h2><p>\n";
		ostr << "Method: " << request.getMethod() << "<br>\n";
		ostr << "URI: " << request.getURI() << "<br>\n";
		NameValueCollection::ConstIterator it = request.begin();
		NameValueCollection::ConstIterator end = request.end();
		for (; it != end; ++it)
		{
			ostr << it->first << ": " << it->second << "<br>\n";
		}
		ostr << "</p>";

		if (!form.empty())
		{
			ostr << "<h2>Form</h2><p>\n";
			it = form.begin();
			end = form.end();
			for (; it != end; ++it)
			{
				ostr << it->first << ": " << it->second << "<br>\n";
			}
			ostr << "</p>";
		}
		
		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";
	}
Beispiel #26
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		HTMLForm form(request, request.stream());

		response.setContentType("text/html");
		response.setChunkedTransferEncoding(true);
        
		std::ostream& ostr = response.send();
        
        URI requestURI(request.getURI());
        
		ostr << "<html><head><title>Echo HTTP Headers and HTML Form Information</title>"
		        "<link rel=\"stylesheet\" href=\"css/styles.css\" type=\"text/css\"/></head><body>"
		        "<div class=\"header\">"
				"<h1 class=\"category\">Open Service Platform</h1>"
				"<h1 class=\"title\">Echo HTTP Headers and HTML Form Information</H1>"
				"</div>"
		        "<div class=\"body\">";
        
		// echo the items available by method
		ostr << "<h2>Request</h2>"
		     << "<ul>"
		     << "<li><b>Method:</b> " << request.getMethod() << "</li>"
             << "<li><b>URI Path:</b> " << requestURI.getPath() << "</li>"
             << "<li><b>URI Query:</b> " << requestURI.getQuery() << "</li>"
             << "<li><b>HTTP Version:</b> " << request.getVersion() << "</li>"
             << "<li><b>Host:</b> " << request.getHost() << "</li>"
             << "<li><b>Content Type:</b> " << request.getContentType() << "</li>"
             << "<li><b>Chunked:</b> " << (request.getChunkedTransferEncoding() ? "true" : "false") << "</li>"
             << "<li><b>Keep Alive:</b> " << (request.getKeepAlive() ? "true" : "false") << "</li>"
             << "<li><b>Transfer Encoding:</b> " << request.getTransferEncoding() << "</li>"
             << "<li><b>Client Address:</b> " << request.clientAddress().toString() << "</li>";

        if (request.hasContentLength())
        {
            ostr << "<li><b>Content Length:</b> " << request.getContentLength64() << "</li>";
        }

		ostr << "</ul>";

        // echo the request headers
        {
            ostr << "<hr>"
                    "<h2>Request Headers</h2><ul>\n";

            NameValueCollection headers;
            NameValueCollection::ConstIterator itr(request.begin());
            NameValueCollection::ConstIterator itrEnd(request.end());
            
            for (; itr != itrEnd; ++itr)
            {
                ostr << "<li><b>" << htmlize(itr->first) << "</b>: " <<  htmlize(itr->second) << "</li>";
            }
            ostr << "</ul>";
        }

        // echo any cookies
        {
            NameValueCollection cookies;
            request.getCookies(cookies);

            if (!cookies.empty())
            {
                ostr << "<hr>";
                ostr << "<h2>Cookies</h2><ul>\n";

                NameValueCollection::ConstIterator itr(cookies.begin());
                NameValueCollection::ConstIterator itrEnd(cookies.end());
                
                for (; itr != itrEnd; ++itr)
                {
                    ostr << "<li><b>" << htmlize(itr->first) << "</b>: " <<  htmlize(itr->second) << "</li>";
                }
                ostr << "</ul>";
            }
        }
        
        // echo any form data (GETs or POSTs)
		if (!form.empty())
		{
            ostr << "<hr>"
			        "<h2>Form Data</h2><ul>\n";

			NameValueCollection::ConstIterator itr(form.begin());
			NameValueCollection::ConstIterator itrEnd(form.end());
			for (; itr != itrEnd; ++itr)
			{
				ostr << "<li><b>" << htmlize(itr->first) << "</b>: " << htmlize(itr->second) << "</li>\n";
			}
			ostr << "</ul>";
		}
        
        ostr << "<hr>"
             << "<h2>Response</h2>"
             << "<ul>"
		     << "<li><b>Status:</b> "  << response.getStatus()  << "</li>"
             << "<li><b>Reason:</b> "  << response.getReason()  << "</li>"
            << "</ul>";
        
        // echo the response headers
        {
            ostr << "<hr>"
                    "<h2>Response Headers</h2><ul>\n";
            
            NameValueCollection headers;
            NameValueCollection::ConstIterator itr(response.begin());
            NameValueCollection::ConstIterator itrEnd(response.end());
            
            for (; itr != itrEnd; ++itr)
            {
                ostr << "<li><b>" << htmlize(itr->first) << "</b>: " <<  htmlize(itr->second) << "</li>";
            }
            ostr << "</ul>";
        }
        
		ostr << "</div></body></html>";
	}
Beispiel #27
0
	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		response.setStatusAndReason(HTTPResponse::HTTP_NOT_FOUND);
		response.send();
	}