//////////////////////////////////////////////////////////////////////////////
// 플레이어가 팔려고 하는 아이템을 가지고 있는지 확인한 다음에,
// 일반 아이템과 모터 사이클 처리 부분으로 분기한다.
//////////////////////////////////////////////////////////////////////////////
void CGShopRequestSellHandler::execute (CGShopRequestSell* pPacket , Player* pPlayer)
	 throw(ProtocolException , Error) {
	__BEGIN_TRY __BEGIN_DEBUG_EX

#ifdef __GAME_SERVER__

	Assert(pPacket != NULL);
	Assert(pPlayer != NULL);
	
	ObjectID_t      ITEMOID     = pPacket->getItemObjectID();
	BYTE            OPCODE      = pPacket->getOpCode();
	GamePlayer*     pGamePlayer = dynamic_cast<GamePlayer*>(pPlayer);
	Creature*       pCreature   = pGamePlayer->getCreature();
	PlayerCreature* pPC         = dynamic_cast<PlayerCreature*>(pCreature);

	if (OPCODE == SHOP_REQUEST_SELL_NORMAL) {
		// 플레이어가 팔려고 하는 아이템을 가지고 있는지 검사
		Inventory* pInventory = pPC->getInventory();
		if (pInventory->hasItem(ITEMOID) == false) 
			throw ProtocolException("CGShopRequestSellHandler::execute() : No such item to sell!");

		Item* pItem = pInventory->getItemWithObjectID(ITEMOID);
		if (pItem == NULL || pPC->getStore()->hasItem(pItem))
			return sendFailPacket(pPacket, pPlayer);

		//ItemInfo* pItemInfo = g_pItemInfoManager->getItemInfo(pItem->getItemClass(), pItem->getItemType());
		//Assert(pItemInfo!=NULL);

		// 유니크 아이템은 못판다.
		// 특정 아이템 클래스는 팔 수 없다. by sigi. 2002.8.29
		// 선물 상자는 팔 수 있다. by bezz. 2002.12.13
		// 커플링은 팔 수 없다. by Sequoia. 2003. 3. 3
		// ItemUtil 안에 canSell 로 Extract 2003. 3. 3
		if (!canSell(pItem))
			return sendFailPacket(pPacket, pPlayer);
		else if (pItem->getItemClass() == Item::ITEM_CLASS_KEY && pItem->getItemType() == 2) 
			executeMotorcycle(pPacket, pPlayer);
		else 
			executeNormal(pPacket, pPlayer);
	}
	else if (OPCODE == SHOP_REQUEST_SELL_ALL_SKULL)
		executeOpAllSkull(pPacket, pPlayer);
	else if (OPCODE == SHOP_REQUEST_SWAP_ADVANCEMENT_ITEM)
		executeOpSwapAdvancementItem(pPacket, pPlayer);
	else
		throw ProtocolException("CGShopRequestSellHandler::execute() : unknown op code");
	
#endif

	__END_DEBUG_EX __END_CATCH
}
	Integer hash_m_to_int(byte *m, unsigned m_len, unsigned ret_byte_count){
		SHA256 sha256;
    if (m_len != sha256.DigestSize()) {
      throw ProtocolException("m_len != sha digest size");
    }
    return Integer(m, ret_byte_count);
	}
Exemple #3
0
CmdResult CommandIJoin::HandleRemote(RemoteUser* user, std::vector<std::string>& params)
{
	Channel* chan = ServerInstance->FindChan(params[0]);
	if (!chan)
	{
		// Desync detected, recover
		// Ignore the join and send RESYNC, this will result in the remote server sending all channel data to us
		ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received IJOIN for non-existant channel: " + params[0]);

		CmdBuilder("RESYNC").push(params[0]).Unicast(user);

		return CMD_FAILURE;
	}

	bool apply_modes;
	if (params.size() > 2)
	{
		time_t RemoteTS = ServerCommand::ExtractTS(params[2]);
		if (RemoteTS < chan->age)
			throw ProtocolException("Attempted to lower TS via IJOIN. LocalTS=" + ConvToStr(chan->age));
		apply_modes = ((params.size() > 3) && (RemoteTS == chan->age));
	}
	else
		apply_modes = false;

	// Join the user and set the membership id to what they sent
	Membership* memb = chan->ForceJoin(user, apply_modes ? &params[3] : NULL);
	if (!memb)
		return CMD_FAILURE;

	memb->id = Membership::IdFromString(params[1]);
	return CMD_SUCCESS;
}
Exemple #4
0
time_t ServerCommand::ExtractTS(const std::string& tsstr)
{
	time_t TS = ConvToNum<time_t>(tsstr);
	if (!TS)
		throw ProtocolException("Invalid TS");
	return TS;
}
Exemple #5
0
bool DEProtoProxy::get_Image(void* image, unsigned int length)
{
	boost::lock_guard<boost::mutex>(*this->server->getTransactionMutex());

	DEPacket pkt, dataHeader;
	pkt.set_type(DEPacket::P_COMMAND);
	SingleCommand* cmd = pkt.add_command();
	cmd->set_command_id(k_GetImage);

	this->sendCommand(pkt);
	this->receiveFromServer(dataHeader);
	if (dataHeader.type() != DEPacket::P_DATA_HEADER ||
		!dataHeader.has_data_header()) 
		BOOST_THROW_EXCEPTION(ProtocolException() << errorMessage("Did not receive expected data header for image."));
	
	this->imgBuffer.resizeIfNeeded(static_cast<std::size_t>(dataHeader.data_header().bytesize()));

	if (!this->server->receive(this->imgBuffer.getBufferPtr(), static_cast<std::size_t>(dataHeader.data_header().bytesize()), this->imageTimeout))
	{
		BOOST_THROW_EXCEPTION(CommunicationException() << errorMessage("Unable to receive image from server."));
	}

	if (dataHeader.data_header().bytesize() != length)
	{
		BOOST_THROW_EXCEPTION(CommandException() << errorMessage ("Image received did not have the expected size"));
	}

	memcpy(image, this->imgBuffer.getBufferPtr(), length);

	return true;
}
void BufferedTransport::setReadPos(size_t pos) {
	ScopedMutexLock(lock_);
	if(pos >= totalSize())
		throw ProtocolException("readpos less than 0 by rewind");

	readPos_ = pos;
}
//TODO: remove return int, make bool
int BinTreeNodeReader::readStreamStart()
{
    bool result = getOneToplevelStream();
    //TODO: count real bytes;
    int bytes = getOneToplevelStreamSize();

    if (decodedStream.bytesAvailable() < 3) {
        //TODO: make bool result. remove int.
        //return false;
        return bytes;
    }

    quint8 tag = 0, size;
    //TODO: check for bool result
    readInt8(tag);
    readInt8(size);
    readInt8(tag);
    if (tag != 1) {
        throw ProtocolException("Expecting STREAM_START in readStreamStart.");
    }

    int attribCount = (size - 2 + size % 2) / 2;

    AttributeList attribs;
    if (!readAttributes(attribs,attribCount)) {
        //TODO: make bool result. remove int.
        //return false;
        qDebug() << "readStreamStart: failed to read attributes" << attribCount;
        return bytes;
    }

    //TODO: make bool result. remove int.
    return bytes;
}
Exemple #8
0
CmdResult CommandSQuit::HandleServer(TreeServer* server, std::vector<std::string>& params)
{
	TreeServer* quitting = Utils->FindServer(params[0]);
	if (!quitting)
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Squit from unknown server");
		return CMD_FAILURE;
	}

	CmdResult ret = CMD_SUCCESS;
	if (quitting == server)
	{
		ret = CMD_FAILURE;
		server = server->GetParent();
	}
	else if (quitting->GetParent() != server)
		throw ProtocolException("Attempted to SQUIT a non-directly connected server or the parent");

	server->SQuitChild(quitting, params[1]);

	// XXX: Return CMD_FAILURE when servers SQUIT themselves (i.e. :00S SQUIT 00S :Shutting down)
	// to stop this message from being forwarded.
	// The squit logic generates a SQUIT message with our sid as the source and sends it to the
	// remaining servers.
	return ret;
}
bool BinTreeNodeReader::readString(int token, QByteArray& s, QDataStream& in)
{
    int size;

    if (token == -1)
        throw ProtocolException("-1 token in readString.");

    if (token > 4 && token < 0xf5)
        return getToken(token,s);

    switch (token)
    {
        case 0:
            return false;

        case 0xfc:
            size = readInt8(in);
            fillArray(s,size,in);
            return true;

        case 0xfd:
            size = readInt24(in);
            fillArray(s,size,in);
            return true;

        case 0xfe:
            in >> token;
            return getToken(245 + token,s);

        case 0xfa:
            QByteArray user,server;
            bool usr = readString(user,in);
            bool srv = readString(server,in);
            if (usr & srv)
            {
                s = user + "@" + server;
                return true;
            }
            if (srv)
            {
                s = server;
                return true;
            }
            throw ProtocolException("readString couldn't reconstruct jid.");
    }
    throw ProtocolException("readString invalid token " + QString::number(token));
}
Exemple #10
0
void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
{
	std::string::size_type comma = item.find(',');

	// Comma not required anymore if the user has no modes
	const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1);
	std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH);
	User* who = ServerInstance->FindUUID(uuid);
	if (!who)
	{
		// Probably KILLed, ignore
		return;
	}

	TreeSocket* src_socket = sourceserver->GetSocket();
	/* Check that the user's 'direction' is correct */
	TreeServer* route_back_again = TreeServer::Get(who);
	if (route_back_again->GetSocket() != src_socket)
	{
		return;
	}

	std::string::const_iterator modeendit = item.begin(); // End of the "ov" mode string
	/* Check if the user received at least one mode */
	if ((modechangelist) && (comma != std::string::npos))
	{
		modeendit += comma;
		/* Iterate through the modes and see if they are valid here, if so, apply */
		for (std::string::const_iterator i = item.begin(); i != modeendit; ++i)
		{
			ModeHandler* mh = ServerInstance->Modes.FindMode(*i, MODETYPE_CHANNEL);
			if (!mh)
				throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");

			/* Add any modes this user had to the mode stack */
			modechangelist->push_add(mh, who->nick);
		}
	}

	Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
	if (!memb)
	{
		// User was already on the channel, forward because of the modes they potentially got
		memb = chan->GetUser(who);
		if (memb)
			fwdfjoin.add(memb, item.begin(), modeendit);
		return;
	}

	// Assign the id to the new Membership
	Membership::Id membid = 0;
	const std::string::size_type colon = item.rfind(':');
	if (colon != std::string::npos)
		membid = Membership::IdFromString(item.substr(colon+1));
	memb->id = membid;

	// Add member to fwdfjoin with prefix modes
	fwdfjoin.add(memb, item.begin(), modeendit);
}
void CGRequestRepairHandler::execute (CGRequestRepair* pPacket , Player* pPlayer)
	 throw(ProtocolException , Error)
{
	__BEGIN_TRY __BEGIN_DEBUG_EX

#ifdef __GAME_SERVER__

	Assert(pPacket != NULL);
	Assert(pPlayer != NULL);
	
	ObjectID_t  ITEMOID     = pPacket->getObjectID();
	GamePlayer* pGamePlayer = dynamic_cast<GamePlayer*>(pPlayer);
	Creature*   pPC         = pGamePlayer->getCreature();
	bool        bSlayer     = false;
	bool        bVampire    = false;
	bool        bOusters    = false;
	Item*       pItem       = NULL;
	
	// 플레이어가 슬레이어인지 뱀파이어인지 구분.
	if (pPC->isSlayer())       bSlayer = true;
	else if (pPC->isVampire()) bVampire = true;
	else if (pPC->isOusters()) bOusters = true;
	else throw ProtocolException("CGRequestRepairHandler::execute() : Unknown player creature!");

	if (ITEMOID == 0)
	{
		// ObjectID가 0이라면 모든 아이템을 수리하고자 하는 것이다.
		executeAll(pPacket, pPlayer);
	}
	else
	{
		if (bSlayer) pItem = (dynamic_cast<Slayer*>(pPC))->findItemOID(ITEMOID);
		else if (bVampire) pItem = (dynamic_cast<Vampire*>(pPC))->findItemOID(ITEMOID);
		else if (bOusters) pItem = (dynamic_cast<Ousters*>(pPC))->findItemOID(ITEMOID);

		// 플레이어가 아이템을 가지고 있다면
		if (pItem != NULL)
		{
			// 그 아이템이 모터 사이클 키라면...
			if (pItem->getItemClass() == Item::ITEM_CLASS_KEY && pItem->getItemType() == 2)
			{
				executeMotorcycle(pPacket, pPlayer);
				return;
			}
			else executeNormal(pPacket, pPlayer);
		}
		else
		{
			// 아이템이 없으니, 당연히 수리할 수 없다.
			GCNPCResponse response;
			response.setCode(NPC_RESPONSE_REPAIR_FAIL_ITEM_NOT_EXIST);
			pPlayer->sendPacket(&response);
		}
	}
	
#endif

	__END_DEBUG_EX __END_CATCH
}
CMSDestGroup::CMSDestGroup(const std::string& s) {
    std::vector<std::string> parts = StringUtils::splitAny(s, ".", true);
    type = validateParts(parts);
    if (type == NONE)
        throw ProtocolException("Invalid CMSDestGroup: " + s);
    this->parts = parts;
    this->destination = s;
}
Exemple #13
0
void BufferedTransport::rewind(size_t size) {
	ScopedMutexLock(lock_);
	int temp = readPos_ - size;
	if(temp < 0) {
		throw ProtocolException("readpos less than 0 by rewind");
	}
	readPos_ = temp;
}
	void S::finish_sig(Integer r, Integer cb){
		this->r = r;
		Integer s2 = paillier.dec(cb) % n;
		s = a_times_b_mod_c(ks.InverseMod(n), s2, n);
		if (s == 0){
			throw ProtocolException("ERR s==0 restart protocol");
		}
    if (s > n - s) {
      s = n - s;
    }

		// bool result = verifier.VerifyMessage(get_data(), get_data_length(), signature, 64);
		bool result = verify(Q, get_data(), get_data_length(), r, s);
		if (!result){
			throw ProtocolException("Invalid signature generated!");
		} else {
    }
	}
void SingleBuyer::verifyKeys() {
	vector<byte> signature = signature_commit.m;
	array<common::TSHA256Digest, common::L> exp_keys = genKeys(signature);
	for(unsigned i = 0; i < L; ++i){
		if (!equal(keys_commits[i].m.begin(), keys_commits[i].m.end(), exp_keys[i].begin())) {
			throw ProtocolException("Invalid key");
		}
	}
}
void stk500SaveFiles::run() {
    if (this->sourceFile.endsWith('/')) {
        // Saving a full directory
        // First navigate to this directory
        QString dirPath = this->sourceFile;
        dirPath.remove(dirPath.length() - 1, 1);
        QString destDirPath = this->destFile;
        if (destDirPath.endsWith('/')) {
            destDirPath.remove(destDirPath.length() - 1, 1);
        }

        DirectoryEntryPtr dirStartPtr;
        if (dirPath.isEmpty()) {
            dirStartPtr = protocol->sd().getRootPtr();
        } else {
            DirectoryEntryPtr dirEntryPtr = sd_findEntry(dirPath, true, false);
            if (isCancelled()) {
                return;
            }
            if (!dirEntryPtr.isValid()) {
                // Should not happen, but just in case...
                throw ProtocolException("Folder not found");
            }
            DirectoryEntry folderEntry = protocol->sd().readDirectory(dirEntryPtr);
            if (folderEntry.firstCluster()) {
                dirStartPtr = protocol->sd().getDirPtrFromCluster(folderEntry.firstCluster());
            } else {
                dirStartPtr = DirectoryEntryPtr(0, 0);
            }
        }
        saveFolder(dirStartPtr, dirPath, destDirPath, 0.0, 1.0);
    } else {
        // Saving a single file
        DirectoryEntryPtr filePtr = sd_findEntry(this->sourceFile, false, false);
        if (isCancelled()) {
            return;
        }
        if (!filePtr.isValid()) {
            throw ProtocolException("File not found");
        }
        DirectoryEntry fileEntry = protocol->sd().readDirectory(filePtr);
        saveFile(fileEntry, this->sourceFile, this->destFile, 0.0, 1.0);
    }
}
	B::B(	Integer paillier_n, 
				Integer paillier_g): 
		ec(common::ec_parameters().GetCurve()),
		G(common::ec_parameters().GetSubgroupGenerator()),
		n(common::ec_parameters().GetGroupOrder()),
		paillier(paillier_n, paillier_g) {

			if (paillier.get_n() <= 2*n*n*n*n)
				throw ProtocolException("too short paillier");
		}
vector<Integer> Receiver::zk_3(const vIvI &zw) {

    if (zw.first.size() != com.K+1 || zw.second.size() != com.K+1) {
        throw ProtocolException("invalid zw size");
    }

    this->zw = zw;

    return commit_values;
}
bool BinTreeNodeReader::getToken(int token, QByteArray &s)
{
    if (token >= 0 && token < dictionary.length())
    {
        s = dictionary.at(token).toUtf8();
        return true;
    }

    throw ProtocolException("Invalid token/length in getToken.");
}
	void SharedSignature::init(S *s, B *b) {
		s->start_init();
		b->start_init();

		s->finish_init(b->get_Qb());
		b->finish_init(s->get_Qs());

		if (!(s->get_Q() == b->get_Q())){
			throw ProtocolException("Mismatching Q");
		}
	}
vector<bool> Receiver::open(Integer vp) {

    Integer v = get_g(com.n, vp);

    Integer u = a_exp_b_mod_c(v, Integer::Power2(com.l), com.n);

    if (u != com.u) {
        throw ProtocolException("u != com.u");
    }

    return decode(v);
}
Exemple #22
0
bool DEProtoProxy::getStrings(PacketParser& util, type cmdVal, vector<string>& values)
{
	DEPacket pkt, response;
	PacketCreator utilSend;
	utilSend.addSingleCommand(pkt, cmdVal);

	if (!this->sendCommand(pkt, response))
		return false;
	if (!util.getStrings(response.acknowledge(0), values))
		BOOST_THROW_EXCEPTION(ProtocolException() << errorMessage("At least one value expected."));

	return true;
}
//----------------------------------------------------------------------
// 캐릭터의 삭제가 실패했다는 뜻이다.
// 가만히 생각해보니, 삭제 실패는 크래킹 시도가 아닌가?? - -;
//----------------------------------------------------------------------
void LCDeletePCErrorHandler::execute (LCDeletePCError * pPacket , Player * pPlayer )
	 throw(ProtocolException , Error )
{
	__BEGIN_TRY __BEGIN_DEBUG_EX

#ifdef __GAME_CLIENT__

	cout << "Fail to deletePC... (" << pPacket->toString() << ")" << endl;
	throw ProtocolException("DeletePC Failed!");

#endif
		
	__END_DEBUG_EX __END_CATCH
}
Exemple #24
0
// Possible exceptions that may occur here.
// 1. Unable to send command.
// 2. Networking problem: incorrect ack or nothing received.
// 3. Server error: unrecognized command.
// 4. Parsing error: values returned were not what was expected.
bool DEProtoProxy::getValues(PacketParser& util, type cmdVal)
{
	DEPacket pkt, response;
	PacketCreator utilSend;
	utilSend.addSingleCommand(pkt, cmdVal);

	if (!this->sendCommand(pkt, response))
		return false;  

	if (!util.getValues(response.acknowledge(0)))
		BOOST_THROW_EXCEPTION(ProtocolException() << errorMessage("Parameters returned do not match Get Expectations"));

	return true;
}
	void B::cont_sig(ECPPoint Ks, Integer cs, byte *m, unsigned m_len){
		kb.Randomize(common::rng(), Integer::One(), n-1);
		K = ec.Multiply(kb, Ks);
		r = K.x % n;
		if (r == 0)
			throw ProtocolException("r == 0");

		Integer hi = hash_m_to_int(m, m_len, n.ByteCount());
		Integer c1 = paillier.enc( a_times_b_mod_c(kb.InverseMod(n), hi, n) );
		Integer t = a_times_b_mod_c(a_times_b_mod_c(kb.InverseMod(n), r, n), db, n);
		Integer c2 = a_times_b_mod_c(c1, a_exp_b_mod_c(cs, t, paillier.get_n2()), paillier.get_n2());
		Integer u(common::rng(), Integer::Zero(), n*n - 1);
		cb = a_times_b_mod_c(c2, paillier.enc(u*n), paillier.get_n2());
	}
quint32 BinTreeNodeReader::readListSize(qint32 token, QDataStream& in)
{
    int size;
    if (token == 0)
        size = 0;
    else if (token == 0xf8)
        size = readInt8(in);
    else if (token == 0xf9)
        size = readInt16(in);
    else
        throw ProtocolException("Invalid list size in readListSize: token 0x" + QString::number(token,16));

    return size;
}
void stk500service::writePage(quint32 address, const char* pageData) {
    QString addressText = QString("0x") + QString::number(address, 16);

    /* Set address */
    setAddress(address);

    /* Try to execute 'w' command */
    char commandData[1+256];
    commandData[0] = 'w';
    memcpy(commandData+1, pageData, 256);
    if (!writeVerifyRetry(commandData, sizeof(commandData))) {
        QString err = QString("Failed to write page data at address %1").arg(addressText);
        throw ProtocolException(err);
    }
}
void Receiver::zk_5(const vI &y) {
    if (y.size() != com.K+1) {
        throw ProtocolException("y size != K+1");
    }

    for(unsigned i = 1; i <= com.K; ++i) {

        Integer zi = a_times_b_mod_c(
                         a_exp_b_mod_c(com.g, y[i], com.n),
                         a_exp_b_mod_c(com.W[i-1].InverseMod(com.n), commit_values[i], com.n),
                         com.n);
        if (zi != zw.first[i]) {
            throw ProtocolException("zi verification failed");
        }

        Integer wi = a_times_b_mod_c(
                         a_exp_b_mod_c(com.W[i-1], y[i], com.n),
                         a_exp_b_mod_c(com.W[i].InverseMod(com.n), commit_values[i], com.n),
                         com.n);
        if (wi != zw.second[i]) {
            throw ProtocolException("wi verification failed");
        }
    }
}
void stk500service::readPage(quint32 address, char* pageData) {
    setAddress(address);

    // Execute the 'r' command and read the response
    // Attempt to do this 2 times to try and read the full page
    int recLen = 0;
    char zero_data[256];
    memset(zero_data, 0, sizeof(zero_data));
    for (int i = 0; i < 2; i++) {
        if (!writeVerifyRetry("r", 1)) {
            throw ProtocolException("Failed to start reading page data");
        }
        _handler->getPort()->write(zero_data, 256);
        recLen = this->readSerial(pageData, 256);
        if (recLen == 256) {
            return;
        }
    }

    // Could not get a full response for the page
    QString errorMessage = QString("Failed to read the full 256 byte page\n"
                                   "Received: %1 bytes").arg(recLen);
    throw ProtocolException(errorMessage);
}
std::future<void> AsyncProtocol::send(std::unique_ptr<Message>&& message)
{
    std::promise<void> promise;
    auto future = promise.get_future();

    if (running_)
    {
        messages_.push(MessageNode(std::move(message), std::move(promise)));
    }
    else
    {
        promise.set_exception(std::make_exception_ptr(ProtocolException(tnt::get_name(*this) + " is not running.")));
    }

    return future;
}