// takes filename, returns whether errors were encountered, returns whether checksums are identical or not
static int compareWorldChecksum(lua_State* inState)
{
	bool theSuccess = false;
	bool theChecksumsAreEqual = false;
	
	const char* theFileName = lua_tostring(inState, 1);
	Checksum theOldChecksum;
	theSuccess = theOldChecksum.ReadFromFile(theFileName);

	Checksum theNewChecksum;
	GetGameRules()->ComputeWorldChecksum(theNewChecksum);
	if(theSuccess)
	{
		StringList theErrors;
		theChecksumsAreEqual = theNewChecksum.Compare(theOldChecksum, theErrors);
	}
	
	// Return function success
	lua_pushnumber(inState, theSuccess);

	// Return checksums are equal
	lua_pushnumber(inState, theChecksumsAreEqual);
	
	return 2;
}
Exemplo n.º 2
0
Checksum Scenario::load(const string &path) {
    Checksum scenarioChecksum;
	try {
		scenarioChecksum.addFile(path);
		checksumValue.addFile(path);

		string name= cutLastExt(lastDir(path));
		Logger::getInstance().add("Scenario: " + formatString(name), true);

		//parse xml
		XmlTree xmlTree;
		xmlTree.load(path);
		const XmlNode *scenarioNode= xmlTree.getRootNode();
		const XmlNode *scriptsNode= scenarioNode->getChild("scripts");

		for(int i= 0; i<scriptsNode->getChildCount(); ++i){
			const XmlNode *scriptNode = scriptsNode->getChild(i);

			scripts.push_back(Script(getFunctionName(scriptNode), scriptNode->getText()));
		}
	}
	//Exception handling (conversions and so on);
	catch(const exception &e) {
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what());
		throw runtime_error("Error: " + path + "\n" + e.what());
	}

	return scenarioChecksum;
}
Exemplo n.º 3
0
void CharacterStats::doChecksum(Checksum &checksum) const {
	checksum.add(conception);
	checksum.add(might);
	checksum.add(potency);
	checksum.add(spirit);
	checksum.add(awareness);
	checksum.add(acumen);
	checksum.add(authority);
	checksum.add(finesse);
	checksum.add(mettle);
	checksum.add(fortitude);
}
Exemplo n.º 4
0
 bool JSectFooter::checkHash(const void* begin, int len) const {
     if( !magicOk() ) { 
         log() << "journal footer not valid" << endl;
         return false;
     }
     Checksum c;
     c.gen(begin, len);
     DEV log() << "checkHash len:" << len << " hash:" << toHex(hash, 16) << " current:" << toHex(c.bytes, 16) << endl;
     if( memcmp(hash, c.bytes, sizeof(hash)) == 0 ) 
         return true;
     log() << "journal checkHash mismatch, got: " << toHex(c.bytes, 16) << " expected: " << toHex(hash,16) << endl;
     return false;
 }
// takes filename, returns success
static int saveWorldChecksum(lua_State* inState)
{
	bool theSuccess = false;

	Checksum theChecksum;
	GetGameRules()->ComputeWorldChecksum(theChecksum);

	const char* theFileName = lua_tostring(inState, 1);
	theSuccess = theChecksum.SaveToFile(theFileName);

	// Return success
	lua_pushnumber(inState, theSuccess);

	return 1;
}
Exemplo n.º 6
0
void ProducibleType::doChecksum(Checksum &checksum) const {
	RequirableType::doChecksum(checksum);
	foreach_const (Costs, it, costs) {
		//checksum.add(it->getType()->getId());
		//checksum.add(it->getType()->getName());
		//checksum.add(it->getAmount());
	}
	checksum.add(productionTime);
}
Exemplo n.º 7
0
bool Protocol::validatePacket(string packet) {
	vector<char> chars;
	Checksum checksum;

	//Valid length
	if (packet.length() < 5 || packet.length() > 516)
		return false;

	for (int i = 4; i < packet.length(); i++)
		checksum.add(packet[i]);

	chars = checksum.get();

	//Validate header, sync bit and  checksum
	return (packet[0] == SOH &&
		packet[1] == sync == SYNC0 ? SYNC0 : SYNC1 &&
		packet[2] == '0' &&//chars[0] &&
		packet[3] == '0');//chars[1]);
}
void
EventLogger::checksum_update(const Packet &packet, const Checksum &checksum) {
  typedef struct : msg_hdr_t {
    int checksum_id;
  } __attribute__((packed)) msg_t;

  msg_t msg;
  fill_msg_hdr(EventType::CHECKSUM_UPDATE, device_id, packet, &msg);
  msg.checksum_id = checksum.get_id();
  transport_instance->send(reinterpret_cast<char *>(&msg), sizeof(msg));
}
Exemplo n.º 9
0
bool Checksum::Compare(const Checksum& inChecksum, StringList& outErrors) const
{
	ChecksumList::const_iterator	theIncomingIter = inChecksum.mChecksumList.begin();
	ChecksumList::const_iterator	theSourceIter = this->mChecksumList.begin();

	string							theErrorString;

	int32							theChecksumCount = 0;

	bool							theReturnCode = true;

	// Only try compare if both checksums are in the same mode 
	if(this->GetIsVerboseMode() == inChecksum.GetIsVerboseMode())
	{
		if(this->mChecksumList.size() == inChecksum.mChecksumList.size())
		{
			for( ; theSourceIter != this->mChecksumList.end(); theSourceIter++, theIncomingIter++)
			{
				if(!(theSourceIter->Compare(*theIncomingIter, theErrorString)))
				{
					outErrors.push_back(theErrorString);
					theReturnCode = false;
				}
				theChecksumCount++;
			}
		}
		else
		{
			sprintf(theErrorString, "Checksum::Compare(): Checksum sizes don't match.  Source size is %d and other size is %d.\n", this->mChecksumList.size(), inChecksum.mChecksumList.size());
			outErrors.push_back(theErrorString);
			theReturnCode = false;
		}
	}
	else
	{
		sprintf(theErrorString, "Checksum::Compare(): One checksum is in verbose mode, the other isn't.\n");
		outErrors.push_back(theErrorString);
		theReturnCode = false;
	}

	return theReturnCode;
}
Exemplo n.º 10
0
void RequirableType::doChecksum(Checksum &checksum) const {
	NameIdPair::doChecksum(checksum);
	for (int i = 0; i < getUnitReqCount(); ++i) {
		checksum.add(unitReqs[i].getUnitType()->getName());
		checksum.add(unitReqs[i].getUnitType()->getId());
	}
	for (int i = 0; i < getItemReqCount(); ++i) {
		checksum.add(itemReqs[i].getItemType()->getName());
		checksum.add(itemReqs[i].getItemType()->getId());
	}
	for (int i = 0; i < getUpgradeReqCount(); ++i) {
		checksum.add(upgradeReqs[i].getUpgradeType()->getName());
		checksum.add(upgradeReqs[i].getUpgradeType()->getId());
	}
}
Exemplo n.º 11
0
void cp5(char* src_file, char* dst_file)
{
    Checksum summer;
    unordered_map<uint32_t, ChunkInfo*> sum_offset;
    list<ChunkInfo*> file_meta;
    int32_t src_size = FileUtils::get_file_size(src_file);
    int32_t count = src_size / CHUNK_SIZE;
    char* buf = NULL;
    int length = CHUNK_SIZE;
    int i = 0;
    for (; i < count; ++i) {
        FileUtils::read(&buf, i * CHUNK_SIZE, length, src_file);
        ChunkInfo* chunk_info = new ChunkInfo();
        chunk_info->from_ = true;
        chunk_info->offset_ = i * CHUNK_SIZE;
        chunk_info->length_ = CHUNK_SIZE;
        string* strong_sum = summer.StrongSum(buf, length);
        chunk_info->strong_sum_ = strong_sum;
        sum_offset[summer.Sum1(buf, length)] = chunk_info;
        file_meta.push_back(chunk_info);
        delete [] buf;
    }
    
    int32_t last = src_size % CHUNK_SIZE;
    if (last > 0) {
        ChunkInfo* chunk_info = new ChunkInfo();
        chunk_info->from_ = true;
        chunk_info->offset_ = i * CHUNK_SIZE;
        chunk_info->length_ = last;
        file_meta.push_back(chunk_info);
    }

    for (auto iter = sum_offset.begin(); iter != sum_offset.end(); ++iter) {
        WLOG(DEBUG, "sum : %u, off: %d len: %d", iter->first,
                iter->second->offset_, iter->second->length_);
    }
    int32_t dst_size = FileUtils::get_file_size(dst_file);
    int32_t len = CHUNK_SIZE;
    FileUtils::read(&buf, 0, len, dst_file);
    int32_t curr = CHUNK_SIZE;
    summer.Init(buf, CHUNK_SIZE);
    auto iter = sum_offset.find(summer.tmp_sum());
    int32_t total_left = dst_size - CHUNK_SIZE;
    if (iter != sum_offset.end()) {
        WLOG(INFO, "%s and %s first chunk is the same", src_file, dst_file);
        string* strong_sum = summer.StrongSum(buf, CHUNK_SIZE);
        if (*strong_sum == *(iter->second->strong_sum_)) {
            iter->second->from_ = false;
            iter->second->offset_ = 0;
        }
        WLOG(INFO, "md5 sum of src chunk %s", iter->second->strong_sum_->c_str());
        WLOG(INFO, "md5 sum of dst chunk %s", strong_sum->c_str());
        WLOG(INFO, "%d is replaced with %d", iter->second->offset_, 0);
    }
    delete [] buf;
    clock_t start, end;
    start = clock();
    int32_t sum_time = 0;
    while (true) {
        WLOG(DEBUG, "total_left: %d", total_left);
        if (total_left <= 0) break;
        int32_t buf_len = SCAN_BUFFER_SIZE;
        if (buf_len > total_left) {
            buf_len = total_left;
        }
        int32_t read_len = buf_len + CHUNK_SIZE;
        FileUtils::read(&buf, curr - CHUNK_SIZE, read_len, dst_file);
        for (int i = CHUNK_SIZE; i < read_len; ++i) {
            uint32_t new_sum = summer.Update(buf[i]);
            auto iter = sum_offset.find(summer.tmp_sum());
            if (iter != sum_offset.end()) {
                ++sum_time;
                string* strong_sum = summer.StrongSum(buf + i - CHUNK_SIZE + 1, CHUNK_SIZE);
                WLOG(INFO, "md5 sum of src chunk %s", iter->second->strong_sum_->c_str());
                WLOG(INFO, "md5 sum of dst chunk %s", strong_sum->c_str());
                WLOG(INFO, "%d is replaced with %d, curr: %d",
                        iter->second->offset_, curr - 1 * CHUNK_SIZE + 1, curr);
                if (*strong_sum == *(iter->second->strong_sum_)) {
                    iter->second->from_ = false;
                    iter->second->offset_ = curr - 1 * CHUNK_SIZE + 1;
                }
            }
            ++curr;
        }
        delete [] buf;
        total_left -= buf_len;
    }
    end = clock();
    WLOG(NOTICE, "find cost %f s, sum time:%d", (double)(end - start) / CLOCKS_PER_SEC, sum_time);

    construct_file(src_file, dst_file, file_meta, "client_data/test.dat");
}
Exemplo n.º 12
0
		void Fds::SaveState(State::Saver& state,const dword baseChunk) const
		{
			state.Begin( baseChunk );

			{
				const byte data[4] =
				{
					io.ctrl,
					io.port,
					0,
					0
				};

				state.Begin( AsciiId<'I','O'>::V ).Write( data ).End();
			}

			adapter.SaveState( state );

			state.Begin( AsciiId<'R','A','M'>::V ).Compress( ram.mem ).End();
			state.Begin( AsciiId<'C','H','R'>::V ).Compress( ppu.GetChrMem().Source().Mem(), SIZE_8K ).End();

			{
				const byte data[4] =
				{
					static_cast<byte>(disks.sides.count),
					static_cast<byte>((disks.current != Disks::EJECTED) | (disks.writeProtected ? 0x2U : 0x0U)),
					static_cast<byte>(disks.current != Disks::EJECTED ? disks.current : 0xFF),
					static_cast<byte>(disks.current != Disks::EJECTED ? disks.mounting : 0)
				};

				state.Begin( AsciiId<'D','S','K'>::V ).Write( data ).End();
			}

			bool saveData = true;

			if (state.Internal())
			{
				Checksum recentChecksum;

				for (uint i=0; i < disks.sides.count; ++i)
					recentChecksum.Compute( disks.sides[i], SIDE_SIZE );

				if (checksum == recentChecksum)
					saveData = false;
				else
					checksum = recentChecksum;
			}

			if (saveData)
			{
				struct Dst
				{
					byte* const NST_RESTRICT mem;

					Dst() : mem(new byte [SIDE_SIZE]) {}
					~Dst() { delete [] mem; }
				};

				Dst dst;

				for (uint i=0; i < disks.sides.count; ++i)
				{
					const byte* const NST_RESTRICT src = disks.sides[i];

					for (uint j=0; j < SIDE_SIZE; ++j)
						dst.mem[j] = src[j] ^ 0xFFU;

					state.Begin( AsciiId<'D','0','A'>::R( 0, i / 2, i % 2 ) ).Compress( dst.mem, SIDE_SIZE ).End();
				}
			}
Exemplo n.º 13
0
		Result Cartridge::SetupBoard
		(
			Ram& prg,
			Ram& chr,
			Boards::Board** board,
			const Context* const context,
			Profile& profile,
			const ProfileEx& profileEx,
			dword* const prgCrc,
			const bool readOnly
		)
		{
			NST_ASSERT( bool(board) == bool(context) );

			Boards::Board::Type::Nmt nmt;

			if (profile.board.solderPads & (Profile::Board::SOLDERPAD_H|Profile::Board::SOLDERPAD_V))
			{
				if (profile.board.solderPads & Profile::Board::SOLDERPAD_H)
					nmt = Boards::Board::Type::NMT_VERTICAL;
				else
					nmt = Boards::Board::Type::NMT_HORIZONTAL;
			}
			else switch (profileEx.nmt)
			{
				case ProfileEx::NMT_HORIZONTAL:   nmt = Boards::Board::Type::NMT_HORIZONTAL;   break;
				case ProfileEx::NMT_VERTICAL:     nmt = Boards::Board::Type::NMT_VERTICAL;     break;
				case ProfileEx::NMT_SINGLESCREEN: nmt = Boards::Board::Type::NMT_SINGLESCREEN; break;
				case ProfileEx::NMT_FOURSCREEN:   nmt = Boards::Board::Type::NMT_FOURSCREEN;   break;
				default:                          nmt = Boards::Board::Type::NMT_CONTROLLED;   break;
			}

			Chips chips;

			for (Profile::Board::Chips::const_iterator i(profile.board.chips.begin()), end(profile.board.chips.end()); i != end; ++i)
			{
				Chips::Type& type = chips.Add( i->type.c_str() );

				for (Profile::Board::Pins::const_iterator j(i->pins.begin()), end(i->pins.end()); j != end; ++j)
					type.Pin(j->number) = j->function.c_str();

				for (Profile::Board::Samples::const_iterator j(i->samples.begin()), end(i->samples.end()); j != end; ++j)
					type.Sample(j->id) = j->file.c_str();
			}

			Boards::Board::Context b
			(
				context ? &context->cpu : NULL,
				context ? &context->apu : NULL,
				context ? &context->ppu : NULL,
				prg,
				chr,
				profileEx.trainer,
				nmt,
				profileEx.battery || profile.board.HasWramBattery(),
				profile.board.HasMmcBattery(),
				chips
			);

			if (profile.board.type.empty() || !b.DetectBoard( profile.board.type.c_str(), profile.board.GetWram() ))
			{
				if (profile.board.mapper == Profile::Board::NO_MAPPER || !b.DetectBoard( profile.board.mapper, profile.board.GetWram(), profileEx.wramAuto, profile.board.subMapper ) && board)
					return RESULT_ERR_UNSUPPORTED_MAPPER;

				if (profile.board.type.empty())
					profile.board.type = std::wstring( b.name, b.name + std::strlen(b.name) );
			}

			if (profile.board.mapper == Profile::Board::NO_MAPPER && b.type.GetMapper() != Boards::Board::Type::NMPR)
				profile.board.mapper = b.type.GetMapper();

			for (uint i=0; i < 2; ++i)
			{
				dword size = (i ? b.chr : b.prg).Size();

				if (size != (i ? profile.board.GetChr() : profile.board.GetPrg()))
				{
					Profile::Board::Roms& roms = (i ? profile.board.chr : profile.board.prg);
					roms.clear();

					if (size)
					{
						Profile::Board::Rom rom;
						rom.size = size;
						roms.push_back( rom );
					}
				}

				size = (i ? b.type.GetVram() : b.type.GetWram());

				if (size != (i ? profile.board.GetVram() : profile.board.GetWram()))
				{
					Profile::Board::Rams& rams = (i ? profile.board.vram : profile.board.wram);
					rams.clear();

					for (uint j=0; j < 2; ++j)
					{
						size = i ? (j ? b.type.GetNonSavableVram() : b.type.GetSavableVram()) :
                                   (j ? b.type.GetNonSavableWram() : b.type.GetSavableWram());

						if (size)
						{
							Profile::Board::Ram ram;
							ram.size = size;
							ram.battery = (i == 0 && j == 0 && b.wramBattery);
							rams.push_back( ram );
						}
					}
				}

				Profile::Board::Roms& roms = (i ? profile.board.chr : profile.board.prg);

				for (dword j=0, k=0, n=roms.size(); j < n; k += roms[j].size, ++j)
					roms[j].hash.Compute( (i ? chr : prg).Mem(k), roms[j].size );
			}

			if (!readOnly)
			{
				Checksum checksum;

				checksum.Compute( prg.Mem(), prg.Size() );

				if (prgCrc)
					*prgCrc = checksum.GetCrc();

				checksum.Compute( chr.Mem(), chr.Size() );
				profile.hash.Assign( checksum.GetSha1(), checksum.GetCrc() );
			}

			if (board)
				*board = Boards::Board::Create( b );

			return RESULT_OK;
		}
void FileTransferSocketThread::execute()
{
    if(info.hostType == eServer)
    {
        ServerSocket serverSocket;
        serverSocket.bind(this->info.serverPort);
        serverSocket.listen(1);
        Socket *clientSocket = serverSocket.accept();

        char data[513]="";
        memset(data, 0, 256);

        clientSocket->receive(data,256, true);
        if(*data == SEND_FILE)
        {
            FileInfo file;

            memcpy(&file, data+1, sizeof(file));

            *data=ACK;
            clientSocket->send(data,256);

            Checksum checksum;
            checksum.addFile(file.fileName);
            file.filecrc  = checksum.getSum();

            ifstream infile(file.fileName.c_str(), ios::in | ios::binary | ios::ate);
            if(infile.is_open() == true)
            {
                file.filesize = infile.tellg();
                infile.seekg (0, ios::beg);

                memset(data, 0, 256);
                *data=SEND_FILE;
                memcpy(data+1,&file,sizeof(file));

                clientSocket->send(data,256);
                clientSocket->receive(data,256, true);
                if(*data != ACK) {
                   //transfer error
                }

                int remain=file.filesize % 512 ;
                int packs=(file.filesize-remain)/512;

                while(packs--)
                {
                    infile.read(data,512);
                    //if(!ReadFile(file,data,512,&read,NULL))
                    //    ; //read error
                    //if(written!=pack)
                    //    ; //read error
                    clientSocket->send(data,512);
                    clientSocket->receive(data,256, true);
                    if(*data!=ACK) {
                           //transfer error
                    }
                }

                infile.read(data,remain);
                //if(!ReadFile(file,data,remain,&read,NULL))
                //   ; //read error
                //if(written!=pack)
                //   ; //read error

                clientSocket->send(data,remain);
                clientSocket->receive(data,256, true);
                if(*data!=ACK) {
                   //transfer error
                }

                infile.close();
            }
        }

        delete clientSocket;
    }
    else
    {
        Ip ip(this->info.serverIP);
        ClientSocket clientSocket;
        clientSocket.connect(this->info.serverIP, this->info.serverPort);

        if(clientSocket.isConnected() == true)
        {
            FileInfo file;
            file.fileName = this->info.fileName;
            //file.filesize =
            //file.filecrc  = this->info.

            string path = extractDirectoryPathFromFile(file.fileName);
            createDirectoryPaths(path);
            ofstream outFile(file.fileName.c_str(), ios_base::binary | ios_base::out);
            if(outFile.is_open() == true)
            {
                char data[513]="";
                memset(data, 0, 256);
                *data=SEND_FILE;
                memcpy(data+1,&file,sizeof(file));

                clientSocket.send(data,256);
                clientSocket.receive(data,256, true);
                if(*data!=ACK) {
                  //transfer error
                }

                clientSocket.receive(data,256,true);
                if(*data == SEND_FILE)
                {
                   memcpy(&file, data+1, sizeof(file));
                   *data=ACK;
                   clientSocket.send(data,256);

                   int remain = file.filesize % 512 ;
                   int packs  = (file.filesize-remain) / 512;

                   while(packs--)
                   {
                      clientSocket.receive(data,512,true);

                      outFile.write(data, 512);
                      if(outFile.bad())
                      {
                          //int ii = 0;
                      }
                      //if(!WriteFile(file,data,512,&written,NULL))
                      //   ; //write error
                      //if(written != pack)
                      //   ; //write error
                      *data=ACK;
                      clientSocket.send(data,256);
                    }
                    clientSocket.receive(data,remain,true);

                    outFile.write(data, remain);
                    if(outFile.bad())
                    {
                        //int ii = 0;
                    }

                    //if(!WriteFile(file,data,remain,&written,NULL))
                    //    ; //write error
                    //if(written!=pack)
                    //    ; //write error
                    *data=ACK;
                    clientSocket.send(data,256);

                    Checksum checksum;
                    checksum.addFile(file.fileName);
                    uint32 crc = checksum.getSum();
                    if(file.filecrc != crc)
                    {
                        //int ii = 0;
                    }

                    //if(calc_crc(file)!=info.crc)
                    //   ; //transfeer error
                }

                outFile.close();
            }
        }
    }
}