Exemple #1
0
    QVariant SessionModel::data(const QModelIndex &index, int role) const {
        if (index.row() < 0 || index.row() >= d->sessions.count())
            return QVariant();

        // get session
        Session *session = d->sessions[index.row()];

        // return correct value
        switch (role) {
        case DirectoryRole:
            return session->directory().absolutePath();
        case FileRole:
            return session->fileName();
        case TypeRole:
            return session->type();
        case NameRole:
            return session->displayName();
        case ExecRole:
            return session->exec();
        case CommentRole:
            return session->comment();
        default:
            break;
        }

        // return empty value
        return QVariant();
    }
Exemple #2
0
void Command::emitResponses()
{
    if ( state() == Retired )
        return;

    Session * s = imap()->session();
    if ( s && !s->initialised() )
        return;

    imap()->emitResponses();
    if ( !d->untagged.isEmpty() )
        return;
    setState( Retired );

    // we don't have a tag if we're an implicit Fetch or Store used by
    // ImapSession.
    if ( d->tag.isEmpty() )
        return;

    EString t = tag();
    if ( !d->error ) {
        t.append( " OK " );
    }
    else if ( d->errorCode == Bad ) {
        imap()->recordSyntaxError();
        t.append( " BAD " );
    }
    else {
        t.append( " NO " );
    }
    if ( !d->respTextCode.isEmpty() ) {
        t.append( "[" );
        t.append( d->respTextCode );
        t.append( "] " );
    }
    if ( d->error ) {
        t.append( d->errorText );
    }
    else {
        t.append( "done" );
    }
    log( t );
    t.append( "\r\n" );
    imap()->enqueue( t );
}
//======================================================================================================================
void SocketWriteThread::run()
{
    Session*            session;


    // Call our internal _startup method
    _startup();

    // Main loop
    while(!mExit)    {

		//if((!this->mServerService) && sessionCount)	{
			//DLOG(info) << "SocketWriteThread::run() START";
			//DLOG(info) << "servicing : " << sessionCount << " Sessions";
			//DLOG(info) << "NO ACTIVE OBJECT";
		//}
		uint32 packetsSend = 0;

        while(mSessionQueue.pop(session))	{
            uint32 packetCount = 0;

            // Process our session
			active_.Send( [=] {
				session->ProcessWriteThread();
				mAsyncSessionQueue.push(session);
			}
			);

        }

		while(mAsyncSessionQueue.pop(session))	{
			_send(session);
		}

		//if((!this->mServerService) && sessionCount)	{
			//DLOG(info) << "SocketWriteThread::run() END";
			//DLOG(info) << "sending : " << packetsSend << "Packets";
		//}

        boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    }

    // Shutdown internally
    _shutdown();
}
void WServer::HandlePlayerLoginResult(WorldPacket & pck)
{
	uint32 guid, sessionid;
	uint8 result;
	pck >> guid >> sessionid >> result;
	if(result)
	{
		Log.Success("WServer", "Worldserver %u reports successful login of player %u", m_id, guid);
		Session * s = sClientMgr.GetSession(sessionid);
		if(s)
		{
			/* update server */
			s->SetNextServer();

			/* pack together a player info packet and distribute it to all the other servers */
			ASSERT(s->GetPlayer());

			WorldPacket data(ISMSG_PLAYER_INFO, 100);
			s->GetPlayer()->Pack(data);
			sClusterMgr.DistributePacketToAll(&data, this);
		}
	}
	else
	{
		Log.Error("WServer", "Worldserver %u reports failed login of player %u", m_id, guid);
		Session * s = sClientMgr.GetSession(sessionid);
		if(s)
		{
			s->ClearCurrentPlayer();
			s->ClearServers();
		}

		sClientMgr.DestroyRPlayerInfo(guid);
	}
}
Exemple #5
0
bool_t NetworkTask::DispatchMsg()
{
	bool_t ret = FALSE;

	Buffer *buffer = network_q_->Pop();
	if(!buffer) { return FALSE; }

	Session *sess = 0;
	PacketHeader pkt_header;
	ret = buffer->GetBinary((char_t*)&pkt_header, sizeof(pkt_header));
	if(!ret) { ECILA_TRACE(); goto _ERROR; }

	//network task 는 비동기, dispatch task 는 동기이므로 세션이 먼저 close 될수 있다.
	//그러므로 활성 세션을 찻지 못했을경우는 스킵한다. 
	sess = act_sess_pool_->ACTSession(pkt_header.uidx_);
	if(!sess) { goto _ABORT; }

	if(pkt_header.cmd_ & PKT_CMD_SEND)
	{
		ret = sess->Send(buffer->GetOutPtr(), pkt_header.size_);
		if(!ret) { ECILA_TRACE(); goto _ERROR; }
	}

	if(pkt_header.cmd_ & PKT_CMD_CLOSE)
	{
		ret = sess->Close(TRUE);
		if(!ret) { ECILA_TRACE(); goto _ERROR; }
	}


_ABORT:

	ret = buff_pool_->Release(buffer);
	if(!ret) { ECILA_TRACE(); return FALSE; }

	return TRUE;



_ERROR:
	ret = buff_pool_->Release(buffer);
	if(!ret) { ECILA_TRACE(); return FALSE; }

	return FALSE;
}
Exemple #6
0
osg::Node*
FeatureModelSource::createNodeImplementation(const Map*        map,
                                             ProgressCallback* progress )
{
    // trivial bailout.
    if (!getStatus().isOK())
        return 0L;

    // user must provide a valid map.
    if ( !map )
    {
        OE_WARN << LC << "NULL Map is illegal when building feature data." << std::endl;
        return 0L;
    }

    // make sure the feature source initialized properly:
    if ( !_features.valid() || !_features->getFeatureProfile() )
    {
        return 0L;
    }

    // create a feature node factory:
    FeatureNodeFactory* factory = createFeatureNodeFactory();
    if ( !factory )
    {
        OE_WARN << LC << "Unable to create a feature node factory!" << std::endl;
        setStatus(Status::Error(Status::ServiceUnavailable, "Failed to create a feature node factory"));
        return 0L;
    }

    // Session holds data that's shared across the life of the FMG
    Session* session = new Session( 
        map, 
        _options.styles().get(), 
        _features.get(), 
        _readOptions.get() );

    // Name the session (for debugging purposes)
    session->setName( this->getName() );

    // Graph that will render feature models. May included paged data.
    FeatureModelGraph* graph = new FeatureModelGraph(session, _options, factory, getSceneGraphCallbacks());

    return graph;
}
Exemple #7
0
    void Display::startAuth(const QString &user, const QString &password, const Session &session) {
        m_passPhrase = password;

        // sanity check
        if (!session.isValid()) {
            qCritical() << "Invalid session" << session.fileName();
            return;
        }
        if (session.xdgSessionType().isEmpty()) {
            qCritical() << "Failed to find XDG session type for session" << session.fileName();
            return;
        }
        if (session.exec().isEmpty()) {
            qCritical() << "Failed to find command for session" << session.fileName();
            return;
        }

        m_reuseSessionId = QString();

        if (Logind::isAvailable() && mainConfig.Users.ReuseSession.get()) {
            OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(), Logind::managerPath(), QDBusConnection::systemBus());
            auto reply = manager.ListSessions();
            reply.waitForFinished();

            foreach(const SessionInfo &s, reply.value()) {
                if (s.userName == user) {
                    OrgFreedesktopLogin1SessionInterface session(Logind::serviceName(), s.sessionPath.path(), QDBusConnection::systemBus());
                    if (session.service() == QLatin1String("sddm")) {
                        m_reuseSessionId =  s.sessionId;
                        break;
                    }
                }
            }
        }
Exemple #8
0
void				ServerManager::Manage(Packet * packet)
{
  Session			*session;
  Packet_v1			*packet_v1;
  
  packet_v1 = static_cast<Packet_v1 *>(packet);
  field_t			componentId = packet_v1->getComponentId(), requestId = packet_v1->getRequestId();
  session = _sessionManager->FindSession(packet_v1);

#ifdef _DEBUG
  COLOR_BLUE;COLOR_INTENSITY;
  std::cout << std::endl;
  std::cout << "<      RECV       > ";
  packet_v1->Print("", this);
  COLOR_DEFAULT;
#endif
  if (session)
    {
      session->setTimeOutTest();
      session->CancelTimeOutOccurred();

      if (IsRegisteredComponent(componentId))
	{
	  if (IsRegisteredRequest(componentId, requestId))
	    {
	      getBindRecv(componentId, requestId).Receive(packet_v1, session);
	      Request const & r = getRegisteredRequest(componentId, requestId);
	      if (r.IsResponseTo())
		session->CancelAutoRetry(componentId, r.getResponseTo());
	    }
	  else
	    std::cout << "UNREGISTERED REQUEST ID" << std::endl;
	}
      else
	std::cout << "UNREGISTERED COMPONENT ID" << std::endl;
    }
  else if (componentId == SESSION_COMPONENTID && requestId == SESSION_AUTHREQUEST)
    _sessionManager->Recv_AuthRequest(packet_v1, 0);
  else
    {
      //_sessionManager->PrintSession(packet);
      std::cout << "auth required" << std::endl;
      // send apropriate information
    }
}
Exemple #9
0
void WidgetIrcMain::connectToImpl(const ConnectionInfo& connection)
{
	Session* session = Session::fromConnection(connection, this);
    session->setEncoding(Application::encoding());
    if (session->userName().isEmpty())
        session->setUserName("quazaa");
	if (!session->hasQuit() && session->ensureNetwork())
		session->open();
    tabWidget->addSession(session);

	connect(session, SIGNAL(activeChanged(bool)), this, SLOT(updateSession()));
	connect(session, SIGNAL(connectedChanged(bool)), this, SLOT(updateSession()));
	updateSession(session);

    SessionTabWidget* tab = tabWidget->sessionWidget(session);
    connect(tab, SIGNAL(viewAdded(WidgetIrcMessageView*)), this, SLOT(viewAdded(WidgetIrcMessageView*)));
    connect(tab, SIGNAL(viewRemoved(WidgetIrcMessageView*)), this, SLOT(viewRemoved(WidgetIrcMessageView*)));
    connect(tab, SIGNAL(viewRenamed(WidgetIrcMessageView*)), this, SLOT(viewRenamed(WidgetIrcMessageView*)));
    connect(tab, SIGNAL(viewActivated(WidgetIrcMessageView*)), this, SLOT(viewActivated(WidgetIrcMessageView*)));
    connect(tab, SIGNAL(editSession(Session*)), this, SLOT(editSession(Session*)));

    if (WidgetIrcMessageView* view = tab->viewAt(0)) {
        treeWidget->addView(view);
        treeWidget->setCurrentView(view);
        treeWidget->parentWidget()->show();
        view->applySettings();
    }

    if (!quazaaSettings.WinMain.ChatUserListSplitter.isEmpty())
        tab->restoreSplitter(quazaaSettings.WinMain.ChatUserListSplitter);
}
Exemple #10
0
int LuaNetwork::CloseSession(lua_State* L)
{
	int sn;
	Lua::argParse(L, "i", &sn);
	Net *pNet = ServerApp::get()->getNet();
	if (!pNet)
	{
		luaL_error(L, "Net have'nt been created!");
		return 0;
	}
	Session *s = pNet->getSession(sn);
	if (s)
	{
		s->close();
		LOG("Close connection %d sn by script interface", sn);
	}
	return 0;
}
Exemple #11
0
void Node::receiveNodeNameSet(void* user, VNodeID ID, const char* name)
{
  Session* session = Session::getCurrent();

  Node* node = session->getNodeByID(ID);
  if (!node)
    return;

  if (node->mName != name)
  {
    const Node::ObserverList& observers = node->getObservers();
    for (Node::ObserverList::const_iterator i = observers.begin();  i != observers.end();  i++)
      (*i)->onSetName(*node, name);

    node->mName = name;
    node->updateDataVersion();
  }
}
ClassificationObjectPtr DatabaseSubsystem::getClassificationObject(int clObjID)
{
    RWLock::ScopedLock lock(_dbLock);

    ClassificationObjectPtr result;
    Session session = getSession();
    session.begin();
    session <<
        "SELECT * FROM classification_object WHERE object_id = ?",
        use(clObjID), into(result),
        now;
    if (!result.isNull()) {
        getClassificationObjectDescrIDs(session, result);
        getClassificationObjectLabelIDs(session, result);
    }
    session.commit();
    return result;
}
void DatabaseSubsystem::createProcess(ProcessPtr process)
{
    RWLock::ScopedLock lock(_dbLock, true);

    Session session = getSession();
    session.begin();
    session <<
        "INSERT INTO process (process_name, input_file, start_time, sample_freq) "
        "VALUES (?, ?, ?, ?)",
        use(process->name),
        use(process->inputFile),
        use(process->startTime),
        use(process->sampleFreq),
        now;
    process->processID = lastInsertID(session);
    insertProcessParams(session, process);
    session.commit();
}
ResponsePtr DatabaseSubsystem::getResponse(int responseID)
{
    RWLock::ScopedLock lock(_dbLock);

    ResponsePtr result;
    Session session = getSession();
    session.begin();
    session <<
        "SELECT * FROM response WHERE response_id = ?",
        use(responseID),
        into(result),
        now;
    if (!result.isNull()) {
        getResponseLabels(session, result);
    }
    session.commit();
    return result;
}
Exemple #15
0
////////////////////////////////////////////////////////////
// Delete Process
data::ENSessionState BasicHandler::OnDBSvrDelete(Session& session) {
    // check db process index
    if (session.db_process_index() >= (size_t)session.db_handles_size()) return data::SESSION_STATE_FINISH;

    // get db query
    auto& db_handle = session.db_handles(session.db_process_index());

    // construct request
    msg::SS message;
    message.set_msg_type(msg::SS_TYPE_DELETE_DATA_REQ);
    message.mutable_proxy_head()->set_session_id(session.session_id());
    auto& request  = *message.mutable_delete_data_req();
    request.set_type(db_handle.type());
    request.set_id(db_handle.id());
    ConnectServerMsgTransferService::Instance()->TransferMessageByHash(conf::SERVER_TYPE_DATA_SERVER, db_handle.id(), message);

    return data::SESSION_STATE_DBSVR_DELETE_WAIT;
}
Exemple #16
0
void SessionInitialiser::recordExpunges()
{
    if ( !d->expunges )
        return;
    Row * r = 0;
    IntegerSet uids;
    while ( (r=d->expunges->nextRow()) != 0 )
        uids.add( r->getInt( "uid" ) );
    if ( uids.isEmpty() )
        return;

    List<Session>::Iterator i( d->sessions );
    while ( i ) {
        Session * s = i;
        ++i;
        s->expunge( uids );
    }
}
AuthHostInstance::AuthHostInstance(Session &session, AuthHostType host) :
	mHostType(host)
{
	secdebug("authhost", "authhost born (%p)", this);
	referent(session);
	session.addReference(*this);
    if (host == securityAgent)
        pthread_once(&agent_cred_init, initialize_agent_creds); 
}
	virtual void List(Session& ses) const {
		ServerInstanceInfo srv(ses);
		
		bool serverIsUp = GameModules[GAME_NAME]->IsUp(srv.Id);
		
		ses.NewElem();
		if (serverIsUp) {
			ses.AddChildNode("name", "server_online");
			ses.AddChildNode("status", "on");
		} else {
			ses.AddChildNode("name", "server_offline");
			ses.AddChildNode("status", "off");
		}
		
		AddRow(ses, "ip", srv.GetIp());
		AddRow(ses, "port", str::Str(srv.GetPort()));
		AddRow(ses, "players_online", serverIsUp?str::Str(GameModules[GAME_NAME]->PlayersOnline(srv.Id)):"-");
	}
void VirtualScrollback::Sync()
{
    if (this->owner == NULL)
        throw new NullPointerException("this->owner", BOOST_CURRENT_FUNCTION);

    // Let's get all sessions who need to be informed about creation of this scrollback
    Session *session = this->owner->GetAnyGPSession();
    if (!session)
        return;
    QHash<QString, QVariant> parameters;
    parameters.insert("name", this->GetTarget());
    if (this->parentSx)
        parameters.insert("parent_sid", QVariant(this->parentSx->GetOriginalID()));
    if (this->GetSession() && this->GetSession()->GetType() == SessionType_IRC)
        parameters.insert("network_id", QVariant(((IRCSession*)this->GetSession())->GetSID()));
    parameters.insert("scrollback", QVariant(this->ToHash()));
    session->SendToEverySession(GP_CMD_SCROLLBACK_RESYNC, parameters);
}
int Game::SspCalculateFrame()
{
    // clear old state
    m_cur_state.clear();
    //pick the newest state of each client
    for(auto session_iter = m_player_list->begin(); session_iter != m_player_list->end(); ++session_iter)
    {
        Session *s = (*session_iter); 

        std::string state;
        if(s->PopState(state) == 0)
        {
            m_cur_state += state;
        }
    }
    
    return 0;
}
void MemcachedSessionManager::delete_session(Session &session)
{
    memcached_return rc;
    std::string const &sessionid = session.sessionid();
    rc = memcached_delete(memcached_conn, sessionid.data(),
            sessionid.length(), 0);
    if (rc != MEMCACHED_SUCCESS)
        throw MemcacheError(memcached_conn, rc);
}
Exemple #22
0
int LuaNetwork::SetSessionUserData(lua_State* L)
{
	int sn;
	char *ud;
	Lua::argParse(L, "is", &sn, &ud);
	Net *pNet = ServerApp::get()->getNet();
	if (!pNet)
	{
		luaL_error(L, "Net have'nt been created!");
		return 0;
	}
	Session *s = pNet->getSession(sn);
	if (s)
		s->setUserData(ud);
	else
		luaL_error(L, "Can't find session %d", sn);
	return 0;
}
Exemple #23
0
TEST(DeleteTests, SessionDeleteUnallowedAfterPostTest) {
    Session session;
    {
        auto url = Url{base + "/url_post.html"};
        auto payload = Payload{{"x", "5"}};
        session.SetUrl(url);
        auto response = session.Post();
    }
    auto url = Url{base + "/delete_unallowed.html"};
    session.SetUrl(url);
    auto response = session.Delete();
    auto expected_text = std::string{"Method unallowed"};
    EXPECT_EQ(expected_text, response.text);
    EXPECT_EQ(url, response.url);
    EXPECT_EQ(std::string{"text/html"}, response.header["content-type"]);
    EXPECT_EQ(405, response.status_code);
    EXPECT_EQ(ErrorCode::OK, response.error.code);
}
void DatabaseSubsystem::updateResponse(ResponsePtr response)
{
    RWLock::ScopedLock lock(_dbLock, true);

    Session session = getSession();
    session.begin();
    session <<
        "UPDATE response SET name = ?, description = ? WHERE response_id = ?",
        use(response->name), use(response->description),
        use(response->responseID),
        now;
    session <<
        "DELETE FROM response_label WHERE response_id = ?",
        use(response->responseID),
        now;
    insertResponseLabels(session, response);
    session.commit();
}
Exemple #25
0
void RTMFPServer::onReadable(Socket& socket) {
    // Running on the thread of manager socket
    AutoPtr<RTMFPReceiving> pRTMFPReceiving(new RTMFPReceiving(*this,(DatagramSocket&)socket));
    if(!pRTMFPReceiving->pPacket)
        return;

    if(pRTMFPReceiving->id==0) {
        _handshake.decode(pRTMFPReceiving);
        return;
    }
    ScopedLock<Mutex>  lock(_sessions.mutex);
    Session* pSession = _sessions.find(pRTMFPReceiving->id);
    if(!pSession) {
        WARN("Unknown session %u",pRTMFPReceiving->id);
        return;
    }
    pSession->decode(pRTMFPReceiving);
}
    virtual void run()
    {

        try {
            // Create a ConnectionFactory
            auto_ptr<ConnectionFactory> connectionFactory(
                ConnectionFactory::createCMSConnectionFactory( (const char*)brokerURI ) );

            // Create a Connection
            connection = connectionFactory->createConnection();
            connection->start();

            // Create a Session
            if( this->sessionTransacted ) {
                session = connection->createSession( Session::SESSION_TRANSACTED );
            } else {
                session = connection->createSession( Session::AUTO_ACKNOWLEDGE );
            }

            destination = session->createQueue((const char*)queue);
            //destination = session->createQueue("/asev/queue");
            // Create a MessageProducer from the Session to the Topic or Queue
            producer = session->createProducer( destination );
            producer->setDeliveryMode( DeliveryMode::PERSISTENT );

            //cout<<"message:"<<message<<"\n";

			TextMessage* sendmessage = session->createTextMessage( (char*)message );

			//cout<<"producer:"<<sendmessage->getText()<<"\n";
			// Tell the producer to send the message
			//printf( "Sent message #%d from thread %s\n", ix+1, threadIdStr.c_str() );
			producer->send( sendmessage );

			if(this->sessionTransacted)
				session->commit();

			delete sendmessage;


        }catch ( CMSException& e ) {
            e.printStackTrace();
        }
    }
Exemple #27
0
int main( int argc, char * argv[] )
{
   Process process;
   Session session;

   // Internal process object not initialized
   try {
      session.Init();
      // Should never come here
      cerr << "Test failed - line " << __LINE__ << endl;
      return 1;
   }
   catch( pso::Exception exc ) {
      if ( exc.ErrorCode() != PSO_PROCESS_NOT_INITIALIZED ) {
         cerr << "Test failed - line " << __LINE__ << ", error = " << exc.Message() << endl;
         return 1;
      }
   }
   
   try {
      if ( argc > 1 ) {
         process.Init( argv[1], argv[0] );
      }
      else {
         process.Init( "10701", argv[0] );
      }
   }
   catch( pso::Exception exc ) {
      cerr << "Test failed in init phase, error = " << exc.Message() << endl;
      cerr << "Is the server running?" << endl;
      return 1;
   }
   
   try {
      session.Init();
   }
   catch( pso::Exception exc ) {
      cerr << "Test failed - line " << __LINE__ << ", error = " << exc.Message() << endl;
      return 1;
   }
   
   return 0;
}
/**
* @brief Returns the userId of the currently logged in user.
* Throws std::invalid_argument if no user with that cookie found.
*
* @param cookie the cookie that the client browser gave us
* @param touch If true, updates the session time out
*
* @return userId of the currently logged in user
*/
int MemorySessionStore::userId(const string& cookie, bool touch) {
    ReadOnlyLock lock(_lock);
    Session* session = findSession(lock, cookie);
    if (session != 0) {
        if (session->age() < _timeout) {
            if (touch) {
                ReadWriteLock touchLock(_lock);
                // Session is still good, update its timeout on our end
                session->updateLoginTime();
            }
            return session->userId();
        } else {
            // Cookie is expired - delete its session and return empty
            ReadWriteLock eraseLock(_lock);
            sessions.erase(cookie);
        }
    }
    throw invalid_argument("No user with cookie " + cookie + " found");
}
Exemple #29
0
static Session *
start_session(team_id team, dev_t device, ino_t node, const char *name,
	int32 seconds = 30)
{
	RecursiveLocker locker(&sLock);

	Session *session = new Session(team, name, device, node, seconds);
	if (session == NULL)
		return NULL;

	if (session->InitCheck() != B_OK || session->StartWatchingTeam() != B_OK) {
		delete session;
		return NULL;
	}

	// let's see if there is a prefetch session for this session

	Session *prefetchSession;
	if (session->IsMainSession()) {
		// search for session by name
		for (prefetchSession = sMainPrefetchSessions;
				prefetchSession != NULL;
				prefetchSession = prefetchSession->Next()) {
			if (!strcmp(prefetchSession->Name(), name)) {
				// found session!
				break;
			}
		}
	} else {
		// ToDo: search for session by device/node ID
		prefetchSession = NULL;
	}
	if (prefetchSession != NULL) {
		TRACE(("found prefetch session %s\n", prefetchSession->Name()));
		prefetchSession->Prefetch();
	}

	if (team >= B_OK)
		hash_insert(sTeamHash, session);

	session->Lock();
	return session;
}
Exemple #30
0
void OkcoinApp::submitMarketOrder(const char *symbol, OrderSide side, double amount, const char *userId)
{
    int ts = timestamp();
    FIX44::NewOrderSingle message;
    message.set(Account(_publicKey + "," + _privateKey));
    if (userId)
        message.set(ClOrdID(userId));
    else
        message.set(ClOrdID("OkcoinOrder"));
    message.set(Price(amount));
    message.set(OrderQty(amount));
    message.set(OrdType(OrdType_MARKET));
    message.set(Symbol(symbol));
    message.set(Side(side == OrderBuy ? Side_BUY : Side_SELL));
    message.set(TransactTime());
    Session *session = Session::lookupSession(_sessionID);
    if (session)
        session->send(message);
}