Ejemplo n.º 1
0
void EventHandler::processSessionVerify(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=5)return;
    uid_type uid;
    int status;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false) return;
    check = safeAtoi(check_cmd[2], status);
    if(check == false) return;
    if(status != 1){
        sendErrorResponse(e.fd_, CMD_LOGIN, ERROR_SESSIONID_ERROR);
        return;
    }
    User * user = safeGetUser(uid, CMD_LOGIN, e.fd_);
    if(user == NULL) {
        sendErrorResponse(e.fd_, CMD_LOGIN, ERROR_USER_DONOT_EXIST);
        return;
    }
    //user->nick_name_ = check_cmd[3];
    user->eqid_ = check_cmd[4];
    check = dh_->saveUserSInfo(user);
    if(check == false){
        sendErrorResponse(e.fd_, CMD_LOGIN, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    LOG4CXX_INFO(logger_, "login;"<<user->uid_);
    long long now = time(NULL);
    long long reaccess_check = now/86400 - user->create_time_/86400;
    if((reaccess_check>=1 && reaccess_check<=6)||reaccess_check == 13 || reaccess_check == 29 || reaccess_check == 59 || reaccess_check == 89){
        LOG4CXX_INFO(logger_, "reaccess;"<<reaccess_check<<";"<<user->uid_);
    }
    string res = buildSessionVerifyResponse();
    nh_->sendString(e.fd_, res);
    return;
}
Ejemplo n.º 2
0
void AbstractHTTPRequestHandler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
	_pRequest  = &request;
	_pResponse = &response;
	if (authenticate())
	{
		try
		{
			run();
		}
		catch (Poco::Exception& exc)
		{
			if (!response.sent())
			{
				sendErrorResponse(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.displayText());
			}
		}
		catch (std::exception& exc)
		{
			if (!response.sent())
			{
				sendErrorResponse(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.what());
			}
		}
	}
	else
	{
		sendErrorResponse(HTTPResponse::HTTP_UNAUTHORIZED, "");
	}
}
Ejemplo n.º 3
0
void HTTPServerConnection::run()
{
	std::string server = _pParams->getSoftwareVersion();
	HTTPServerSession session(socket(), _pParams);
	while (!_stopped && session.hasMoreRequests())
	{
		try
		{
			Poco::FastMutex::ScopedLock lock(_mutex);

			if (!_stopped)
			{
				HTTPServerResponseImpl response(session);
				HTTPServerRequestImpl request(response, session, _pParams);

				Poco::Timestamp now;
				response.setDate(now);
				response.setVersion(request.getVersion());
				response.setKeepAlive(_pParams->getKeepAlive() && request.getKeepAlive() && session.canKeepAlive());
				if (!server.empty())
					response.set("Server", server);
				try
				{
					std::auto_ptr<HTTPRequestHandler> pHandler(_pFactory->createRequestHandler(request));
					if (pHandler.get())
					{
						if (request.expectContinue())
							response.sendContinue();
						
						pHandler->handleRequest(request, response);
						session.setKeepAlive(_pParams->getKeepAlive() && response.getKeepAlive() && session.canKeepAlive());
					}
					else sendErrorResponse(session, HTTPResponse::HTTP_NOT_IMPLEMENTED);
				}
				catch (Poco::Exception&)
				{
					if (!response.sent())
					{
						try
						{
							sendErrorResponse(session, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
						}
						catch (...)
						{
						}
					}
					throw;
				}
			}
		}
		catch (NoMessageException&)
		{
			break;
		}
		catch (MessageException&)
		{
			sendErrorResponse(session, HTTPResponse::HTTP_BAD_REQUEST);
		}
	}
}
Ejemplo n.º 4
0
void EventHandler::processRegister(EventCmd &e,vector<string> &check_cmd)
{
    if(check_cmd.size()!=4) return;
    //1.eqid 2.name 3.passwd
    if(check_cmd[1].size() == 0 || check_cmd[2].size() == 0 || check_cmd[3].size() == 0) return;
    if(check_cmd[1].size()>32 || check_cmd[2].size()>32 || check_cmd[3].size()>32) return;
    if(checkString(check_cmd[1])==false || checkString(check_cmd[2])==false || checkString(check_cmd[3]) == false){
        LOG4CXX_WARN(logger_, "check string false:"<<check_cmd[1]<<";"<<check_cmd[2]<<";"<<check_cmd[3]);
    }
    bool check = false;
    check = dh_->usernameHasBeenUsed(check_cmd[2]);
    if(check == true){
        sendErrorResponse(e.fd_, CMD_REGISTER,ERROR_USERNAME_HAS_BEEN_USED);
        return;
    }else{
        if(dh_->db_error_ != 0){
            sendErrorResponse(e.fd_, CMD_REGISTER, ERROR_SYSTEM_CRITICAL_ERROR);
            return;
        }
        long long user_id;
        check = dh_->registerNewUser(check_cmd[2],check_cmd[3],check_cmd[1],user_id);
        if(check == true){
            LOG4CXX_INFO(logger_, "register;"<<user_id);
            string res = buildRegisterResponse();
            nh_->sendString(e.fd_, res);
            return;
        }else{
            sendErrorResponse(e.fd_, CMD_REGISTER,ERROR_SYSTEM_CRITICAL_ERROR);
            return;
        }
    }
    //string res = buildRegisterResponse();
    //nh_->sendString(e.fd_, res);
    return;
}
Ejemplo n.º 5
0
void EventHandler::processPaymentAddDiamondResponse(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=7)return;
    int succ = 0;
    bool check = safeAtoi(check_cmd[1], succ);
    if(check == false) return;
    uid_type uid;
    string tran_id;
    check = safeAtoll(check_cmd[2], uid);
    if(check == false) return;
    tran_id = check_cmd[4];
    string product_id = check_cmd[3];
    int diamond = 0;
    check = safeAtoi(check_cmd[5], diamond);
    if(check == false) return;
    int dst_fd = 0;
    check = safeAtoi(check_cmd[6], dst_fd);
    if(check == false) return;
    
    PaymentInfo *pi = NULL;
    check = dh_->loadPayment(tran_id, pi);
    if(check == false){
        sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(pi == NULL){
        sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_WRONG_TIME);
        return;
    }else{
        if(uid != pi->uid_ || product_id != pi->product_id_ || tran_id != pi->tran_id_){
            delete pi;
            //sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH);
            sendErrorResponseFroPayment(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH, tran_id);
            return;
        }
        if(succ != 0){
            delete pi;
            check = dh_->savePaymentStatus(tran_id, PAYMENT_STATUS_VERIFY_SUCC);
            if(check == false){
                sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
                return;
            }else{
                sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_WRONG_TIME);
                return;
            }
        }else{
            check = dh_->savePaymentStatus(tran_id, PAYMENT_STATUS_ADDCMD_SUCC);
            if(check ==false){
                sendErrorResponse(dst_fd, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
                return;
            }else{
                string res = buildPaymentVerifyReceivedResponse(uid,product_id,tran_id,diamond);
                nh_->sendString(dst_fd, res);
                return;
            }
        }
    }
    return;
}
Ejemplo n.º 6
0
void EventHandler::processLogin(EventCmd &e, vector<string> &check_cmd)
{
    cout<<check_cmd[1]<<endl;
    if(check_cmd.size()!=4) return;
    if(check_cmd[1].size() == 0 || check_cmd[2].size() == 0 || check_cmd[3].size() == 0) return;
    if(check_cmd[1].size()>32 || check_cmd[2].size()>32 || check_cmd[3].size() > 32) return;
    if(checkString(check_cmd[1])==false || checkString(check_cmd[2])==false || checkString(check_cmd[3]) == false){
        LOG4CXX_WARN(logger_, "check string false:"<<check_cmd[1]<<";"<<check_cmd[2]<<";"<<check_cmd[3]);
    }
    UserBasicInfo ubi;
    bool check = dh_->getUserBasicInfo(check_cmd[2], check_cmd[3], ubi);
    if(check == false){
        if(dh_->db_error_ != 0){
            sendErrorResponse(e.fd_, CMD_LOGIN,ERROR_SYSTEM_CRITICAL_ERROR);
            return;
        }else{
            sendErrorResponse(e.fd_, CMD_LOGIN,ERROR_USER_OR_PASSWD_WRONG);
            return;
        }
    }else{
        /*if(check_cmd[3] == ubi.eqid_){
         string res = buildLoginResponse(ubi.uid_, -1);
         nh_->sendString(e.fd_, res);
         return;
         }else{
         check = dh_->changeEquipment(ubi.uid_, check_cmd[3]);
         if(dh_->db_error_ !=0||check == false){
         sendErrorResponse(e.fd_, CMD_LOGIN,ERROR_SYSTEM_CRITICAL_ERROR);
         return;
         }else{
         string res = buildLoginResponse(ubi.uid_, getAuthorizeCode(ubi.uid_));
         nh_->sendString(e.fd_, res);
         return;
         }
         }*/
        if(check_cmd[1]!= ubi.eqid_){
            check = dh_->changeEquipment(ubi.uid_, check_cmd[1]);
            if(dh_->db_error_ !=0||check == false){
                sendErrorResponse(e.fd_, CMD_LOGIN,ERROR_SYSTEM_CRITICAL_ERROR);
                return;
            }
        }
        LOG4CXX_INFO(logger_, "login;"<<ubi.uid_);
        long long now = time(NULL);
        long long reaccess_check = now/86400 - ubi.create_time_/86400;
        if((reaccess_check>=1 && reaccess_check<=6)||reaccess_check == 13 || reaccess_check == 29 || reaccess_check == 59 || reaccess_check == 89){
            LOG4CXX_INFO(logger_, "reaccess;"<<reaccess_check<<";"<<ubi.uid_);
        }
        string res = buildLoginResponse(ubi.uid_, getAuthorizeCode(ubi.uid_));
        nh_->sendString(e.fd_, res);
        return;
    }
}
Ejemplo n.º 7
0
status_t WifiDisplaySource::onPlayRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    int32_t playbackSessionID;
    sp<PlaybackSession> playbackSession =
        findPlaybackSession(data, &playbackSessionID);

    if (playbackSession == NULL) {
        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
        return ERROR_MALFORMED;
    }

    if (mState != AWAITING_CLIENT_PLAY
     && mState != PAUSED_TO_PLAYING
     && mState != PAUSED) {
        ALOGW("Received PLAY request but we're in state %d", mState);

        sendErrorResponse(
                sessionID, "455 Method Not Valid in This State", cseq);

        return INVALID_OPERATION;
    }

    ALOGI("Received PLAY request.");
    if (mPlaybackSessionEstablished) {
        finishPlay();
    } else {
        ALOGI("deferring PLAY request until session established.");
    }

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);
    response.append("Range: npt=now-\r\n");
    response.append("\r\n");

    status_t err = mNetSession->sendRequest(sessionID, response.c_str());

    if (err != OK) {
        return err;
    }

    if (mState == PAUSED_TO_PLAYING || mPlaybackSessionEstablished) {
        mState = PLAYING;
        return OK;
    }

    CHECK_EQ(mState, AWAITING_CLIENT_PLAY);
    mState = ABOUT_TO_PLAY;

    return OK;
}
void AudioHTTPServer::startStreamingResponse( QxtWebRequestEvent* event, sp_track* track )
{
    // yay we gots a track
//    qDebug() << QThread::currentThreadId() << "We got a track!" << sp_track_name( track ) << sp_artist_name( sp_track_artist( track, 0 ) ) << sp_track_duration( track );
    uint duration = sp_track_duration( track );

    sp_error err = sp_session_player_load( SpotifySession::getInstance()->Session(), track );
    if( err != SP_ERROR_OK ) {
        qWarning() << QThread::currentThreadId() << "Failed to start track from spotify :(" << sp_error_message( err );
        sendErrorResponse( event );
        return;
    }

//    qDebug() << QThread::currentThreadId() << "Starting to play!";
    sp_session_player_play( SpotifySession::getInstance()->Session(), true );
    SpotifySession::getInstance()->Playback()->startPlaying();

    qDebug() << "Getting iodevice...";
    spotifyiodev_ptr iodev = SpotifySession::getInstance()->Playback()->getIODeviceForNewTrack( duration );
//    qDebug()  << QThread::currentThreadId() << "Got iodevice to send:" << iodev << iodev.isNull() << iodev->isSequential() << iodev->isReadable();
    QxtWebPageEvent* wpe = new QxtWebPageEvent( event->sessionID, event->requestID, iodev );
    wpe->streaming = true;
    wpe->contentType = "audio/basic";
    postEvent( wpe );
}
Ejemplo n.º 9
0
void HttpSocket::handleNewConnection()
{
    DBUG;
    while (hasPendingConnections()) {
        QTcpSocket *socket = nextPendingConnection();

        // prevent clients from sending too much data
        socket->setReadBufferSize(constMaxBuffer);

        static const QLatin1String constIpV6Prefix("::ffff:");

        QString peer=socket->peerAddress().toString();
        QString ifaceAddress=serverAddress().toString();
        const bool hostOk=peer==ifaceAddress || peer==mpdAddr || peer==(constIpV6Prefix+mpdAddr) ||
                          peer==QLatin1String("127.0.0.1") || peer==(constIpV6Prefix+QLatin1String("127.0.0.1"));

        DBUG << "peer:" << peer << "mpd:" << mpdAddr << "iface:" << ifaceAddress << "ok:" << hostOk;
        if (!hostOk) {
            sendErrorResponse(socket, 400);
            socket->close();
            DBUG << "Not from valid host";
            return;
        }

        connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
    }
}
Ejemplo n.º 10
0
status_t WifiDisplaySource::onSetParameterRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    int32_t playbackSessionID;
    sp<PlaybackSession> playbackSession =
        findPlaybackSession(data, &playbackSessionID);

    if (playbackSession == NULL) {
        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
        return ERROR_MALFORMED;
    }

    if (strstr(data->getContent(), "wfd_idr_request\r\n")) {
        playbackSession->requestIDRFrame();
    }

    playbackSession->updateLiveness();

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);
    response.append("\r\n");

    status_t err = mNetSession->sendRequest(sessionID, response.c_str());
    return err;
}
Ejemplo n.º 11
0
status_t WifiDisplaySource::onTeardownRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    ALOGI("Received TEARDOWN request.");

    int32_t playbackSessionID;
    sp<PlaybackSession> playbackSession =
        findPlaybackSession(data, &playbackSessionID);

    if (playbackSession == NULL) {
        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
        return ERROR_MALFORMED;
    }

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);
    response.append("Connection: close\r\n");
    response.append("\r\n");

    mNetSession->sendRequest(sessionID, response.c_str());

    if (mState == AWAITING_CLIENT_TEARDOWN) {
        CHECK(mStopReplyID != NULL);
        finishStop();
    } else {
        mClient->onDisplayError(IRemoteDisplayClient::kDisplayErrorUnknown);
    }

    return OK;
}
Ejemplo n.º 12
0
void EventHandler::processCreateUser(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=5)return;
    uid_type uid;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false) return;
    if(check_cmd[3].size() == 0 || check_cmd[3].size()>32) return;
    if(checkString(check_cmd[3]) == false) return;
    int authorize_code;
    check = safeAtoi(check_cmd[4], authorize_code);
    if(check == false) return;
    if(authorize_code != getAuthorizeCode(uid)){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_AUTHORIZE_CODE_WRONG);
        return;
    }
    User * user = dh_->getUser(uid);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(user != NULL){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_USER_ALREADY_REGISTERED);
        delete user;
        return;
    }
    /*check = dh_->checkNick(check_cmd[3]);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(check == false){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_NICKNAME_USED);
        return;
    }*/
    check = dh_->createUser(uid,check_cmd);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(check == false){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_CREATE_USER_FAIL);
        return;
    }
    string res = buildCreateUserResponse();
    nh_->sendString(e.fd_, res);
    return;
}
Ejemplo n.º 13
0
int eraseMtdDevice( char* mtdblock )
{
    int fd;
    mtd_info_t mtdinfo;
    erase_info_t eraseinfo;
	char mtddevice[256];
	char vfdtext[17];

	sprintf( mtddevice, "/dev/mtd%s", mtdblock );

	// Open the mtdblock
	if ( ( fd = open( mtddevice, O_RDWR ) ) < 0 )
	{
		sendErrorResponse( sock, E_COULD_NOT_OPEN_MTDBLOCK, 0, 0 );
		close( sock );
		exit( EXIT_FAILURE );
	}
	
	// Retrieve some info about our mtddevice	
	if( ioctl( fd, MEMGETINFO, &mtdinfo ) != 0 ) {
		sendErrorResponse( sock, E_COULD_NOT_GET_MTDINFO, 0, 0 );
		exit( EXIT_FAILURE );
	}

	// Erase the rom block by block
	eraseinfo.length = mtdinfo.erasesize;
	for ( eraseinfo.start = 0; eraseinfo.start < mtdinfo.size; eraseinfo.start += mtdinfo.erasesize ) {
		// Update the status text on the display
		sprintf( vfdtext, "ERASE %s %i", mtdblock, ((eraseinfo.start*100)/mtdinfo.size) );
		setVfdText( vfdtext );

		// Erase the current block
		if( ioctl( fd, MEMERASE, &eraseinfo ) != 0 )
		{
			sprintf( vfdtext, "ERROR" );
			setVfdText( vfdtext );
			sendErrorResponse( sock, E_ERASING_MTDBLOCK_FAILED, 0, 0 );
			exit( EXIT_FAILURE );
		}
	}

	close( fd );

	return mtdinfo.size;
}
Ejemplo n.º 14
0
	void RtBroker::issueOrder(BrkLib::BrokerSession &session, Order const& order)
	{
		BrkLib::RtSession &rtsession = (BrkLib::RtSession &)session;

		bool result = true;
		CppUtils::String reason;
		

		try {
			
			if (!order.ID_m.isValid()) {
				THROW_BRK(getName().c_str(), "exc_InvalidOrderID", "ctx_issueOrder", "");
			}

			//
			if (order.orderType_m & BrkLib::OP_HANDSHAKE) {
				// handshake
				BrokerResponseOrder brokerResponse;

				processHandshake(order, rtsession, brokerResponse);
				onBrokerResponseArrived(rtsession, brokerResponse);
			}
			else if (order.orderType_m & BrkLib::OP_GET_SYMBOL_METAINFO) {

				BrokerResponseMetaInfo brespMinfo;

				getSymbolMetainfo(order, rtsession, brespMinfo);
				onBrokerResponseArrived(rtsession, brespMinfo);
			}
			else {
				engine_m.onNewOrderArrived( order, rtsession );
			}
		}
		catch(CppUtils::Exception& e)
		{
			result = false;
			reason.append("Exception occured: ");
		
			reason += EXC2STR(e);
		}
		catch(...)
		{
			result = false;
			reason.append("Unknown exception occured");
		}

		if (!result) {
			// TODO
			BrokerResponseOrder brokerResponse;
			BRK_LOG(getName().c_str(), BRK_MSG_ERROR, RTBROKER, "Error occured: " << reason);
			
			sendErrorResponse(order,rtsession, brokerResponse, -1, reason );
			onBrokerResponseArrived(rtsession, brokerResponse);
		}

	}
Ejemplo n.º 15
0
void EventHandler::processCreateUser(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=4)return;
    uid_type uid;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false) return;
    if(check_cmd[2].size() == 0 || check_cmd[2].size()>32) return;
    if(check_cmd[3].size() == 0 || check_cmd[3].size()>32) return;
    if(checkString(check_cmd[2]) == false || checkString(check_cmd[3]) == false) return;
    User * user = dh_->getUser(uid);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(user != NULL){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_USER_ALREADY_REGISTERED);
        return;
    }
    /*check = dh_->checkNick(check_cmd[3]);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(check == false){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_NICKNAME_USED);
        return;
    }*/
    check = dh_->createUser(uid,check_cmd);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(check == false){
        sendErrorResponse(e.fd_, CMD_CREATEUSER, ERROR_CREATE_USER_FAIL);
        return;
    }
    LOG4CXX_INFO(logger_, "register;"<<uid);
    string res = buildCreateUserResponse();
    nh_->sendString(e.fd_, res);
    return;
}
//------------------------------------------------------------------------------
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;
    }
}
Ejemplo n.º 17
0
void EventHandler::processAuthorize(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=4) return;
    if(check_cmd[1].size() == 0 || check_cmd[2].size() == 0) return;
    if(check_cmd[1].size()>32 || check_cmd[2].size()>32) return;
    if(checkString(check_cmd[2])==false){
        LOG4CXX_WARN(logger_, "check string false:"<<check_cmd[2]);
    }
    uid_type uid ;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false) return;
    int authorize_code;
    check = safeAtoi(check_cmd[3], authorize_code);
    if(check == false) return;
    User * user = dh_->getUser(uid);
    if(dh_->db_error_ != 0){
        sendErrorResponse(e.fd_, CMD_AUTHORIZE,ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    if(user == NULL){
        sendErrorResponse(e.fd_, CMD_AUTHORIZE,ERROR_USER_DONOT_EXIST);
        return;
    }
    if(authorize_code != getAuthorizeCode(uid)){
        sendErrorResponse(e.fd_, CMD_AUTHORIZE, ERROR_AUTHORIZE_CODE_WRONG);
        return;
    }
    user->eqid_ = check_cmd[2];
    user->dirty_ = true;
    check = dh_->saveEquipmentId(user);
    if(dh_->db_error_ != 0 || check == false){
        sendErrorResponse(e.fd_, CMD_AUTHORIZE,ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    string res = buildAuthorizeResponse();
    nh_->sendString(e.fd_, res);
    return;
}
Ejemplo n.º 18
0
void AudioHTTPServer::sid( QxtWebRequestEvent* event, QString a )
{
    qDebug() << QThread::currentThreadId() << "HTTP" << event->url.toString() << a;

    if( !SpotifySession::getInstance()->Playback()->trackIsOver() ) {
        SpotifySession::getInstance()->Playback()->endTrack();
    }

    // the requested track
    QString uid = a.replace( ".wav", "");
//    qDebug() << QThread::currentThreadId() << "Beginning to stream requested track:" << uid;
    if( uid.isEmpty() || !sApp->hasLinkFromTrack( uid ) ) {
        qWarning() << "Did not find spotify track UID in our list!" << uid;
        sendErrorResponse( event );

        return;
    }

    // get the sp_track
    sp_link* link = sApp->linkFromTrack( uid );

    sp_track* track = sp_link_as_track( link );
    if( !track ) {
        qWarning() << QThread::currentThreadId() << "Uh oh... got null track from link :(" << sp_link_type( link );
        sendErrorResponse( event );
        return;
    }
    if( !sp_track_is_loaded( track ) ) {
        qWarning() << QThread::currentThreadId() << "uh oh... track not loaded yet! Asked for:" << sp_track_name( track );
        m_savedEvent = event;
        m_savedTrack = track;
        QTimer::singleShot( 250, this, SLOT( checkForLoaded() ) );
        return;

    } else {
        startStreamingResponse( event, track );
    }
}
Ejemplo n.º 19
0
	void RootRequestHandler::run()
	{
		if (request().getMethod() == HTTPRequest::HTTP_GET || request().getMethod() == HTTPRequest::HTTP_HEAD)
		{
			response().setChunkedTransferEncoding(true);
			response().setContentType("application/json");

			std::ostream& out = response().send();
			if (request().getMethod() == HTTPRequest::HTTP_GET)
			{
				out << "{\"valid\":true}";
			}
		}
		else
		{
			sendErrorResponse(HTTPResponse::HTTP_METHOD_NOT_ALLOWED, "");
		}
	}
/* Checks through all existing commands if one match returns NULL pointer otherwise */
SerialCommand * SerialProtocolHandler::parseLine() {
	//read line till C char
	int var;

	//All commands starts with GET/SET <OBJECT>
	for (int i = 0; i < AVAILABLE_COMMANDS_COUNT; i++){
		if (cmdList[i]->parse(inBuffer, IN_BUFFER_SIZE)) {
			cleanAndResetInBuffer();
			return cmdList[i];
		}
	}

	if (strchr((const char*)inBuffer, 10) != NULL) {
		sendErrorResponse(0, (const char *)F("No valid command"));
		cleanAndResetInBuffer();
	}

	return NULL;
}
status_t WifiDisplaySource::onPlayRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    int32_t playbackSessionID;
    sp<PlaybackSession> playbackSession =
        findPlaybackSession(data, &playbackSessionID);

    if (playbackSession == NULL) {
        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
        return ERROR_MALFORMED;
    }

    ALOGI("Received PLAY request.");

    status_t err = playbackSession->play();
    CHECK_EQ(err, (status_t)OK);

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);
    response.append("Range: npt=now-\r\n");
    response.append("\r\n");

    err = mNetSession->sendRequest(sessionID, response.c_str());

    if (err != OK) {
        return err;
    }

    if (mState == PAUSED_TO_PLAYING) {
        mState = PLAYING;
        return OK;
    }

    playbackSession->finishPlay();

    CHECK_EQ(mState, AWAITING_CLIENT_PLAY);
    mState = ABOUT_TO_PLAY;

    return OK;
}
Ejemplo n.º 22
0
status_t WifiDisplaySource::onPauseRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    int32_t playbackSessionID;
    sp<PlaybackSession> playbackSession =
        findPlaybackSession(data, &playbackSessionID);

    if (playbackSession == NULL) {
        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
        return ERROR_MALFORMED;
    }

    ALOGI("Received PAUSE request.");

    if (mState != PLAYING_TO_PAUSED && mState != PLAYING) {
        return INVALID_OPERATION;
    }

    status_t err = playbackSession->pause();
    CHECK_EQ(err, (status_t)OK);

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);
    response.append("\r\n");

    err = mNetSession->sendRequest(sessionID, response.c_str());

    if (err != OK) {
        return err;
    }

    mState = PAUSED;

    return err;
}
Ejemplo n.º 23
0
status_t WifiDisplaySource::onReceiveClientData(const sp<AMessage> &msg) {
    int32_t sessionID;
    CHECK(msg->findInt32("sessionID", &sessionID));

    sp<RefBase> obj;
    CHECK(msg->findObject("data", &obj));

    sp<ParsedMessage> data =
        static_cast<ParsedMessage *>(obj.get());

    ALOGV("session %d received '%s'",
          sessionID, data->debugString().c_str());

    AString method;
    AString uri;
    data->getRequestField(0, &method);

    int32_t cseq;
    if (!data->findInt32("cseq", &cseq)) {
        sendErrorResponse(sessionID, "400 Bad Request", -1 /* cseq */);
        return ERROR_MALFORMED;
    }

    if (method.startsWith("RTSP/")) {
        // This is a response.

        ResponseID id;
        id.mSessionID = sessionID;
        id.mCSeq = cseq;

        ssize_t index = mResponseHandlers.indexOfKey(id);

        if (index < 0) {
            ALOGW("Received unsolicited server response, cseq %d", cseq);
            return ERROR_MALFORMED;
        }

        HandleRTSPResponseFunc func = mResponseHandlers.valueAt(index);
        mResponseHandlers.removeItemsAt(index);

        status_t err = (this->*func)(sessionID, data);

        if (err != OK) {
            ALOGW("Response handler for session %d, cseq %d returned "
                  "err %d (%s)",
                  sessionID, cseq, err, strerror(-err));

            return err;
        }

        return OK;
    }

    AString version;
    data->getRequestField(2, &version);
    if (!(version == AString("RTSP/1.0"))) {
        sendErrorResponse(sessionID, "505 RTSP Version not supported", cseq);
        return ERROR_UNSUPPORTED;
    }

    status_t err;
    if (method == "OPTIONS") {
        err = onOptionsRequest(sessionID, cseq, data);
    } else if (method == "SETUP") {
        err = onSetupRequest(sessionID, cseq, data);
    } else if (method == "PLAY") {
        err = onPlayRequest(sessionID, cseq, data);
    } else if (method == "PAUSE") {
        err = onPauseRequest(sessionID, cseq, data);
    } else if (method == "TEARDOWN") {
        err = onTeardownRequest(sessionID, cseq, data);
    } else if (method == "GET_PARAMETER") {
        err = onGetParameterRequest(sessionID, cseq, data);
    } else if (method == "SET_PARAMETER") {
        err = onSetParameterRequest(sessionID, cseq, data);
    } else {
        sendErrorResponse(sessionID, "405 Method Not Allowed", cseq);

        err = ERROR_UNSUPPORTED;
    }

    return err;
}
Ejemplo n.º 24
0
void EventHandler::processPaymentVerifyComplete(EventCmd &e, vector<string> &check_cmd)
{
    if(check_cmd.size()!=6) return;
    uid_type uid;
    int status = 0;
    int server_id = 0;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false) return;
    check = safeAtoi(check_cmd[2], status);
    if(check == false) return;
    string * tran_id = new string(check_cmd[4]);
    string * product_id = new string(check_cmd[3]);
    check = safeAtoi(check_cmd[5], server_id);
    if(check == false) return;
    
    PaymentInfo * pi = NULL;
    check = dh_->loadPayment(*tran_id, pi);
    if(check == false){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    
    if(pi == NULL){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_WRONG_TIME);
        return;
    }else{
        server_id = pi->server_id_;
        if(uid != pi->uid_ || *product_id != pi->product_id_){
            delete pi;
            sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH);
            return;
        }
        if(pi!=NULL)
            delete pi;
        if(status != 0){
            check = dh_->savePaymentStatus(*tran_id, PAYMENT_STATUS_REQUEST_RECEIVED);
            if(check == false){
                sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
                return;
            }else{
                sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_WRONG_TIME);
                return;
            }
        }else{
            check = dh_->savePaymentStatus(*tran_id, PAYMENT_STATUS_ADDCMD_SEND);
            if(check == false){
                sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
                return;
            }else{
                pthread_t tid;
                struct PaymentAdd *pa;
                pa = (struct PaymentAdd *) malloc (sizeof(PaymentAdd));
                if(pa == NULL) {
                    sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
                    return;
                }
                pa->eq = this->eq_;
                pa->fd_ = e.fd_;
                pa->product_id = product_id;
                pa->server_id = server_id;
                pa->tran_id = tran_id;
                pa->uid = uid;
                pthread_create(&tid,NULL,paymentAdd,(void *)pa);
            }
        }
    }
    return;
}
Ejemplo n.º 25
0
void EventHandler::processPaymentVerify(EventCmd &e,vector<string> &check_cmd)
{
    //if(check_cmd.size()!=4) return;
    /*    uid_type uid;
     bool check = safeAtoll(check_cmd[1], uid);
     if(check == false) return;
     User * user = safeGetUser(uid, CMD_PAYMENTVERIFY, e.fd_, check_cmd[2]);
     if(user == NULL) return;
     string input = e.cmd_.substr(e.cmd_.find('{'));
     if(input.size()>=3000){
     sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
     return;
     }
     char * outputc = (char * ) malloc (4*((input.length()+2)/3));
     if(outputc == NULL){
     sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
     return;
     }
     base64_encode((unsigned char * )input.c_str(), (int)input.length(),
     (unsigned char  *)outputc, (int)4*((input.length()+2)/3));
     string output = string(outputc,(int)4*((input.length()+2)/3));
     free(outputc);
     string * test = new string("{\"receipt-data\":\"" + output + "\"}");
     //pp->verify_info = &check_cmd[3];
     pp->verify_info = test;
     pthread_create(&tid,NULL,verify,(void *)pp);
     */
    
    //read params
    uid_type uid;
    int server_id;
    string product_id;
    bool check = safeAtoll(check_cmd[1], uid);
    if(check == false)return;
    if(check_cmd[3].size()>64 ||check_cmd[3].size()<=0||check_cmd[5].size()>64 ||check_cmd[5].size()<=0) return;
    //string tran_id = check_cmd[3];
    string * tran_id = new string(check_cmd[3]);
    check = safeAtoi(check_cmd[4], server_id);
    if(check == false) return;
    product_id = check_cmd[5];
    
    sconfig * sc = game_config.getSconfig(server_id);
    if(sc == NULL){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_INFO_ERROR);
        return;
    }
    if(game_config.payment_.find(product_id) == game_config.payment_.end()){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_INFO_ERROR);
        return;
    }
    
    //try to load
    PaymentInfo *pi = NULL;
    check = dh_->loadPayment(*tran_id, pi);
    if(check == false){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    
    string input = e.cmd_.substr(e.cmd_.find('{'));
    if(input.size()>=3000){
        //sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    char * outputc = (char *) malloc (4*((input.length()+2)/3));
    if(outputc == NULL){
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    base64_encode((unsigned char * )input.c_str(), (int)input.length(),
                  (unsigned char  *)outputc, (int)4*((input.length()+2)/3));
    string output = string(outputc,(int)4*((input.length()+2)/3));
    free(outputc);
    //string * test = new string("{\"receipt-data\":\"" + output + "\"}");
    
    //check
    string checkcode = MDString(output.c_str());
    if(pi == NULL){
        pi = new PaymentInfo(*tran_id,product_id,checkcode);
        if(pi == NULL){
            sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
            return;
        }
        //pi->tran_id_ = tran_id;
        pi->uid_ = uid;
        pi->pay_time_ = time(NULL);
        //pi->product_id_ = product_id;
        pi->server_id_ = server_id;
        pi->status_ = PAYMENT_STATUS_REQUEST_RECEIVED;
        pi->status_ = PAYMENT_STATUS_VERIFY_SEND;
        //pi->check_info_ = checkcode;
        
        check = dh_->addNewPayment(pi);
        if(check == false || dh_->db_error_ != 0){
            delete pi;
            sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
            return;
        }
        
    }else{
        if(uid != pi->uid_ || server_id_ != pi->server_id_ || product_id != pi->product_id_ || checkcode != pi->check_info_){
            delete pi;
            //sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH);
            sendErrorResponseFroPayment(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH, (*tran_id));
            return;
        }
        if(pi->status_ == PAYMENT_STATUS_REQUEST_RECEIVED || pi->status_ == PAYMENT_STATUS_VERIFY_SUCC){
        }else if(pi->status_ == PAYMENT_STATUS_VERIFY_SEND
                 || pi->status_ == PAYMENT_STATUS_ADDCMD_SEND){
            delete pi;
            sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_WRONG_TIME);
            return;
        }else if(pi->status_ == PAYMENT_STATUS_REQUEST_REFUSED || pi->status_ == PAYMENT_STATUS_ADDCMD_SUCC){
            delete  pi;
            //sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_TRADE_COMPLETE);
            sendErrorResponseFroPayment(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_PAYMENT_TRADE_COMPLETE, (*tran_id));
            return;
        }
    }
    if(pi!=NULL){
        delete pi;
    }
    string * test = new string("{\"receipt-data\":\"" + output + "\"}");
    pthread_t tid;
    struct PaymentParam *pp;
    pp = (struct PaymentParam *) malloc (sizeof(PaymentParam));
    if(pp == NULL) {
        sendErrorResponse(e.fd_, CMD_PAYMENTVERIFYRECEIVED, ERROR_SYSTEM_CRITICAL_ERROR);
        return;
    }
    pp->uid = uid;
    pp->tran_id = tran_id;
    pp->eq = eq_;
    pp->fd_ = e.fd_;
    pp->verify_info = test;
    pp->server_id = server_id;
    pthread_create(&tid,NULL,verify,(void *)pp);
    return;
}
Ejemplo n.º 26
0
status_t WifiDisplaySource::onSetupRequest(
        int32_t sessionID,
        int32_t cseq,
        const sp<ParsedMessage> &data) {
    CHECK_EQ(sessionID, mClientSessionID);
    if (mClientInfo.mPlaybackSessionID != -1) {
        // We only support a single playback session per client.
        // This is due to the reversed keep-alive design in the wfd specs...
        sendErrorResponse(sessionID, "400 Bad Request", cseq);
        return ERROR_MALFORMED;
    }

    AString transport;
    if (!data->findString("transport", &transport)) {
        sendErrorResponse(sessionID, "400 Bad Request", cseq);
        return ERROR_MALFORMED;
    }

    RTPSender::TransportMode rtpMode = RTPSender::TRANSPORT_UDP;

    int clientRtp, clientRtcp;
    if (transport.startsWith("RTP/AVP/TCP;")) {
        AString interleaved;
        if (ParsedMessage::GetAttribute(
                    transport.c_str(), "interleaved", &interleaved)
                && sscanf(interleaved.c_str(), "%d-%d",
                          &clientRtp, &clientRtcp) == 2) {
            rtpMode = RTPSender::TRANSPORT_TCP_INTERLEAVED;
        } else {
            bool badRequest = false;

            AString clientPort;
            if (!ParsedMessage::GetAttribute(
                        transport.c_str(), "client_port", &clientPort)) {
                badRequest = true;
            } else if (sscanf(clientPort.c_str(), "%d-%d",
                              &clientRtp, &clientRtcp) == 2) {
            } else if (sscanf(clientPort.c_str(), "%d", &clientRtp) == 1) {
                // No RTCP.
                clientRtcp = -1;
            } else {
                badRequest = true;
            }

            if (badRequest) {
                sendErrorResponse(sessionID, "400 Bad Request", cseq);
                return ERROR_MALFORMED;
            }

            rtpMode = RTPSender::TRANSPORT_TCP;
        }
    } else if (transport.startsWith("RTP/AVP;unicast;")
            || transport.startsWith("RTP/AVP/UDP;unicast;")) {
        bool badRequest = false;

        AString clientPort;
        if (!ParsedMessage::GetAttribute(
                    transport.c_str(), "client_port", &clientPort)) {
            badRequest = true;
        } else if (sscanf(clientPort.c_str(), "%d-%d",
                          &clientRtp, &clientRtcp) == 2) {
        } else if (sscanf(clientPort.c_str(), "%d", &clientRtp) == 1) {
            // No RTCP.
            clientRtcp = -1;
        } else {
            badRequest = true;
        }

        if (badRequest) {
            sendErrorResponse(sessionID, "400 Bad Request", cseq);
            return ERROR_MALFORMED;
        }
#if 1
    // The older LG dongles doesn't specify client_port=xxx apparently.
    } else if (transport == "RTP/AVP/UDP;unicast") {
        clientRtp = 19000;
        clientRtcp = -1;
#endif
    } else {
        sendErrorResponse(sessionID, "461 Unsupported Transport", cseq);
        return ERROR_UNSUPPORTED;
    }

    int32_t playbackSessionID = makeUniquePlaybackSessionID();

    sp<AMessage> notify = new AMessage(kWhatPlaybackSessionNotify, this);
    notify->setInt32("playbackSessionID", playbackSessionID);
    notify->setInt32("sessionID", sessionID);

    sp<PlaybackSession> playbackSession =
        new PlaybackSession(
                mOpPackageName, mNetSession, notify, mInterfaceAddr, mHDCP, mMediaPath.c_str());

    looper()->registerHandler(playbackSession);

    AString uri;
    data->getRequestField(1, &uri);

    if (strncasecmp("rtsp://", uri.c_str(), 7)) {
        sendErrorResponse(sessionID, "400 Bad Request", cseq);
        return ERROR_MALFORMED;
    }

    if (!(uri.startsWith("rtsp://") && uri.endsWith("/wfd1.0/streamid=0"))) {
        sendErrorResponse(sessionID, "404 Not found", cseq);
        return ERROR_MALFORMED;
    }

    RTPSender::TransportMode rtcpMode = RTPSender::TRANSPORT_UDP;
    if (clientRtcp < 0) {
        rtcpMode = RTPSender::TRANSPORT_NONE;
    }

    status_t err = playbackSession->init(
            mClientInfo.mRemoteIP.c_str(),
            clientRtp,
            rtpMode,
            clientRtcp,
            rtcpMode,
            mSinkSupportsAudio,
            mUsingPCMAudio,
            mSinkSupportsVideo,
            mChosenVideoResolutionType,
            mChosenVideoResolutionIndex,
            mChosenVideoProfile,
            mChosenVideoLevel);

    if (err != OK) {
        looper()->unregisterHandler(playbackSession->id());
        playbackSession.clear();
    }

    switch (err) {
        case OK:
            break;
        case -ENOENT:
            sendErrorResponse(sessionID, "404 Not Found", cseq);
            return err;
        default:
            sendErrorResponse(sessionID, "403 Forbidden", cseq);
            return err;
    }

    mClientInfo.mPlaybackSessionID = playbackSessionID;
    mClientInfo.mPlaybackSession = playbackSession;

    AString response = "RTSP/1.0 200 OK\r\n";
    AppendCommonResponse(&response, cseq, playbackSessionID);

    if (rtpMode == RTPSender::TRANSPORT_TCP_INTERLEAVED) {
        response.append(
                AStringPrintf(
                    "Transport: RTP/AVP/TCP;interleaved=%d-%d;",
                    clientRtp, clientRtcp));
    } else {
        int32_t serverRtp = playbackSession->getRTPPort();

        AString transportString = "UDP";
        if (rtpMode == RTPSender::TRANSPORT_TCP) {
            transportString = "TCP";
        }

        if (clientRtcp >= 0) {
            response.append(
                    AStringPrintf(
                        "Transport: RTP/AVP/%s;unicast;client_port=%d-%d;"
                        "server_port=%d-%d\r\n",
                        transportString.c_str(),
                        clientRtp, clientRtcp, serverRtp, serverRtp + 1));
        } else {
            response.append(
                    AStringPrintf(
                        "Transport: RTP/AVP/%s;unicast;client_port=%d;"
                        "server_port=%d\r\n",
                        transportString.c_str(),
                        clientRtp, serverRtp));
        }
    }

    response.append("\r\n");

    err = mNetSession->sendRequest(sessionID, response.c_str());

    if (err != OK) {
        return err;
    }

    mState = AWAITING_CLIENT_PLAY;

    scheduleReaper();
    scheduleKeepAlive(sessionID);

    return OK;
}
Ejemplo n.º 27
0
static void prepareAndSendErrorResponse(const char *msg, int status)
{
   HTTPResponse *resp = resp_errorResponse(msg, status);
   sendErrorResponse(resp);
}
Ejemplo n.º 28
0
void ProxygenTransport::onHeadersComplete(
  unique_ptr<HTTPMessage> msg) noexcept {

  Timer::GetMonotonicTime(m_requestStart);
  m_request = std::move(msg);
  if (m_request->isSecure()) {
    setSSL();
  }
  m_request->dumpMessage(4);
  auto method = m_request->getMethod();
  const auto& methodStr = m_request->getMethodString();
  if (method == HTTPMethod::GET) {
    m_method = Transport::Method::GET;
  } else if (method == HTTPMethod::POST ||
             s_post_methods.find(methodStr) != s_post_methods.end()) {
    m_method = Transport::Method::POST;
  } else if (method == HTTPMethod::HEAD) {
    m_method = Transport::Method::HEAD;
  } else if (method == HTTPMethod::CONNECT) {
    sendErrorResponse(400 /* Bad Request */);
    return;
  } else {
    // looks like proxygen HTTP parser understands a few more methods
    // than libevent:
    //   TRACE, COPY, MOVE, MKACTIVITY, CHECKOUT, MERGE, MSEARCH, NOTIFY,
    //   SUBSCRIBE, UNSUBSCRIBE, PATCH
    sendErrorResponse(400 /* Bad Request */);
    return;
  }
  m_extended_method = methodStr.c_str();

  const auto& headers = m_request->getHeaders();
  headers.forEach([&] (const std::string &header, const std::string &val) {
      m_requestHeaders[header.c_str()].push_back(val.c_str());
    });

  if (m_method == Transport::Method::POST && m_request->isHTTP1_1()) {
    const std::string& expectation =
      headers.getSingleOrEmpty(HTTP_HEADER_EXPECT);
    if (!expectation.empty()) {
      bool sendEom = false;
      HTTPMessage response;
      if (!boost::iequals(expectation, "100-continue")) {
        response.setStatusCode(417);
        response.setStatusMessage(HTTPMessage::getDefaultReason(417));
        response.getHeaders().add(HTTP_HEADER_CONNECTION, "close");
        sendEom = true;
      } else {
        response.setStatusCode(100);
        response.setStatusMessage(HTTPMessage::getDefaultReason(100));
      }
      response.setHTTPVersion(1, 1);
      response.dumpMessage(4);
      m_clientTxn->sendHeaders(response);
      if (sendEom) {
        m_responseCode = response.getStatusCode();
        m_responseCodeInfo = response.getStatusMessage();
        m_server->onRequestError(this);
        m_clientTxn->sendEOM();
        // this object is no longer valid
        return;
      }
    }
  }

  if (!bufferRequest()) {
    m_enqueued = true;
    m_server->onRequest(shared_from_this());
  } // otherwise we wait for EOM
}
Ejemplo n.º 29
0
static int serverTransact( INOUT SESSION_INFO *sessionInfoPtr )
	{
	SCEP_PROTOCOL_INFO protocolInfo;
	HTTP_DATA_INFO httpDataInfo;
	HTTP_URI_INFO httpReqInfo;
	BOOLEAN requestDataOK;
	int requestCount, length = DUMMY_INIT, status;

	assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );

	/* SCEP is a weird protocol that started out as a basic IPsec 
	   certificate-provisioning mechanism for routers but then had a pile of 
	   additional functionality bolted onto it via HTTP mechanisms rather 
	   than having the protocol itself handle the extra functionality.  
	   Because of this we have to handle not only the standard HTTP-as-a-
	   substrate mechanism used by the other protocols but also HTTP GET 
	   requests for additional information that the original protocol didn't 
	   accomodate */
	sessionInfoPtr->receiveBufEnd = 0;
	sioctlSet( &sessionInfoPtr->stream, STREAM_IOCTL_HTTPREQTYPES, 
			   STREAM_HTTPREQTYPE_ANY );
	for( requestCount = 0; requestCount < 5; requestCount++ )
		{
		initHttpDataInfoEx( &httpDataInfo, sessionInfoPtr->receiveBuffer,
							sessionInfoPtr->receiveBufSize, &httpReqInfo );
		status = sread( &sessionInfoPtr->stream, &httpDataInfo,
						sizeof( HTTP_DATA_INFO ) );
		if( cryptStatusError( status ) )
			{
			sNetGetErrorInfo( &sessionInfoPtr->stream, 
							  &sessionInfoPtr->errorInfo );
			return( status );
			}

		/* If it's a proper SCEP protocol message, switch back to handling 
		   the main protocol */
		if( httpDataInfo.reqType != STREAM_HTTPREQTYPE_GET )
			{
			sioctlSet( &sessionInfoPtr->stream, STREAM_IOCTL_HTTPREQTYPES, 
					   STREAM_HTTPREQTYPE_POST );
			length = httpDataInfo.bytesAvail;
			break;
			}

		/* It's one of the bolted-on additions to the basic SCEP protocol,
		   handle it specially */
		status = processAdditionalScepRequest( sessionInfoPtr, 
											   &httpReqInfo );
		if( cryptStatusError( status ) )
			return( status );
		}
	if( requestCount >= 5 )
		{
		/* The exact type of error response to send at this point is a bit
		   tricky, the least inappropriate one is probably 
		   CRYPT_ERROR_DUPLICATE to indicate that too many duplicate 
		   requests were sent, since to get here the client would have had 
		   to send repeated identical bolt-on requests */
		sendCertErrorResponse( sessionInfoPtr, CRYPT_ERROR_DUPLICATE );
		return( CRYPT_ERROR_OVERFLOW );
		}

	/* Unfortunately we can't use readPkiDatagram() because of the weird 
	   dual-purpose HTTP transport used in SCEP so we have to duplicate 
	   portions of readPkiDatagram() here.  See the readPkiDatagram() 
	   function for code comments explaining the following operations */
	if( length < 4 || length >= MAX_INTLENGTH )
		{
		sendCertErrorResponse( sessionInfoPtr, CRYPT_ERROR_BADDATA );
		retExt( CRYPT_ERROR_UNDERFLOW,
				( CRYPT_ERROR_UNDERFLOW, SESSION_ERRINFO, 
				  "Invalid PKI message length %d", length ) );
		}
	status = length = \
				checkObjectEncoding( sessionInfoPtr->receiveBuffer, length );
	if( cryptStatusError( status ) )
		{
		sendCertErrorResponse( sessionInfoPtr, CRYPT_ERROR_BADDATA );
		retExt( status, 
				( status, SESSION_ERRINFO, "Invalid PKI message encoding" ) );
		}
	sessionInfoPtr->receiveBufEnd = length;

	/* Process the initial message from the client */
	initSCEPprotocolInfo( &protocolInfo );
	status = checkScepRequest( sessionInfoPtr, &protocolInfo, 
							   &requestDataOK );
	if( cryptStatusError( status ) )
		{
		/* If we got far enough into the request data to be able to send a 
		   SCEP-level response, send that, otherwise just send an HTTP-level
		   response */
		if( requestDataOK )
			sendErrorResponse( sessionInfoPtr, &protocolInfo, status );
		else
			sendCertErrorResponse( sessionInfoPtr, status );
		return( status );
		}

	/* Issue a certificate from the request */
	status = issueCertFromRequest( sessionInfoPtr, &protocolInfo );
	if( cryptStatusError( status ) )
		{
		sendErrorResponse( sessionInfoPtr, &protocolInfo, status );
		destroySCEPprotocolInfo( &protocolInfo );
		return( status );
		}

	/* Return the certificate to the client */
	status = createScepResponse( sessionInfoPtr, &protocolInfo );
	if( cryptStatusOK( status ) )
		status = writePkiDatagram( sessionInfoPtr, SCEP_CONTENT_TYPE,
								   SCEP_CONTENT_TYPE_LEN );
	destroySCEPprotocolInfo( &protocolInfo );
	return( status );
	}
Ejemplo n.º 30
0
int main() {

#ifdef	PROFILE
    int i;
#endif
    const char *config_url, *username, *password, *config_options;
    strtbl *options = NULL;
    int exit_status = 0;

    // install SIGUSR1, SIGPIPE, SIGTERM handler
    signal(SIGTERM, sig_handler);
    signal(SIGUSR1, sig_handler);
    signal(SIGPIPE, sig_handler);

      /* Provide a hook via an environment variable to define the config URL */
      config_url = getenv(WO_CONFIG_URL);
      if (!config_url) {
         /* Flat file URL */
         /* config_url = "file:///Local/Library/WebObjects/Configuration/WOConfig.xml"; */
         /* Local wotaskd */
         /* config_url = "http://localhost:1085"; */
         /* Multicast URL */
         config_url = CONFIG_URL; /* Actually "webobjects://239.128.14.2:1085"; */
      }
      WOLog(WO_INFO,"<FastCGI> config url is %s", config_url);
      options = st_new(8);
      st_add(options, WOCONFIG, config_url, 0);

      /*
         * If your webserver is configured to pass these environment variables, we use them to
       * protect WOAdaptorInfo output.
       */
      username = getenv(WO_ADAPTOR_INFO_USERNAME);
      if (username && strlen(username) != 0) {
         st_add(options, WOUSERNAME, username, 0);
         password = getenv(WO_ADAPTOR_INFO_PASSWORD);
         if(password && strlen(password) != 0) {
            st_add(options, WOPASSWORD, password, 0);
         }
      }

      config_options = getenv(WO_CONFIG_OPTIONS);
      if (config_options)
         st_add(options, WOOPTIONS, config_options, 0);
      /*
       * SECURITY ALERT
       *
       * To disable WOAdaptorInfo, uncomment the next line.
       * st_add(options, WOUSERNAME, "disabled", 0);
       *
       * To specify an WOAdaptorInfo username and password, uncomment the next two lines.
       * st_add(options, WOUSERNAME, "joe", 0);
       * st_add(options, WOPASSWORD, "secret", 0);
       *
       */

      if (init_adaptor(options)) {
          WOLog( WO_ERR, "<FastCGI> Adaptor initialization failed.");
    	    exit(-1);
      }

    WOLog( WO_INFO,"<FastCGI> process started" );
   
    while (!should_terminate) {

      HTTPRequest *req;
      HTTPResponse *resp = NULL;
      WOURLComponents wc = WOURLComponents_Initializer;
      const char *qs;
      unsigned int qs_len;
      char *url;
      const char *script_name, *path_info;
      const char *reqerr;
      WOURLError urlerr;
      FCGX_ParamArray hdrp_org;
     
      exit_status = FCGX_Accept(&in, &out, &err, &hdrp );
      if ( exit_status < 0 ) {
	    break;
      }

#ifdef	PROFILE
    for (i=0; i < 50000; i++) {
#endif

      WOLog( WO_INFO,"<FastCGI> request accepted" );

#ifdef WIN32
      _setmode(_fileno(stdout), _O_BINARY);
      _setmode(_fileno(stdin), _O_BINAR1Y);
#endif

      script_name = FCGX_GetParam( CGI_SCRIPT_NAME, hdrp);
      path_info = FCGX_GetParam( CGI_PATH_INFO, hdrp);

      WOLog( WO_INFO,"<FastCGI> CGI_SCRIPT_NAME = %s", script_name );
      WOLog( WO_INFO,"<FastCGI> CGI_PATH_INFO = %s", path_info );

      if (script_name == NULL) {
         prepareAndSendErrorResponse(INV_SCRIPT, HTTP_NOT_FOUND);
         break;
      } else if (path_info == NULL) {
         path_info = "/";
      }

      /*
       *	extract WebObjects application name from URI
       */

      url = WOMALLOC(strlen(path_info) + strlen(script_name) + 1);
      strcpy(url, script_name);
      strcat(url, path_info);
      WOLog(WO_INFO,"<FastCGI> new request: %s",url);
      
      urlerr = WOParseApplicationName(&wc, url);
      if (urlerr != WOURLOK) {
         const char *_urlerr;
         _urlerr = WOURLstrerror(urlerr);
         WOLog(WO_INFO,"<FastCGI> URL Parsing Error: %s", _urlerr);

         if (urlerr == WOURLInvalidApplicationName) {
             if (ac_authorizeAppListing(&wc)) {
                 resp = WOAdaptorInfo(NULL, &wc);
                 sendErrorResponse(resp);
             } else {
                 prepareAndSendErrorResponse(_urlerr, HTTP_NOT_FOUND);
             }
             WOFREE(url);
             break;
         }

         prepareAndSendErrorResponse(_urlerr, HTTP_BAD_REQUEST);
         WOFREE(url);
         break;
      }


      /*
       *	build the request...
       */
      req = req_new( FCGX_GetParam("REQUEST_METHOD", hdrp), NULL);


      /*
       *	validate the method
       */
      reqerr = req_validateMethod(req);
      if (reqerr) {
          prepareAndSendErrorResponse(reqerr, HTTP_BAD_REQUEST);
          WOFREE(url);
          break;
      }

      /*
       *	copy the headers.  This looks wierd... all we're doing is copying
       *	*every* environment variable into our headers.  It may be beyond
       *	the spec, but more information probably won't hurt.
       */
      hdrp_org=hdrp;
      while (hdrp && *hdrp) {
         char *key, *value;
         /* copy env. line. */
         key = WOSTRDUP(*hdrp);

         for (value = key; *value && !isspace((int)*value) && (*value != '='); value++) {}
         if (*value) {
            *value++ = '\0';	/* null terminate 'key' */
         }
         while (*value && (isspace((int)*value) || (*value == '='))) {
            value++;
         }
         /* BEGIN Support for getting the client's certificate. */
         if (strcmp((const char *)key, "SSL_CLIENT_CERTIFICATE") == 0 || strcmp((const char *)key, "SSL_SERVER_CERTIFICATE") == 0 ) {
             value = 0;
             WOLog(WO_INFO,"<FastCGI> DROPPING ENV VAR (DUPLICATE) = %s", key);
         }
         if (strcmp((const char *)key, "SSL_CLIENT_CERT") == 0 || strcmp((const char *)key, "SSL_SERVER_CERT") == 0) {
             value = make_cert_one_line(value);
             //WOLog(WO_INFO,"<FastCGI> PASSING %s = %s", key, value);
         }
         /*  END Support for getting the client's certificate  */

         if (key && *key && value && *value) {
            /* must specify copy key and value because key translation might replace this key, and value lives in the same buffer */
            req_addHeader(req, key, value, STR_COPYKEY|STR_COPYVALUE);
         }

         /*  BEGIN Support for getting the client's certificate  */
         if (freeValueNeeded ) {
             free(value);
             freeValueNeeded=0;
         }
         /*  END Support for getting the client's certificate  */

         WOFREE(key);
         hdrp++;			/* next env variable */
      }
      hdrp=hdrp_org;

      /*
       *	get form data if any
       *	assume that POSTs with content length will be reformatted to GETs later
       */
	
      WOLog ( WO_INFO, "Getting request data, length: %d",req->content_length );
      if (req->content_length > 0) {
         req_allocateContent(req, req->content_length, 1);
         req->getMoreContent = (req_getMoreContentCallback)readContentData;
         WOLog ( WO_INFO, "content_buffer_size: %d",req->content_buffer_size );
         if (req->content_buffer_size == 0) {
            prepareAndSendErrorResponse(ALLOCATION_FAILURE, HTTP_SERVER_ERROR);
            WOFREE(url);
            break;
         }
         if (readContentData(req, req->content, req->content_buffer_size, 1) == -1) {
            prepareAndSendErrorResponse(WOURLstrerror(WOURLInvalidPostData), HTTP_BAD_REQUEST);
            WOFREE(url);
            break;
         }
      }

      /* Always get the query string */
      qs = FCGX_GetParam("QUERY_STRING", hdrp);
      if (qs) {
         qs_len = strlen(qs);
      } else {
         qs_len = 0;
      }

      if (qs_len > 0) {
         wc.queryString.start = qs;
         wc.queryString.length = qs_len;
         WOLog(WO_INFO,"<FastCGI> new request with Query String: %s", qs);
      }

      /*
       *	message the application & collect the response
       */
      resp = tr_handleRequest(req, url, &wc, FCGX_GetParam(CGI_SERVER_PROTOCOL, hdrp), documentRoot());

      if (resp != NULL) {
         sendResponse(resp);
         resp_free(resp);		/* dump the response */
      }

      WOFREE(url);
      req_free(req);

#if defined(FINDLEAKS)
      showleaks();
#endif
    }

#ifdef	PROFILE
    }
#endif


    st_free(options);
    WOLog( WO_INFO,"<FastCGI> process exiting" );

    return exit_status;
}