bool com_ximeta_driver_NDASLogicalDevice::receiveDeviceNotification(kNDASDeviceNotificationType type)
{
	
	// Create NDAS Command.
	com_ximeta_driver_NDASDeviceNotificationCommand *command = new com_ximeta_driver_NDASDeviceNotificationCommand();
	if(command == NULL || !command->init()) {
		DbgIOLog(DEBUG_MASK_NDAS_ERROR, ("failed to alloc command class\n"));
		if (command) {
			command->release();
		}
		
		return false;
	}
	
	command->setCommand(type, this);
	
	com_ximeta_driver_NDASLogicalDeviceController *controller = OSDynamicCast(com_ximeta_driver_NDASLogicalDeviceController, getClient());
		
	if(!controller) { 
		DbgIOLog(DEBUG_MASK_NDAS_INFO, ("Controller is not installed.\n"));
		
		command->release();
		
		return false;
	}
		
	controller->enqueueCommand(command);
	
	return true;
}
StatusWith<SharedSemiFuture<ReplIndexBuildState::IndexCatalogStats>>
IndexBuildsCoordinatorMongod::startIndexBuild(OperationContext* opCtx,
                                              CollectionUUID collectionUUID,
                                              const std::vector<BSONObj>& specs,
                                              const UUID& buildUUID) {
    std::vector<std::string> indexNames;
    for (auto& spec : specs) {
        std::string name = spec.getStringField(IndexDescriptor::kIndexNameFieldName);
        if (name.empty()) {
            return Status(
                ErrorCodes::CannotCreateIndex,
                str::stream() << "Cannot create an index for a spec '" << spec
                              << "' without a non-empty string value for the 'name' field");
        }
        indexNames.push_back(name);
    }

    auto nss = UUIDCatalog::get(opCtx).lookupNSSByUUID(collectionUUID);
    auto dbName = nss.db().toString();
    auto replIndexBuildState =
        std::make_shared<ReplIndexBuildState>(buildUUID, collectionUUID, dbName, indexNames, specs);

    Status status = _registerIndexBuild(opCtx, replIndexBuildState);
    if (!status.isOK()) {
        return status;
    }

    // Run index build in-line if we are transitioning between replication modes.
    // While the RSTLExclusive is being held, the async thread in the thread pool is not allowed
    // to take locks.
    if (opCtx->lockState()->isRSTLExclusive()) {
        log() << "Running index build on current thread because we are transitioning between "
                 "replication states: "
              << buildUUID;
        // Sets up and runs the index build. Sets result and cleans up index build.
        _runIndexBuild(opCtx, buildUUID);
        return replIndexBuildState->sharedPromise.getFuture();
    }

    // Task in thread pool should retain the caller's deadline.
    auto deadline = opCtx->getDeadline();
    auto timeoutError = opCtx->getTimeoutError();

    // Task in thread pool should have similar CurOp representation to the caller so that it can be
    // identified as a createIndexes operation.
    BSONObj opDesc;
    {
        stdx::unique_lock<Client> lk(*opCtx->getClient());
        auto curOp = CurOp::get(opCtx);
        opDesc = curOp->opDescription().getOwned();
    }

    status = _threadPool.schedule([ this, buildUUID, deadline, timeoutError, opDesc ]() noexcept {
        auto opCtx = Client::getCurrent()->makeOperationContext();

        opCtx->setDeadlineByDate(deadline, timeoutError);

        {
            stdx::unique_lock<Client> lk(*opCtx->getClient());
            auto curOp = CurOp::get(opCtx.get());
            curOp->setOpDescription_inlock(opDesc);
        }

        // Sets up and runs the index build. Sets result and cleans up index build.
        _runIndexBuild(opCtx.get(), buildUUID);
    });

    // Clean up the index build if we failed to schedule it.
    if (!status.isOK()) {
        stdx::unique_lock<stdx::mutex> lk(_mutex);

        // Unregister the index build before setting the promises, so callers do not see the build
        // again.
        _unregisterIndexBuild(lk, opCtx, replIndexBuildState);

        // Set the promise in case another thread already joined the index build.
        replIndexBuildState->sharedPromise.setError(status);

        return status;
    }

    return replIndexBuildState->sharedPromise.getFuture();
}
uint32_t com_ximeta_driver_NDASLogicalDevice::updateStatus()
{
	uint32_t prevStatus, newStatus;
	
	prevStatus = newStatus = Status();

	switch(prevStatus) {
		case kNDASUnitStatusNotPresent:
		case kNDASUnitStatusFailure:
		{
			newStatus = fUnitDevice->Status();
		}
			break;
		case kNDASUnitStatusDisconnected:
		{
			switch(fUnitDevice->Status()) {
				case kNDASUnitStatusConnectedRO:
				{
					newStatus = kNDASUnitStatusTryConnectRO;
				}
					break;
				case kNDASUnitStatusConnectedRW:
				{
					newStatus = kNDASUnitStatusTryConnectRW;
				}
					break;
				case kNDASUnitStatusFailure:
				case kNDASUnitStatusNotPresent:
				{
					newStatus = fUnitDevice->Status();
				}
					break;
			}
		}
			break;
		case kNDASUnitStatusTryConnectRO:
		{
			if (kNDASUnitStatusConnectedRO == fUnitDevice->Status()) {
				newStatus = kNDASUnitStatusConnectedRO;
			}
		}
			break;
		case kNDASUnitStatusTryConnectRW:
		{
			if (kNDASUnitStatusConnectedRW == fUnitDevice->Status()) {
				newStatus = kNDASUnitStatusConnectedRW;
			}
		}
			break;
		case kNDASUnitStatusConnectedRO:
		{
			switch(fUnitDevice->Status()) {
				case kNDASUnitStatusDisconnected:
				case kNDASUnitStatusFailure:
				case kNDASUnitStatusNotPresent:
					newStatus = kNDASUnitStatusTryDisconnectRO;
					break;
				case kNDASUnitStatusReconnectRO:
					newStatus = kNDASUnitStatusReconnectRO;
					break;
			}
		}
			break;
		case kNDASUnitStatusConnectedRW:
		{
			switch(fUnitDevice->Status()) {
				case kNDASUnitStatusDisconnected:
				case kNDASUnitStatusFailure:
				case kNDASUnitStatusNotPresent:
					newStatus = kNDASUnitStatusTryDisconnectRW;
					break;
				case kNDASUnitStatusReconnectRW:
					newStatus = kNDASUnitStatusReconnectRW;
					break;
			}
		}
			break;
		case kNDASUnitStatusTryDisconnectRO:
		case kNDASUnitStatusTryDisconnectRW:
		{
		
			com_ximeta_driver_NDASLogicalDeviceController *controller = OSDynamicCast(com_ximeta_driver_NDASLogicalDeviceController, getClient());
			DbgIOASSERT(controller);
			
			if (!controller->isProtocolTransportNubAttached()) {
				newStatus = kNDASUnitStatusDisconnected;
			}

		}
			break;
		case kNDASUnitStatusReconnectRO:
		{
			switch (fUnitDevice->Status()) {
			case kNDASUnitStatusConnectedRO:
				newStatus = kNDASUnitStatusConnectedRO;
				break;
			case kNDASUnitStatusDisconnected:
			case kNDASUnitStatusFailure:
			case kNDASUnitStatusNotPresent:
				newStatus = kNDASUnitStatusTryDisconnectRO;
				break;
			}
		}
			break;
		case kNDASUnitStatusReconnectRW:
		{
			switch (fUnitDevice->Status()) {
				case kNDASUnitStatusConnectedRW:
					newStatus = kNDASUnitStatusConnectedRW;
					break;
				case kNDASUnitStatusDisconnected:
				case kNDASUnitStatusFailure:
				case kNDASUnitStatusNotPresent:
					newStatus = kNDASUnitStatusTryDisconnectRW;
					break;
			}
		}
			break;
		default:
			break;
	}

	if (prevStatus != newStatus) {
		DbgIOLog(DEBUG_MASK_NDAS_INFO, ("Status changed from %d to %d. Status of Unit %d\n", Status(), newStatus, prevStatus));
		
		// Send Message to BunEnumerator.
		sendNDASFamilyIOMessage(kNDASFamilyIOMessageLogicalDeviceStatusWasChanged, UnitDevice()->ID(), sizeof(GUID));
	}
	
	setStatus(newStatus);
	
	return Status();
}
Beispiel #4
0
//TODO: return here shared_ptr
RemoteClient* ClientInterface::getClientNoEx(u16 peer_id, ClientState state_min)
{
	auto client = getClient(peer_id, state_min);
	return client.get();
}
void Server::handleCommand_Init_Legacy(NetworkPacket* pkt) {
	const auto peer_id = pkt->getPeerId();
	auto & packet = *(pkt->packet);

	RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);

	std::string addr_s;
	try {
		addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
	} catch (std::exception &e) {
		/*
		 * no peer for this packet found
		 * most common reason is peer timeout, e.g. peer didn't
		 * respond for some time, your server was overloaded or
		 * things like that.
		 */
		infostream << "Server::ProcessData(): Canceling: peer "
		           << pkt->getPeerId() << " not found : " << e.what() << std::endl;
		return;
	}

	// If net_proto_version is set, this client has already been handled
	if(client->getState() > CS_Created) {
		verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
		              << addr_s << " (peer_id=" << peer_id << ")" << std::endl;
		return;
	}

	verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
	              << peer_id << ")" << std::endl;

	// Do not allow multiple players in simple singleplayer mode.
	// This isn't a perfect way to do it, but will suffice for now
	if(m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
		infostream << "Server: Not allowing another client (" << addr_s
		           << ") to connect in simple singleplayer mode" << std::endl;
		DenyAccess(peer_id, "Running in simple singleplayer mode.");
		return;
	}

	// First byte after command is maximum supported
	// serialization version
	u8 client_max;
	packet[TOSERVER_INIT_LEGACY_FMT].convert(client_max);
	u8 our_max = SER_FMT_VER_HIGHEST_READ;
	// Use the highest version supported by both
	int deployed = std::min(client_max, our_max);
	// If it's lower than the lowest supported, give up.
	if (deployed < SER_FMT_VER_LOWEST_READ)
		deployed = SER_FMT_VER_INVALID;

	if (deployed == SER_FMT_VER_INVALID) {
		actionstream << "Server: A mismatched client tried to connect from "
		             << addr_s << std::endl;
		infostream << "Server: Cannot negotiate serialization version with "
		           << addr_s << std::endl;
		DenyAccess(peer_id, std::string(
		               "Your client's version is not supported.\n"
		               "Server version is ")
		           + (g_version_string) + "."
		          );
		return;
	}

	client->setPendingSerializationVersion(deployed);

	/*
		Read and check network protocol version
	*/

	u16 min_net_proto_version = 0;
	packet[TOSERVER_INIT_LEGACY_PROTOCOL_VERSION_MIN].convert(min_net_proto_version);
	u16 max_net_proto_version = min_net_proto_version;
	packet[TOSERVER_INIT_LEGACY_PROTOCOL_VERSION_MAX].convert(max_net_proto_version);

	packet.convert_safe(TOSERVER_INIT_LEGACY_PROTOCOL_VERSION_FM, client->net_proto_version_fm);

	// Start with client's maximum version
	u16 net_proto_version = max_net_proto_version;

	// Figure out a working version if it is possible at all
	if(max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
	        min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
		// If maximum is larger than our maximum, go with our maximum
		if(max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
			net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
		// Else go with client's maximum
		else
			net_proto_version = max_net_proto_version;
	}

	verbosestream << "Server: " << addr_s << ": Protocol version: min: "
	              << min_net_proto_version << ", max: " << max_net_proto_version
	              << ", chosen: " << net_proto_version << std::endl;

	client->net_proto_version = net_proto_version;

	if(net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
	        net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
		actionstream << "Server: A mismatched client tried to connect from "
		             << addr_s << std::endl;
		DenyAccess(peer_id, std::string(
		               "Your client's version is not supported.\n"
		               "Server version is ")
		           + (g_version_string) + ",\n"
		           + "server's PROTOCOL_VERSION is "
		           + itos(SERVER_PROTOCOL_VERSION_MIN)
		           + "..."
		           + itos(SERVER_PROTOCOL_VERSION_MAX)
		           + ", client's PROTOCOL_VERSION is "
		           + itos(min_net_proto_version)
		           + "..."
		           + itos(max_net_proto_version)
		          );
		return;
	}

	if(g_settings->getBool("strict_protocol_version_checking")) {
		if(net_proto_version != LATEST_PROTOCOL_VERSION) {
			actionstream << "Server: A mismatched (strict) client tried to "
			             << "connect from " << addr_s << std::endl;
			DenyAccess(peer_id, std::string(
			               "Your client's version is not supported.\n"
			               "Server version is ")
			           + (g_version_string) + ",\n"
			           + "server's PROTOCOL_VERSION (strict) is "
			           + itos(LATEST_PROTOCOL_VERSION)
			           + ", client's PROTOCOL_VERSION is "
			           + itos(min_net_proto_version)
			           + "..."
			           + itos(max_net_proto_version)
			          );
			return;
		}
	}

	/*
		Set up player
	*/

	// Get player name
	std::string playername;
	packet[TOSERVER_INIT_LEGACY_NAME].convert(playername);

	if(playername.empty()) {
		actionstream << "Server: Player with an empty name "
		             << "tried to connect from " << addr_s << std::endl;
		DenyAccess(peer_id, "Empty name");
		return;
	}

	if(!g_settings->getBool("enable_any_name") && string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
		actionstream << "Server: Player with an invalid name [" << playername
		             << "] tried to connect from " << addr_s << std::endl;
		DenyAccess(peer_id, "Name contains unallowed characters");
		return;
	}

	if(!isSingleplayer() && playername == "singleplayer") {
		actionstream << "Server: Player with the name \"singleplayer\" "
		             << "tried to connect from " << addr_s << std::endl;
		DenyAccess(peer_id, "Name is not allowed");
		return;
	}

	{
		std::string reason;
		if(m_script->on_prejoinplayer(playername, addr_s, &reason)) {
			actionstream << "Server: Player with the name \"" << playername << "\" "
			             << "tried to connect from " << addr_s << " "
			             << "but it was disallowed for the following reason: "
			             << reason << std::endl;
			DenyAccess(peer_id, reason);
			return;
		}
	}

	infostream << "Server: New connection: \"" << playername << "\" from "
	           << addr_s << " (peer_id=" << peer_id << ")" << std::endl;

	// Get password
	std::string given_password;
	packet[TOSERVER_INIT_LEGACY_PASSWORD].convert(given_password);

	if(!base64_is_valid(given_password.c_str())) {
		actionstream << "Server: " << playername
		             << " supplied invalid password hash" << std::endl;
		DenyAccess(peer_id, "Invalid password hash");
		return;
	}

	// Enforce user limit.
	// Don't enforce for users that have some admin right
	if(m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
	        !checkPriv(playername, "server") &&
	        !checkPriv(playername, "ban") &&
	        !checkPriv(playername, "privs") &&
	        !checkPriv(playername, "password") &&
	        playername != g_settings->get("name")) {
		actionstream << "Server: " << playername << " tried to join, but there"
		             << " are already max_users="
		             << g_settings->getU16("max_users") << " players." << std::endl;
		DenyAccess(peer_id, "Too many users.");
		return;
	}

	std::string checkpwd; // Password hash to check against
	bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);

	// If no authentication info exists for user, create it
	if(!has_auth) {
		if(!isSingleplayer() &&
		        g_settings->getBool("disallow_empty_password") &&
		        given_password == "") {
			actionstream << "Server: " << playername
			             << " supplied empty password" << std::endl;
			DenyAccess(peer_id, "Empty passwords are "
			           "disallowed. Set a password and try again.");
			return;
		}
		std::string raw_default_password = g_settings->get("default_password");
		std::string initial_password =
		    translate_password(playername, raw_default_password);

		// If default_password is empty, allow any initial password
		if (raw_default_password.length() == 0)
			initial_password = given_password;

		m_script->createAuth(playername, initial_password);
	}

	has_auth = m_script->getAuth(playername, &checkpwd, NULL);

	if(!has_auth) {
		actionstream << "Server: " << playername << " cannot be authenticated"
		             << " (auth handler does not work?)" << std::endl;
		DenyAccess(peer_id, "Not allowed to login");
		return;
	}

	if(given_password != checkpwd) {
		actionstream << "Server: " << playername << " supplied wrong password"
		             << " at " << addr_s
		             << std::endl;
		DenyAccess(peer_id, "Wrong password");
		return;
	}

	RemotePlayer *player =
	    static_cast<RemotePlayer*>(m_env->getPlayer(playername.c_str()));

	if (player && player->peer_id != 0) {

		if (given_password.size()) {
			actionstream << "Server: " << playername << " rejoining" << std::endl;
			DenyAccessVerCompliant(player->peer_id, player->protocol_version, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
			player->getPlayerSAO()->removingFromEnvironment();
			m_env->removePlayer(player);
			player = nullptr;
		} else {
			errorstream << "Server: " << playername << ": Failed to emerge player" << " (player allocated to an another client)" << std::endl;
			DenyAccess(peer_id, "Another client is connected with this "
			           "name. If your client closed unexpectedly, try again in "
			           "a minute.");
		}
	}

	m_clients.setPlayerName(peer_id, playername);

	/*
		Answer with a TOCLIENT_INIT
	*/
	{
		MSGPACK_PACKET_INIT(TOCLIENT_INIT_LEGACY, 6);
		PACK(TOCLIENT_INIT_DEPLOYED, deployed);
		PACK(TOCLIENT_INIT_SEED, m_env->getServerMap().getSeed());
		PACK(TOCLIENT_INIT_STEP, g_settings->getFloat("dedicated_server_step"));

		//if (player) //todo : remake me
		//	PACK(TOCLIENT_INIT_POS, player->getPosition());

		Settings params;
		m_emerge->params.save(params);
		PACK(TOCLIENT_INIT_MAP_PARAMS, params);

		PACK(TOCLIENT_INIT_PROTOCOL_VERSION_FM, SERVER_PROTOCOL_VERSION_FM);

		PACK(TOCLIENT_INIT_WEATHER, g_settings->getBool("weather"));

		// Send as reliable
		m_clients.send(peer_id, 0, buffer, true);
		m_clients.event(peer_id, CSE_InitLegacy);
	}

	return;
}
Beispiel #6
0
bool HypothesisClient::isClient(int id) {
	return (getClient(id)!= NULL);
}
Beispiel #7
0
// send_respawn()
int ModApiClient::l_send_respawn(lua_State *L)
{
	getClient(L)->sendRespawn();
	return 0;
}
Beispiel #8
0
void Call::setState(call_state st)
{
	log(LOG_ALL, "call %d[%d->%d] state: %s->%s", getID(), getClient(), getTranslator(), StateToString(state), StateToString(st));
	state = st;
}
//--------------------------
bool ofxTCPServer::isClientConnected(int clientID) {
    std::unique_lock<std::mutex> lck( mConnectionsLock );
    return isClientSetup(clientID) && getClient(clientID).isConnected();
}
Beispiel #10
0
string ClientManager::getHubName(const HintedUser& user) const {
	Lock l(cs);
	auto ou = findOnlineUserHint(user);
	return ou ? ou->getClient().getHubName() : _("Offline");
}
void Logic::getCommand(unsigned short proto_type, google::protobuf::Message* proto)
{
    QMutexLocker locker(&mutex);
    TipArea *tipArea;
    DecisionArea* decisionArea;
    BPArea* bpArea;
    SafeList<int> roleIDs;
    PlayerArea* playerArea;
    int targetID,roleID,howMany,num;
    QString arg[10];

    network::RoleRequest* char_pick;

    switch (proto_type)
    {
    case network::MSG_ROOMLIST_REP:
        lobby->fill((network::RoomListResponse*) proto);
        break;

    case network::MSG_GAME:
    {
        network::GameInfo* game_info = (network::GameInfo*) proto;
        if(game_info->has_player_id()){
            myID = game_info->player_id();
            dataInterface->setID(myID);            
            cleanRoom();
            if(myID == GUEST)
                gui->logAppend(QStringLiteral("<font color=\'pink\'>房间已满,进入观战模式</font>"));
            else
                gui->logAppend(QStringLiteral("<font color=\'pink\'>请准备</font>"));
        }
        if(game_info->has_room_id()){
            gui->getTeamArea()->setRoomID(game_info->room_id());
        }
        setupRoom(game_info->is_started(), game_info);

        for (int i = 0; i < game_info->player_infos_size(); ++i)
        {
            network::SinglePlayerInfo* player_info = (network::SinglePlayerInfo*)&(game_info->player_infos(i));
            targetID = player_info->id();
            if(player_info->has_role_id())
            {
                roleID = player_info->role_id();
                roles[targetID] = roleID;
                count++;
            }
            if(player_info->has_nickname()){
                dataInterface->setNickName(targetID, QString::fromStdString(player_info->nickname()));
            }
            if(player_info->has_team()){
                dataInterface->getPlayerById(targetID)->setTeam(player_info->team());
            }
            gui->getPlayerArea()->getPlayerItem(targetID)->setReady(player_info->ready());
        }

        if(count==dataInterface->getPlayerMax())
        {
            disconnect(getClient(),0,this,0);
            disconnect(gui->getDecisionArea(), 0, this, 0);
            for(int i=0;i<dataInterface->getPlayerMax();i++){
                dataInterface->getPlayerList().at(i)->setRole(roles[i]);
                gui->getPlayerArea()->getPlayerItem(i)->setToolTip(dataInterface->getRoleSkillInfo(roles[i]));
            }

            roleID = myID == GUEST ? roles[0] : roles[myID];
            setMyRole(roleID);
            network::GameInfo* toRole = new network::GameInfo;
            toRole->CopyFrom(*game_info);
            myRole->decipher(network::MSG_GAME, toRole);
        }
        gui->getPlayerArea()->update();
        break;
    }
    case network::MSG_GOSSIP:
        if(gui!=NULL)
        {
            network::Gossip* gossip = (network::Gossip*) proto;
            gui->chatAppend(gossip->id(), QString::fromStdString(gossip->txt()));
        }
        break;
    case network::MSG_ERROR:
    {
        network::Error* error = (network::Error*)proto;
        if(error->dst_id() == myID){
            gui->reset();
        }
        switch(error->id())
        {
        //GE_DISCONNECTED
        case GE_DISCONNECTED:
        {
            int targetId = error->dst_id();
            gui->logAppend(QStringLiteral("<font color=\'red\'>玩家") + QString::number(targetId) + QStringLiteral("离开房间</font>"));
            dataInterface->setNickName(targetId, "");
            dataInterface->getPlayerById(targetId)->setTeam(-1);
            gui->getPlayerArea()->getPlayerItem(targetId)->setReady(false);
            gui->getPlayerArea()->update();
            break;
        }
        case GE_NOT_WELCOME:
            gui->logAppend(QStringLiteral("<font color=\'red\'>这个房主比较高冷,下个房间见。。</font>"));
            break;
        case GE_WRONG_PASSWORD:
            gui->logAppend(QStringLiteral("<font color=\'red\'>瞎蒙果然是不行的。。</font>"));
            break;
        default:
            gui->logAppend(QStringLiteral("<font color=\'red\'>错误代码") + QString::number(error->id()) + "</font>");
            break;
        }
        break;
    }
//选择角色
    case network::MSG_ROLE_REQ:
        state=46;
        char_pick = (network::RoleRequest*) proto;

        tipArea=gui->getTipArea();
        decisionArea=gui->getDecisionArea();
        tipArea->reset();        
        howMany=char_pick->role_ids_size();
        for(int i=0;i<howMany;i++){
            roleID=char_pick->role_ids(i);
            tipArea->addBoxItem(QString::number(roleID)+"."+dataInterface->getRoleName(roleID));
        }
        tipArea->setMsg(QStringLiteral("请选择角色:"));
        tipArea->showBox();
        decisionArea->enable(0);
        gui->alert();
        break;
    case 51:
        // TODO:BP模式,暂不可用
        state = 51;
        tipArea=gui->getTipArea();
        decisionArea=gui->getDecisionArea();
        bpArea = gui->getBPArea();
        tipArea->reset();
        connect(decisionArea,SIGNAL(okClicked()),this,SLOT(onOkClicked()));
        connect(bpArea,SIGNAL(roleReady()),this,SLOT(roleAnalyse()));
        num = arg[1].toInt();

        for(int i=0;i<num;i++)
        {
            roleIDs<<arg[i+2].toInt();
        }

        bpArea->BPStart(num, roleIDs);
        break;
    case 52:
        // TODO:BP模式,暂不可用
        state = 52;
        bpArea = gui->getBPArea();
        bpArea->setMsg("请禁用一角色");
        bpArea->setQuota(1);
        bpArea->enableAll();
        playerArea = gui->getPlayerArea();
        gui->alert();
        break;
    case 55:
        // TODO:BP模式,暂不可用
        state = 55;
        bpArea = gui->getBPArea();
        bpArea->setMsg("请选择一角色");
        bpArea->setQuota(1);
        bpArea->enableAll();
        playerArea = gui->getPlayerArea();
        gui->alert();
        break;
    case 54:
        //  TODO:BP模式,暂不可用
        bpArea = gui->getBPArea();
        bpArea->ban(arg[1].toInt(), arg[2].toInt());
        break;
    case 57:
        //  TODO:BP模式,暂不可用
        bpArea = gui->getBPArea();
        bpArea->choose(arg[1].toInt(), arg[2].toInt());
        decisionArea = gui->getDecisionArea();
        if(bpArea->checkOver())
        {
            bpArea->setVisible(0);
            disconnect(decisionArea,SIGNAL(okClicked()),this,SLOT(onOkClicked()));
            disconnect(bpArea,SIGNAL(roleReady()),this,SLOT(roleAnalyse()));
        }
        break;
    case 59:
        //  TODO:BP模式,暂不可用
        if(gui!=NULL)
            gui->chatAppend(arg[1].toInt(),arg[2]);
        break;
    }
    delete proto;
}
Beispiel #12
0
co::CommandQueue* Server::getCommandThreadQueue() 
{
    return getClient()->getCommandThreadQueue();
}
PRL_RESULT Task_VzManager::clone_env()
{
	PRL_RESULT res;

	CProtoCommandPtr cmd = CProtoSerializer::ParseCommand( getRequestPackage() );
	if (!cmd->IsValid())
		return PRL_ERR_UNRECOGNIZED_REQUEST;

	CProtoVmCloneCommand *pCmd = CProtoSerializer::CastToProtoCommand<CProtoVmCloneCommand>(cmd);

	QString sUuid = pCmd->GetVmUuid();
	QString sNewHome = pCmd->GetVmHomePath();
	QString sNewName = pCmd->GetVmName();
	unsigned int nFlags = pCmd->GetCommandFlags();

	if (sNewName.isEmpty())
		return PRL_ERR_VM_NAME_IS_EMPTY;

	res = check_env_state(PVE::DspCmdDirVmClone, sUuid);
	if (PRL_FAILED(res))
		return res;

	SmartPtr<CVmConfiguration> pConfig = getVzHelper()->getCtConfig(getClient(), sUuid);
	if (!pConfig)
	{
		WRITE_TRACE(DBG_FATAL, "Unable to find CT by uuid %s", QSTR2UTF8(sUuid));
		return PRL_ERR_VM_GET_CONFIG_FAILED;
	}

	SmartPtr<CVmConfiguration> pNewConfig(new CVmConfiguration);

	if (!pCmd->GetNewVmUuid().isEmpty())
		pNewConfig->getVmIdentification()->setVmUuid(pCmd->GetNewVmUuid());

	CVmDirectory::TemporaryCatalogueItem vmInfo(
			pNewConfig->getVmIdentification()->getVmUuid(),
			QString(),
			sNewName);

	res = checkAndLockRegisterParameters(&vmInfo);
	if (PRL_FAILED(res))
		return res;

	res = get_op_helper()->clone_env(pConfig, sNewHome, sNewName, nFlags, pNewConfig);
	if (PRL_SUCCEEDED(res)) {
		res = getVzHelper()->insertVmDirectoryItem(pNewConfig);
		if (PRL_FAILED(res))
			get_op_helper()->delete_env(
					pNewConfig->getVmIdentification()->getVmUuid());
	}
	// delete temporary registration
	CDspService::instance()->getVmDirManager()
		.unlockExclusiveVmParameters(&vmInfo);

	if (PRL_FAILED(res) || !pNewConfig.isValid())
		return res;

	SmartPtr<CVmConfiguration> pOldConfig(new CVmConfiguration(pNewConfig->toString()));

	bool isTemplate = (nFlags & PCVF_CLONE_TO_TEMPLATE);
	pNewConfig->getVmSettings()->getVmCommonOptions()->setTemplate(isTemplate);

	Task_CloneVm::ResetNetSettings(pNewConfig);
	Backup::Device::Dao(pNewConfig).deleteAll();

	get_op_helper()->apply_env_config(pNewConfig, pOldConfig, PVCF_DESTROY_HDD_BUNDLE);

	getResponseCmd()->SetVmConfig(pNewConfig->toString());
	{
	       CVmEvent event(PET_DSP_EVT_VM_ADDED,
			       pNewConfig->getVmIdentification()->getVmUuid(),
			       PIE_DISPATCHER);
	       SmartPtr<IOPackage> p = DispatcherPackage::createInstance(PVE::DspVmEvent, event);
	       CDspService::instance()->getClientManager().sendPackageToAllClients(p);
	}
	// Set some parameters in the response (see Task_CloneVm)
	CDspLockedPointer<CVmEvent> pParams = getTaskParameters();

	pParams->addEventParameter(
			new CVmEventParameter( PVE::String,
				pNewConfig->getVmIdentification()->getVmUuid(),
				EVT_PARAM_DISP_TASK_CLONE_VM_UUID ) );
	pParams->addEventParameter(
			new CVmEventParameter( PVE::String,
				pNewConfig->getVmIdentification()->getVmName(),
				EVT_PARAM_DISP_TASK_CLONE_NEW_VM_NAME ) );
	pParams->addEventParameter(
			new CVmEventParameter( PVE::String,
				pNewConfig->getVmIdentification()->getHomePath(),
				EVT_PARAM_DISP_TASK_CLONE_NEW_VM_ROOT_DIR ) );
	pParams->addEventParameter(
			new CVmEventParameter( PVE::Boolean,
				QString("%1").arg(isTemplate),
				EVT_PARAM_DISP_TASK_CLONE_AS_TEMPLATE ) );
	return PRL_ERR_SUCCESS;
}
PRL_RESULT Task_VzManager::editConfig()
{
	PRL_RESULT res;

	CProtoCommandPtr cmd = CProtoSerializer::ParseCommand( getRequestPackage() );
	if ( ! cmd->IsValid() )
		return PRL_ERR_UNRECOGNIZED_REQUEST;

	SmartPtr<CVmConfiguration> pConfig( new CVmConfiguration( cmd->GetFirstStrParam() ) );
	if( !IS_OPERATION_SUCCEEDED( pConfig->m_uiRcInit ) )
	{
		PRL_RESULT code = PRL_ERR_PARSE_VM_CONFIG;
		WRITE_TRACE(DBG_FATAL, "Error occurred while modification CT configuration: %s",
				PRL_RESULT_TO_STRING( code ) );
		return code;
	}
	QString sUuid = pConfig->getVmIdentification()->getVmUuid();
	SmartPtr<CVmConfiguration> pOldConfig = getVzHelper()->getCtConfig(getClient(), sUuid);
	if (!pOldConfig)
		return PRL_ERR_VM_GET_CONFIG_FAILED;

        QString oldname = pOldConfig->getVmIdentification()->getVmName();
        QString name = pConfig->getVmIdentification()->getVmName();

	QStringList lstFullItemIds;
	pConfig->diffDocuments(pOldConfig.getImpl(), lstFullItemIds);

	// Code below prohibits all other than Hdd and Network devices for Containers
	if (!lstFullItemIds.filter(QRegExp("Hardware\\.(?!Hdd|Network|Cpu|Memory)")).isEmpty())
		return PRL_ERR_ACTION_NOT_SUPPORTED_FOR_CT;
	// Handle the Firewall settings change on the running CT
	if (!lstFullItemIds.filter(QRegExp("\\.(?=Firewall\\.|MAC|NetAddress)")).isEmpty()) {
		VIRTUAL_MACHINE_STATE nState = VMS_UNKNOWN;
		PRL_RESULT res = getVzHelper()->getVzlibHelper().get_env_status(sUuid, nState);
		if (nState == VMS_RUNNING) {
			res = setupFirewall(pConfig);
			if (PRL_FAILED(res))
				return res;
		}
	}

	// Handle Name change
	if (oldname != name) {
		QString vm_uuid; // Skip uuid check
		QString vm_name = name;
		QString vm_home;

		// Lock the new name in the VmDirectory
		CVmDirectory::TemporaryCatalogueItem vmInfo( vm_uuid, vm_home, vm_name);
		res = checkAndLockRegisterParameters(&vmInfo);
		if (PRL_FAILED(res))
			return res;

		res = get_op_helper()->set_env_name(sUuid, name);
		if (PRL_SUCCEEDED(res)) {
			CDspLockedPointer< CVmDirectoryItem >
				pVmDirItem = CDspService::instance()->getVmDirManager()
				.getVmDirItemByUuid(m_sVzDirUuid, sUuid );

			if (!pVmDirItem) {
				WRITE_TRACE(DBG_FATAL, "Can't found VmDirItem by vmUuid = %s",
						QSTR2UTF8(sUuid));
			} else {
				pVmDirItem->setVmName(name);
				PRL_RESULT ret = CDspService::instance()->getVmDirManager().updateVmDirItem(pVmDirItem);
				if (PRL_FAILED(ret) )
					WRITE_TRACE(DBG_FATAL, "Can't update Container %s VmCatalogue by error: %s",
						QSTR2UTF8(sUuid), PRL_RESULT_TO_STRING(ret));
			}
		}

		// delete temporary registration
		CDspService::instance()->getVmDirManager()
			.unlockExclusiveVmParameters(&vmInfo);

		if (PRL_FAILED(res))
			return res;
	}

	// reset IP addresses for CT templates
	Task_EditVm::resetNetworkAddressesFromVmConfig(pConfig, pOldConfig);

	// update High Availability Cluster resource
	if (pConfig->getVmSettings()->getHighAvailability()->toString() !=
			pOldConfig->getVmSettings()->getHighAvailability()->toString()
		&& CFileHelper::isSharedFS(pConfig->getVmIdentification()->getHomePath())) {
		res = CDspService::instance()->getHaClusterHelper()->updateClusterResourceParams(
				sUuid,
				pOldConfig->getVmSettings()->getHighAvailability(),
				pConfig->getVmSettings()->getHighAvailability(),
				pConfig->getVmIdentification()->getHomePath(),
				PVT_CT);
		if (PRL_FAILED(res))
			return res;
	}

	CVmRemoteDisplay* oldD = pOldConfig->getVmSettings()->getVmRemoteDisplay();
	CVmRemoteDisplay* newD = pConfig->getVmSettings()->getVmRemoteDisplay();

	if (oldD->getPassword() != newD->getPassword()) {
		if (newD->getPassword().length() > PRL_VM_REMOTE_DISPLAY_MAX_PASS_LEN) {
			WRITE_TRACE(DBG_FATAL, "The specified remote display password is too long.");
			getLastError()->addEventParameter(
				new CVmEventParameter(
					PVE::UnsignedInt,
					QString::number(PRL_VM_REMOTE_DISPLAY_MAX_PASS_LEN),
					EVT_PARAM_MESSAGE_PARAM_0));

			return PRL_ERR_VMCONF_REMOTE_DISPLAY_PASSWORD_TOO_LONG;
		}
	}

	Backup::Device::Service service(pOldConfig);
	service.setContext(*this).setVmHome(pConfig->getVmIdentification()->getHomePath());
	Backup::Device::Details::Transition t = service.getTransition(pConfig);
	res = t.plant();
	if (PRL_FAILED(res))
		return res;

	res = get_op_helper()->apply_env_config(pConfig, pOldConfig, cmd->GetCommandFlags());
	if (PRL_FAILED(res))
		return res;

	res = t.remove();
	if (PRL_FAILED(res))
		return res;

	// Invalidate cache
	CDspService::instance()->getVzHelper()->getConfigCache().
		remove(pConfig->getVmIdentification()->getHomePath());

	res = changeVNCServerState(pOldConfig, pConfig, sUuid);
	if (PRL_FAILED(res))
		return res;

	// Handle memory limit change
	unsigned int newRamSize = pConfig->getVmHardwareList()->getMemory()->getRamSize();
	unsigned int oldRamSize = pOldConfig->getVmHardwareList()->getMemory()->getRamSize();
	if (newRamSize != oldRamSize) {
		VIRTUAL_MACHINE_STATE nState = VMS_UNKNOWN;
		PRL_RESULT res = getVzHelper()->getVzlibHelper().get_env_status(sUuid, nState);
		if (PRL_SUCCEEDED(res) && (nState == VMS_RUNNING))
			adjustReservedMemLimit((long long)newRamSize - oldRamSize);
	}

	QStringList lstAdd, lstDel;
	// Handle application templates
	QStringList newAppTemplates = pConfig->getCtSettings()->getAppTemplate();
	QStringList oldAppTemplates = pOldConfig->getCtSettings()->getAppTemplate();

	for (int i = 0; i < newAppTemplates.size(); i++) {
		if (newAppTemplates.at(i).startsWith('.'))
			newAppTemplates[i].remove(0, 1);
	}
	for (int i = 0; i < oldAppTemplates.size(); i++) {
		if (oldAppTemplates.at(i).startsWith('.'))
			oldAppTemplates[i].remove(0, 1);
	}

	if (newAppTemplates == oldAppTemplates)
		goto ok;

	foreach(QString str, newAppTemplates)
		if (!oldAppTemplates.contains(str))
			lstAdd.append(str);
	foreach(QString str, oldAppTemplates)
		if (!newAppTemplates.contains(str))
			lstDel.append(str);

	do {
		CVzTemplateHelper TmplHelper = getVzHelper()->getVzTemplateHelper();
		res = TmplHelper.remove_templates_env(sUuid, lstDel);
		if (PRL_FAILED(res))
			return res;

		res = TmplHelper.install_templates_env(sUuid, lstAdd);
	} while (0);

ok:
	if ( PRL_SUCCEEDED(res) ) {
		SmartPtr<CVmConfiguration> pNewConfig = getVzHelper()->getCtConfig(getClient(), sUuid);
		QStringList lstParams(pNewConfig ?
				pNewConfig->toString() : pConfig->toString());
		getResponseCmd()->SetParamsList( lstParams );

		sendEvent(PET_DSP_EVT_VM_CONFIG_CHANGED, sUuid);
	}

	return res;
}
void Logic::getCommand(unsigned short proto_type, google::protobuf::Message* proto)
{
    TipArea *tipArea;
    DecisionArea* decisionArea;
    BPArea* bpArea;
    SafeList<int> roleIDs;
    SafeList<int> options;
    PlayerArea* playerArea;
    int targetID,roleID,howMany;    

    network::RoleRequest* char_pick;
    int targetId;
    switch (proto_type)
    {
    case network::MSG_ROOMLIST_REP:
        lobby->fill((network::RoomListResponse*) proto);
        break;
    case network::MSG_GAME:
    {
        network::GameInfo* game_info = (network::GameInfo*) proto;
        if(game_info->has_player_id()){
            myID = game_info->player_id();
            dataInterface->setID(myID);
            cleanRoom();
            if(myID == GUEST)
                gui->logAppend(QStringLiteral("<font color=\'pink\'>房间已满,进入观战模式</font>"));
            else{
                gui->logAppend(QStringLiteral("<font color=\'pink\'>请准备</font>"));
                gui->logAppend(QStringLiteral("<font color=\'pink\'>觉得某人烦的话,可以“mute n”,n是该玩家座次;“unmute n”恢复</font>"));
            }
        }
        if(game_info->has_room_id()){
            gui->getTeamArea()->setRoomID(game_info->room_id());
        }
        int count = 0;

        setupRoom(game_info -> is_started(), game_info);

        for (int i = 0; i < game_info->player_infos_size(); ++i)
        {
            network::SinglePlayerInfo* player_info = (network::SinglePlayerInfo*)&(game_info->player_infos(i));
            targetID = player_info->id();
            if(player_info->has_role_id())
            {
                roleID = player_info->role_id();
                roles[targetID] = roleID;
                dataInterface->getPlayerList().at(targetID)->setRole(roleID);
                gui->getPlayerArea()->getPlayerItem(targetID)->setToolTip(dataInterface->getRoleSkillInfo(roleID));
				count++;
            }
            if(player_info->has_nickname()){
                dataInterface->setNickName(targetID, QString::fromStdString(player_info->nickname()));
            }
            if(player_info->has_team()){
                dataInterface->getPlayerById(targetID)->setTeam(player_info->team());
            }
            gui->getPlayerArea()->getPlayerItem(targetID)->setReady(player_info->ready());
            if(player_info->has_leader()){
                gui->getPlayerArea()->getPlayerItem(targetID)->setLeader(player_info->leader());
            }
        }


        if(count == dataInterface->getPlayerMax())
        {
            disconnect(getClient(),0,this,0);
            disconnect(gui->getDecisionArea(), 0, this, 0);
            disconnect(gui->getBPArea(),0,this,0);

            roleID = myID == GUEST ? roles[0] : roles[myID];
            setMyRole(roleID);
            network::GameInfo* toRole = new network::GameInfo;
            toRole->CopyFrom(*game_info);
            myRole->decipher(network::MSG_GAME, toRole);
            gui->hideBP();
        }
        gui->getPlayerArea()->update();
        break;
    }

    case network::MSG_BECOME_LEADER_REQ:
        state = 60;
        gui->reset();
        tipArea = gui->getTipArea();
        tipArea->setMsg(QStringLiteral("要申请做队长吗?"));

        decisionArea = gui->getDecisionArea();
        decisionArea->enable(0);
        decisionArea->enable(1);
        gui->alert();
        break;

    case network::MSG_GOSSIP:
        if(gui!=NULL)
        {
            network::Gossip* gossip = (network::Gossip*)proto;
            switch (gossip->type())
            {
            case network::GOSSIP_TALK:
                gui->chatAppend(gossip->id(), QString(gossip->txt().c_str()));
                break;
            case network::GOSSIP_NOTICE:
                gui->logAppend(QString(gossip->txt().c_str()));
                break;
            }
        }
        break;
    case network::MSG_ERROR:
    {
        network::Error* error = (network::Error*)proto;
        if(error->dst_id() == myID){
            gui->reset();
        }
        switch(error->id())
        {
        case GE_DISCONNECTED:
        {
            int targetId = error->dst_id();
            gui->logAppend(QStringLiteral("<font color=\'red\'>玩家") + QString::number(targetId) + QStringLiteral("离开房间</font>"));
            dataInterface->setNickName(targetId, "");
            dataInterface->getPlayerById(targetId)->setTeam(-1);
            gui->getPlayerArea()->getPlayerItem(targetId)->setReady(false);
            gui->getPlayerArea()->update();
            break;
        }
        case GE_NOT_WELCOME:
            gui->logAppend(QStringLiteral("<font color=\'red\'>这个房主比较高冷,下个房间见。。</font>"));
            break;
        case GE_WRONG_PASSWORD:
            gui->logAppend(QStringLiteral("<font color=\'red\'>瞎蒙果然是不行的。。</font>"));
            break;
        default:
            gui->logAppend(QStringLiteral("<font color=\'red\'>错误代码") + QString::number(error->id()) + "</font>");
            break;
            }
        break;
    }
//选择角色
    case network::MSG_ROLE_REQ:
    {
        char_pick = (network::RoleRequest*) proto;
        targetId = char_pick->id();
        if(char_pick->strategy() == ROLE_STRATEGY_31)
        {
            gui->logAppend(QStringLiteral("<font color=\'white\'>等待玩家") + QString::number(targetId) + QStringLiteral("选择角色")+"</front");
            if(targetId != myID)
                break;
            state=46;
            tipArea=gui->getTipArea();
            decisionArea=gui->getDecisionArea();
            tipArea->reset();
            howMany=char_pick->role_ids_size();
            for(int i=0;i<howMany;i++){
                roleID=char_pick->role_ids(i);
                tipArea->addBoxItem(QString::number(roleID)+"."+dataInterface->getRoleName(roleID));
            }
            tipArea->setMsg(QStringLiteral("请选择角色:"));
            tipArea->showBox();
            decisionArea->enable(0);
            gui->alert();
            break;
        }
        else if(char_pick->strategy() == ROLE_STRATEGY_BP)
        {
            state = 51;
            tipArea=gui->getTipArea();
            decisionArea=gui->getDecisionArea();
            bpArea = gui->getBPArea();
            tipArea->reset();
            howMany=char_pick->role_ids_size();
            for(int i=0;i<howMany;i++){
                roleIDs << char_pick->role_ids(i);
                options << char_pick->args(i);
            }
            bpArea->BPStart(howMany, roleIDs, options, char_pick->opration());
            if(char_pick->opration() ==  BP_NULL )
            {
                int lastChosen = -1;
                int step = 0;
                for(int i = 0; i < howMany; i++){
                    if(options[i] > step){
                        step = options[i];
                        lastChosen = i;
                    }
                }
                if(step == 0){
                    gui->logAppend(QStringLiteral("以下英雄响应了召唤:"));
                    QString msg;
                    foreach(int id, roleIDs)
                        msg += QStringLiteral("<font color=\'yellow\'>%1 </font>").arg(dataInterface->getRoleName(id));
                    gui->logAppend(msg);
                }
                else {
                    QString msg = QStringLiteral("<font color=\'yellow\'>%1</font> %2 了<font color=\'yellow\'>%3</font>");
                    QString nickname = dataInterface->getPlayerList().at(targetId)->getNickname();
                    gui->logAppend(msg.arg(nickname, ((options[lastChosen]-1) % 4) < 2 ? "BAN" : "PICK", dataInterface->getRoleName(roleIDs[lastChosen])));
                }
            }
bool gmshLocalNetworkClient::run()
{
 new_connection:
  setPid(0); // dummy pid, should be non-negative

  onelabGmshServer *server = new onelabGmshServer(this);

  int sock = server->LaunchClient();

  if(sock < 0){
    // could not establish the connection: aborting
    server->Shutdown();
    delete server;
    return false;
  }

  Msg::StatusBar(true, "Running '%s'...", _name.c_str());

  setGmshServer(server);

  while(1) {
    if(getExecutable().empty() && !CTX::instance()->solver.listen){
      // we stopped listening to the special "Listen" client
      break;
    }

    // loop over all the clients (usually only one, but can be more if we
    // spawned subclients) and check if data is available for one of them
    bool stop = false, haveData = false;
    gmshLocalNetworkClient *c = 0;
    std::vector<gmshLocalNetworkClient*> toDelete;
    for(int i = 0; i < getNumClients(); i++){
      c = getClient(i);
      if(c->getPid() < 0){
        if(c == this){ // the "master" client stopped
          stop = true;
          break;
        }
        else{
          // this subclient is not active anymore: shut down and delete its
          // server and mark the client for deletion
          GmshServer *s = c->getGmshServer();
          c->setGmshServer(0);
          c->setFather(0);
          if(s){
            s->Shutdown();
            delete s;
          }
          toDelete.push_back(c);
          continue;
        }
      }
      GmshServer *s = c->getGmshServer();
      if(!s){
        Msg::Error("Abnormal server termination (no valid server)");
        stop = true;
        break;
      }
      else{
        int ret = s->NonBlockingWait(0.001, -1.);
        if(ret == 0){ // we have data from this particular client
          haveData = true;
          break;
        }
        else if(ret == 3){ // pass to the next client
          continue;
        }
        else{ // an error occurred
          stop = true;
          break;
        }
      }
    }
    for(unsigned int i = 0; i < toDelete.size(); i++){
      removeClient(toDelete[i]);
      delete toDelete[i];
    }

    // break the while(1) if the master client has stopped or if we encountered
    // a problem
    if(stop) break;

    // if data is available try to get the message from the corresponding
    // client; break the while(1) if we could not receive the message
    if(haveData && !c->receiveMessage(this)) break;

    // break the while(1) if the master client has stopped
    if(c == this && c->getPid() < 0) break;
  }

  // we are done running the (master) client: delete the servers and the
  // subclients, if any remain (they should have been deleted already).
  std::vector<gmshLocalNetworkClient*> toDelete;
  for(int i = 0; i < getNumClients(); i++){
    gmshLocalNetworkClient *c = getClient(i);
    GmshServer *s = c->getGmshServer();
    c->setGmshServer(0);
    c->setFather(0);
    if(s){
      s->Shutdown();
      delete s;
    }
    if(c != this){
      if(c->getPid() > 0)
        Msg::Error("Subclient %s was not stopped correctly", c->getName().c_str());
      toDelete.push_back(c);
    }
  }
  for(unsigned int i = 0; i < toDelete.size(); i++){
    removeClient(toDelete[i]);
    delete toDelete[i];
  }

  Msg::StatusBar(true, "Done running '%s'", _name.c_str());

  if(getExecutable().empty()){
    Msg::Info("Client disconnected: starting new connection");
    goto new_connection;
  }

  return true;
}
bool CreatureObject::unpilotShip()
{
	//-- Only do this on the authoritative pilot.
	if (!isAuthoritative())
	{
		DEBUG_REPORT_LOG(true, ("CreatureObject::unpilotShip(): server id=[%d], ship id=[%s], skipping call because ship is not authoritative.",
			static_cast<int>(GameServer::getInstance().getProcessId()),
			getNetworkId().getValueString().c_str()));
		return false;
	}

	//-- Ensure ships are enabled.
	if (!ConfigServerGame::getShipsEnabled())
		return false;

	bool unpilotedShip = false;

	ShipObject* ship = getPilotedShip();
	if (!ship)
		return false;

	ServerObject * const containingObject = NON_NULL(safe_cast<ServerObject *>(ContainerInterface::getContainedByObject(*this)));

	// If directly contained by a ship, we use the pilot slot, else we use the pob pilot slot
	SlotId const pilotSlotId = containingObject->asShipObject() ? ShipSlotIdManager::getShipPilotSlotId() : ShipSlotIdManager::getPobShipPilotSlotId();

	// If this creature is piloting the ship, he is in the pilot slot of either the ship or an object contained by a cell of the ship.
	SlottedContainer * const slottedContainer = ContainerInterface::getSlottedContainer(*containingObject);
	if (slottedContainer)
	{
		//-- Check for a pilot.
		Container::ContainerErrorCode errorCode = Container::CEC_Success;
		CachedNetworkId pilotId = slottedContainer->getObjectInSlot(pilotSlotId, errorCode);
		if (errorCode == Container::CEC_Success)
		{
			ServerObject * const pilot = safe_cast<ServerObject*>(pilotId.getObject());
			FATAL(pilot != this, ("Somehow told to unpilot a ship when we are not the pilot of the ship!"));

			// Transfer pilot to location of the object it was contained by, which may or may not have been the ship, but it something with a pilot slot.
			CellObject * const destCell = dynamic_cast<CellObject *>(containingObject->getAttachedTo());
			if (destCell)
			{
				Transform tr(containingObject->getTransform_o2p());
				// push them back a meter as well if they are unpiloting a pob ship
				if (!containingObject->asShipObject())
					tr.move_l(Vector(0.f, 0.f, -1.f));
				IGNORE_RETURN(ContainerInterface::transferItemToCell(*destCell, *this, tr, 0, errorCode));
			}
			else
				IGNORE_RETURN(ContainerInterface::transferItemToWorld(*this, containingObject->getTransform_o2w(), 0, errorCode));
			if (errorCode == Container::CEC_Success)
				unpilotedShip = true;
		}
	}

	Client * const client = getClient();
	if (client)
	{
		client->removeControlledObject(*ship);
		// make sure the client can start receiving updates for the ship
		ShipClientUpdateTracker::queueForUpdate(*client, *ship);
	}

	return unpilotedShip;
}
Beispiel #18
0
int             main(int ac, char **av)
{
	std::string s;
	std::string token;
	size_t pos;
	Instruction instruct(Instruction::KO);
	ISocket *servTcp = getClient();

	/*
	try
	{
	servTcp->attachOnReceive(&recvHandler);
	instruct.setInstruct(Instruction::CONNEXION);
	instruct.addName("fabY");
	servTcp->writePacket(Packet::pack(instruct));
	#ifdef _WIN_32
	Sleep(100);
	#else
	usleep(10000);
	#endif

	instruct.setInstruct(Instruction::CREATE_ROOM);
	servTcp->writePacket(Packet::pack(instruct));
	#ifdef _WIN_32
	Sleep(100);
	#else
	usleep(10000);
	#endif

	instruct.setInstruct(Instruction::START_GAME);
	servTcp->writePacket(Packet::pack(instruct));
	#ifdef _WIN_32
	Sleep(100);
	#else
	usleep(10000);
	#endif

	game();
	}
	catch (BBException &err)
	{
	std::cerr << err.what() << std::endl;
	system("pause");
	}
	*/

	while (s != "quit") {

		instruct.eraseNames();
		std::getline(std::cin, s);

		if ((pos = s.find(" ")) != s.npos)
		{
			token = s.substr(0, pos);
			if (token == "connect")
				instruct.setInstruct(Instruction::CONNEXION);
			else if (token == "join")
				instruct.setInstruct(Instruction::JOIN_ROOM);
			else if (token == "create")
				instruct.setInstruct(Instruction::CREATE_ROOM);
			s.erase(0, pos + 1);
			if (s.size() > 0) {
				instruct.addName(s);
				servTcp->writePacket(Packet::pack(instruct));
			}
		}
		else if (s == "roomusers") {

			instruct.setInstruct(Instruction::GETALLUSERSINROOM);
			servTcp->writePacket(Packet::pack(instruct));
		}
		else if (s == "users")
		{
			instruct.setInstruct(Instruction::GETALLUSERNAMES);
			servTcp->writePacket(Packet::pack(instruct));
		}
		else if (s == "rooms")
		{
			instruct.setInstruct(Instruction::GETALLROOMNAMES);
			servTcp->writePacket(Packet::pack(instruct));
		}
		else if (s == "disconnect")
		{
			instruct.setInstruct(Instruction::DECONNEXION);
			servTcp->writePacket(Packet::pack(instruct));
		}
		else if (s == "leave")
		{
			instruct.setInstruct(Instruction::LEAVE_ROOM);
			servTcp->writePacket(Packet::pack(instruct));
		}
		else if (s == "start")
		{
			instruct.setInstruct(Instruction::START_GAME);
			servTcp->writePacket(Packet::pack(instruct));
			game();
			break;
		}
		//servUdp->writePacket(Packet::pack<std::string>(s));
	}
	servTcp->cancel();
#ifdef _WIN_32
	Sleep(1000);
#else
	sleep(1);
#endif

	delete servTcp;
	return (0);
}
Beispiel #19
0
// clear_out_chat_queue()
int ModApiClient::l_clear_out_chat_queue(lua_State *L)
{
	getClient(L)->clearOutChatQueue();
	return 0;
}
bool JackTransportClient::init()
{
    // register a jack timebase callback:
    jack_set_timebase_callback(getClient(), 0, timebase, this);
    return JackThreadEventProcessorClient::init();
}
Beispiel #21
0
int ModApiClient::l_take_screenshot(lua_State *L)
{
	Client *client = getClient(L);
	client->makeScreenshot();
	return 0;
}
Beispiel #22
0
/*get client in bank Client list.*/
client* getBankClient(accountNum acc){
    client* getCl=NULL;
    getCl= getClient(CLIENTSROOT(masterBank), acc, NOCHECK);
    return getCl;
}
void Server::handleCommand_Init2(NetworkPacket* pkt) {
	const auto peer_id = pkt->getPeerId();
	//auto & packet = *(pkt->packet);

	verbosestream << "Server: Got TOSERVER_INIT2 from "
	              << peer_id << std::endl;

	m_clients.event(peer_id, CSE_GotInit2);
	u16 protocol_version = m_clients.getProtocolVersion(peer_id);


	///// begin compatibility code
	PlayerSAO* playersao = NULL;
	if (protocol_version <= 22) {
		playersao = StageTwoClientInit(peer_id);

		if (playersao == NULL) {
			errorstream
			        << "TOSERVER_INIT2 stage 2 client init failed for peer "
			        << peer_id << std::endl;
			return;
		}
	}
	///// end compatibility code

	/*
		Send some initialization data
	*/

	infostream << "Server: Sending content to "
	           << getPlayerName(peer_id) << std::endl;

	// Send player movement settings
	SendMovement(peer_id);

	// Send item definitions
	SendItemDef(peer_id, m_itemdef, protocol_version);

	// Send node definitions
	SendNodeDef(peer_id, m_nodedef, protocol_version);

	m_clients.event(peer_id, CSE_SetDefinitionsSent);

	// Send media announcement
	sendMediaAnnouncement(peer_id);

	// Send detached inventories
	sendDetachedInventories(peer_id);

	// Send time of day
	u16 time = m_env->getTimeOfDay();
	float time_speed = g_settings->getFloat("time_speed");
	SendTimeOfDay(peer_id, time, time_speed);

	///// begin compatibility code
	if (protocol_version <= 22) {
		m_clients.event(peer_id, CSE_SetClientReady);
		m_script->on_joinplayer(playersao);
	}
	///// end compatibility code

	// Warnings about protocol version can be issued here
	if(getClient(peer_id)->net_proto_version < LATEST_PROTOCOL_VERSION) {
		SendChatMessage(peer_id, "# Server: WARNING: YOUR CLIENT'S "
		                "VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
	}
}
void com_ximeta_driver_NDASLogicalDevice::completeCommand(com_ximeta_driver_NDASSCSICommand *command)
{
	DbgIOLog(DEBUG_MASK_DISK_TRACE, ("Entered.\n"));
	
	com_ximeta_driver_NDASLogicalDeviceController *controller = OSDynamicCast(com_ximeta_driver_NDASLogicalDeviceController, getClient());

	controller->completeCommand(command);
}
void Server::handleCommand_Interact(NetworkPacket* pkt) {
	const auto peer_id = pkt->getPeerId();
	auto & packet = *(pkt->packet);
	auto player = m_env->getPlayer(pkt->getPeerId());
	if (!player) {
		m_con.DisconnectPeer(pkt->getPeerId());
		return;
	}
	auto playersao = player->getPlayerSAO();
	if (!playersao) {
		m_con.DisconnectPeer(pkt->getPeerId());
		return;
	}

	u8 action;
	u16 item_i;
	PointedThing pointed;

	packet[TOSERVER_INTERACT_ACTION].convert(action);
	packet[TOSERVER_INTERACT_ITEM].convert(item_i);
	packet[TOSERVER_INTERACT_POINTED_THING].convert(pointed);

	if(player->hp == 0) {
		verbosestream << "TOSERVER_INTERACT: " << player->getName()
		              << " tried to interact, but is dead!" << std::endl;
		return;
	}

	MAP_NOTHREAD_LOCK((&m_env->getMap()));

	v3f player_pos = playersao->getLastGoodPosition();

	// Update wielded item
	playersao->setWieldIndex(item_i);

	// Get pointed to node (undefined if not POINTEDTYPE_NODE)
	v3s16 p_under = pointed.node_undersurface;
	v3s16 p_above = pointed.node_abovesurface;

	// Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
	ServerActiveObject *pointed_object = NULL;
	if(pointed.type == POINTEDTHING_OBJECT) {
		pointed_object = m_env->getActiveObject(pointed.object_id);
		if(pointed_object == NULL) {
			verbosestream << "TOSERVER_INTERACT: "
			              "pointed object is NULL" << std::endl;
			return;
		}

	}

	v3f pointed_pos_under = player_pos;
	v3f pointed_pos_above = player_pos;
	if(pointed.type == POINTEDTHING_NODE) {
		pointed_pos_under = intToFloat(p_under, BS);
		pointed_pos_above = intToFloat(p_above, BS);
	} else if(pointed.type == POINTEDTHING_OBJECT) {
		pointed_pos_under = pointed_object->getBasePosition();
		pointed_pos_above = pointed_pos_under;
	}

	/*
		Check that target is reasonably close
		(only when digging or placing things)
	*/
	static const bool enable_anticheat = !g_settings->getBool("disable_anticheat");
	if ((action == 0 || action == 2 || action == 3) &&
	        (enable_anticheat && !isSingleplayer())) {
		float d = player_pos.getDistanceFrom(pointed_pos_under);
		float max_d = BS * 14; // Just some large enough value
		if(d > max_d) {
			actionstream << "Player " << player->getName()
			             << " tried to access " << pointed.dump()
			             << " from too far: "
			             << "d=" << d << ", max_d=" << max_d
			             << ". ignoring." << std::endl;
			// Re-send block to revert change on client-side
			RemoteClient *client = getClient(peer_id);
			v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
			client->SetBlockNotSent(blockpos);
			// Call callbacks
			m_script->on_cheat(playersao, "interacted_too_far");
			// Do nothing else
			return;
		}
	}

	/*
		Make sure the player is allowed to do it
	*/
	if(!checkPriv(player->getName(), "interact")) {
		actionstream << player->getName() << " attempted to interact with "
		             << pointed.dump() << " without 'interact' privilege"
		             << std::endl;
		// Re-send block to revert change on client-side
		RemoteClient *client = getClient(peer_id);
		// Digging completed -> under
		if(action == 2) {
			v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
			client->SetBlockNotSent(blockpos);
		}
		// Placement -> above
		if(action == 3) {
			v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
			client->SetBlockNotSent(blockpos);
		}
		stat.add("interact_denied", player->getName());
		return;
	}

	/*
		If something goes wrong, this player is to blame
	*/
	RollbackScopeActor rollback_scope(m_rollback,
	                                  std::string("player:") + player->getName());

	/*
		0: start digging or punch object
	*/
	if(action == 0) {
		if(pointed.type == POINTEDTHING_NODE) {
			/*
				NOTE: This can be used in the future to check if
				somebody is cheating, by checking the timing.
			*/
			MapNode n = m_env->getMap().getNode(p_under);

			if (!n) {
				infostream << "Server: Not punching: Node not found."
				           << " Adding block to emerge queue."
				           << std::endl;
				m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above), false);
			}

			if(n.getContent() != CONTENT_IGNORE)
				m_script->node_on_punch(p_under, n, playersao, pointed);
			// Cheat prevention
			playersao->noCheatDigStart(p_under);
		} else if(pointed.type == POINTEDTHING_OBJECT) {
			// Skip if object has been removed
			if(pointed_object->m_removed)
				return;

			actionstream << player->getName() << " punches object "
			             << pointed.object_id << ": "
			             << pointed_object->getDescription() << std::endl;

			ItemStack punchitem = playersao->getWieldedItem();
			ToolCapabilities toolcap =
			    punchitem.getToolCapabilities(m_itemdef);
			v3f dir = (pointed_object->getBasePosition() -
			           (player->getPosition() + player->getEyeOffset())
			          ).normalize();
			float time_from_last_punch =
			    playersao->resetTimeFromLastPunch();

			s16 src_original_hp = pointed_object->getHP();
			s16 dst_origin_hp = playersao->getHP();

			pointed_object->punch(dir, &toolcap, playersao,
			                      time_from_last_punch);

			// If the object is a player and its HP changed
			if (src_original_hp != pointed_object->getHP() &&
			        pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
				SendPlayerHPOrDie(((PlayerSAO*)pointed_object));
			}

			// If the puncher is a player and its HP changed
			if (dst_origin_hp != playersao->getHP()) {
				SendPlayerHPOrDie(playersao);
			}

			stat.add("punch", player->getName());
		}

	} // action == 0

	/*
		1: stop digging
	*/
	else if(action == 1) {
	} // action == 1

	/*
		2: Digging completed
	*/
	else if(action == 2) {
		// Only digging of nodes
		if(pointed.type == POINTEDTHING_NODE) {
			MapNode n = m_env->getMap().getNode(p_under);
			if (!n) {
				infostream << "Server: Not finishing digging: Node not found."
				           << " Adding block to emerge queue."
				           << std::endl;
				m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above), false);
			}

			/* Cheat prevention */
			bool is_valid_dig = true;
			if (enable_anticheat && !isSingleplayer()) {
				v3s16 nocheat_p = playersao->getNoCheatDigPos();
				float nocheat_t = playersao->getNoCheatDigTime();
				playersao->noCheatDigEnd();
				// If player didn't start digging this, ignore dig
				if(nocheat_p != p_under) {
					infostream << "Server: NoCheat: " << player->getName()
					           << " started digging "
					           << PP(nocheat_p) << " and completed digging "
					           << PP(p_under) << "; not digging." << std::endl;
					is_valid_dig = false;
					// Call callbacks
					m_script->on_cheat(playersao, "finished_unknown_dig");
				}
				// Get player's wielded item
				ItemStack playeritem;
				InventoryList *mlist = playersao->getInventory()->getList("main");
				if(mlist != NULL)
					playeritem = mlist->getItem(playersao->getWieldIndex());
				ToolCapabilities playeritem_toolcap =
				    playeritem.getToolCapabilities(m_itemdef);
				// Get diggability and expected digging time
				DigParams params = getDigParams(m_nodedef->get(n).groups,
				                                &playeritem_toolcap);
				// If can't dig, try hand
				if(!params.diggable) {
					const ItemDefinition &hand = m_itemdef->get("");
					const ToolCapabilities *tp = hand.tool_capabilities;
					if(tp)
						params = getDigParams(m_nodedef->get(n).groups, tp);
				}
				// If can't dig, ignore dig
				if(!params.diggable) {
					infostream << "Server: NoCheat: " << player->getName()
					           << " completed digging " << PP(p_under)
					           << ", which is not diggable with tool. not digging."
					           << std::endl;
					is_valid_dig = false;
					// Call callbacks
					m_script->on_cheat(playersao, "dug_unbreakable");
				}
				// Check digging time
				// If already invalidated, we don't have to
				if(!is_valid_dig) {
					// Well not our problem then
				}
				// Clean and long dig
				else if(params.time > 2.0 && nocheat_t * 1.2 > params.time) {
					// All is good, but grab time from pool; don't care if
					// it's actually available
					playersao->getDigPool().grab(params.time);
				}
				// Short or laggy dig
				// Try getting the time from pool
				else if(playersao->getDigPool().grab(params.time)) {
					// All is good
				}
				// Dig not possible
				else {
					infostream << "Server: NoCheat: " << player->getName()
					           << " completed digging " << PP(p_under)
					           << "too fast; not digging." << std::endl;
					is_valid_dig = false;
					// Call callbacks
					m_script->on_cheat(playersao, "dug_too_fast");
				}
			}

			/* Actually dig node */

			if(is_valid_dig && n.getContent() != CONTENT_IGNORE) {
				m_script->node_on_dig(p_under, n, playersao);
				stat.add("dig", player->getName());
				stat.add("dig_" + m_nodedef->get(n).name , player->getName());
			}

			v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
			RemoteClient *client = getClient(peer_id);
			// Send unusual result (that is, node not being removed)
			if(m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
				// Re-send block to revert change on client-side
				client->SetBlockNotSent(blockpos);
			} else {
				client->ResendBlockIfOnWire(blockpos);
			}
			m_env->nodeUpdate(p_under, 5, 0);
		}
	} // action == 2

	/*
		3: place block or right-click object
	*/
	else if(action == 3) {
		ItemStack item = playersao->getWieldedItem();

		// Reset build time counter
		if(pointed.type == POINTEDTHING_NODE &&
		        item.getDefinition(m_itemdef).type == ITEM_NODE)
			getClient(peer_id)->m_time_from_building = 0.0;

		if(pointed.type == POINTEDTHING_OBJECT) {
			// Right click object

			// Skip if object has been removed
			if(pointed_object->m_removed)
				return;

			/* android bug - too many
							actionstream<<player->getName()<<" right-clicks object "
									<<pointed.object_id<<": "
									<<pointed_object->getDescription()<<std::endl;
			*/

			// Do stuff
			pointed_object->rightClick(playersao);
		} else if(m_script->item_OnPlace(
		              item, playersao, pointed)) {
			// Placement was handled in lua

			// Apply returned ItemStack
			if (playersao->setWieldedItem(item)) {
				SendInventory(playersao);
			}

			stat.add("place", player->getName());
			//stat.add("place_" + item.name, player->getName());
		}

		// If item has node placement prediction, always send the
		// blocks to make sure the client knows what exactly happened
		RemoteClient *client = getClient(peer_id);
		v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
		v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
		if(item.getDefinition(m_itemdef).node_placement_prediction != "") {
			client->SetBlockNotSent(blockpos);
			if(blockpos2 != blockpos) {
				client->SetBlockNotSent(blockpos2);
			}
		} else {
			client->ResendBlockIfOnWire(blockpos);
			if(blockpos2 != blockpos) {
				client->ResendBlockIfOnWire(blockpos2);
			}
		}
		m_env->nodeUpdate(p_under, 5, 0);
	} // action == 3

	/*
		4: use
	*/
	else if(action == 4) {
		ItemStack item = playersao->getWieldedItem();

		actionstream << player->getName() << " uses " << item.name
		             << ", pointing at " << pointed.dump() << std::endl;

		if(m_script->item_OnUse(
		            item, playersao, pointed)) {
			// Apply returned ItemStack
			if (playersao->setWieldedItem(item)) {
				SendInventory(playersao);
			}
			stat.add("use", player->getName());
			stat.add("use_" + item.name, player->getName());
			m_env->nodeUpdate(p_under, 5, 0);
		}

	} // action == 4

	/*
		5: rightclick air
	*/
	else if (action == 5) {
		ItemStack item = playersao->getWieldedItem();

		actionstream << player->getName() << " activates "
		             << item.name << std::endl;

		if (m_script->item_OnSecondaryUse(
		            item, playersao)) {
			if( playersao->setWieldedItem(item)) {
				SendInventory(playersao);
			}
		}
	}


	/*
		Catch invalid actions
	*/
	else {
		infostream << "WARNING: Server: Invalid action "
		           << action << std::endl;
	}

}
Beispiel #26
0
void DBInfo::getProperty(JSContext* cx,
                         JS::HandleObject obj,
                         JS::HandleId id,
                         JS::MutableHandleValue vp) {
    // 2nd look into real values, may be cached collection object
    if (!vp.isUndefined()) {
        auto scope = getScope(cx);
        auto opContext = scope->getOpContext();

        if (opContext && vp.isObject()) {
            ObjectWrapper o(cx, vp);

            if (o.hasOwnField(InternedString::_fullName)) {
                // need to check every time that the collection did not get sharded
                if (haveLocalShardingInfo(opContext->getClient(),
                                          o.getString(InternedString::_fullName)))
                    uasserted(ErrorCodes::BadValue, "can't use sharded collection from db.eval");
            }
        }

        return;
    }

    JS::RootedObject parent(cx);
    if (!JS_GetPrototype(cx, obj, &parent))
        uasserted(ErrorCodes::JSInterpreterFailure, "Couldn't get prototype");

    ObjectWrapper parentWrapper(cx, parent);

    if (parentWrapper.hasOwnField(id)) {
        parentWrapper.getValue(id, vp);
        return;
    }

    IdWrapper idw(cx, id);

    // if starts with '_' we dont return collection, one must use getCollection()
    if (idw.isString()) {
        JSStringWrapper jsstr;
        auto sname = idw.toStringData(&jsstr);
        if (sname.size() == 0 || sname[0] == '_') {
            return;
        }
    }

    // no hit, create new collection
    JS::RootedValue getCollection(cx);
    parentWrapper.getValue(InternedString::getCollection, &getCollection);

    if (!(getCollection.isObject() && JS_ObjectIsFunction(cx, getCollection.toObjectOrNull()))) {
        uasserted(ErrorCodes::BadValue, "getCollection is not a function");
    }

    JS::AutoValueArray<1> args(cx);

    idw.toValue(args[0]);

    JS::RootedValue coll(cx);
    ObjectWrapper(cx, obj).callMethod(getCollection, args, &coll);

    uassert(16861,
            "getCollection returned something other than a collection",
            getScope(cx)->getProto<DBCollectionInfo>().instanceOf(coll));

    // cache collection for reuse, don't enumerate
    ObjectWrapper(cx, obj).defineProperty(id, coll, 0);

    vp.set(coll);
}