void WorldSession::ReadAddonsInfo(WorldPacket &data)
{
    if (data.rpos() + 4 > data.size())
        return;

    uint32 size;
    data >> size;

    if (!size)
        return;

    if (size > 0xFFFFF)
    {
        sLog->outError(LOG_FILTER_GENERAL, "WorldSession::ReadAddonsInfo addon info too big, size %u", size);
        return;
    }

    uLongf uSize = size;

    uint32 pos = data.rpos();

    ByteBuffer addonInfo;
    addonInfo.resize(size);

    if (uncompress(addonInfo.contents(), &uSize, data.contents() + pos, data.size() - pos) == Z_OK)
    {
        uint32 addonsCount;
        addonInfo >> addonsCount;                         // addons count

        for (uint32 i = 0; i < addonsCount; ++i)
        {
            std::string addonName;
            uint8 enabled;
            uint32 crc, unk1;

            // check next addon data format correctness
            if (addonInfo.rpos() + 1 > addonInfo.size())
                return;

            addonInfo >> addonName;

            addonInfo >> enabled >> crc >> unk1;

            sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);

            AddonInfo addon(addonName, enabled, crc, 2, true);

            SavedAddon const* savedAddon = AddonMgr::GetAddonInfo(addonName);
            if (savedAddon)
            {
                bool match = true;

                if (addon.CRC != savedAddon->CRC)
                    match = false;

                if (!match)
                    sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s was known, but didn't match known CRC (0x%x)!", addon.Name.c_str(), savedAddon->CRC);
                else
                    sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s was known, CRC is correct (0x%x)", addon.Name.c_str(), savedAddon->CRC);
            }
            else
            {
                AddonMgr::SaveAddon(addon);

                sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s (0x%x) was not known, saving...", addon.Name.c_str(), addon.CRC);
            }

            /// @todo Find out when to not use CRC/pubkey, and other possible states.
            m_addonsList.push_back(addon);
        }

        uint32 currentTime;
        addonInfo >> currentTime;
        sLog->outDebug(LOG_FILTER_NETWORKIO, "ADDON: CurrentTime: %u", currentTime);

        if (addonInfo.rpos() != addonInfo.size())
            sLog->outDebug(LOG_FILTER_NETWORKIO, "packet under-read!");
    }
Example #2
0
int main()
{
	//Transpose
	vec4 mat[4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};

	__m128i xmm0 = _mm_unpacklo_epi32(_mm_castps_si128(mat[0]), _mm_castps_si128(mat[1]));
	__m128i xmm1 = _mm_unpackhi_epi32(_mm_castps_si128(mat[0]), _mm_castps_si128(mat[1]));
	__m128i xmm2 = _mm_unpacklo_epi32(_mm_castps_si128(mat[2]), _mm_castps_si128(mat[3]));
	__m128i xmm3 = _mm_unpackhi_epi32(_mm_castps_si128(mat[2]), _mm_castps_si128(mat[3]));

	vec4 trans[4];

	trans[0] = _mm_castsi128_ps(_mm_unpacklo_epi64(xmm0, xmm2));
	trans[1] = _mm_castsi128_ps(_mm_unpackhi_epi64(xmm0, xmm2));
	trans[2] = _mm_castsi128_ps(_mm_unpacklo_epi64(xmm1, xmm3));
	trans[3] = _mm_castsi128_ps(_mm_unpackhi_epi64(xmm1, xmm3));

	vec4 trans2[4];

	ml::transpose(trans2, mat);

	FILE* file = fopen("..\\..\\AppData\\VT.swf", "rb");
	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	fseek(file, 0, SEEK_SET);
	unsigned char* fileData = (unsigned char*)malloc(size);
	fread(fileData, 1, size, file);
	fclose(file);

	MemReader data = {(const char*)fileData, (const char*)fileData+size, (const char*)fileData};
	
	//Read SWF header
	const u32 signatureAndVersion	= data.read<u32>();
	const u32 actualSize			= data.read<u32>();

	u32 signature = signatureAndVersion&0x00FFFFFF;
	u8	version = signatureAndVersion>>24;

	bool isCompressed   = signature=='\0SWC';
	bool isUncompressed = signature=='\0SWF';

	//if !isCompressed && !isUncompressed return error;

	MemReader data2 = {0, 0, 0};

	char* uncompressed = 0;
	if (isCompressed)
	{
		 uncompressed = (char*)malloc(actualSize-8);
		 data2.cur = data2.start = uncompressed;
		 data2.end = uncompressed+actualSize-8;
		 uLongf uncompressedSize = actualSize-8;
		 uncompress((Bytef*)uncompressed, &uncompressedSize, data.as<Bytef>(), size-8);
	}
	else if (isCompressed)
	{
		data2.cur = data2.start = data.as<char>();
		data2.end = data2.start+actualSize-8;
	}

	
	u8 bits = data2.read<u8>();
	u8 numBits = bits>>3;

	u32 rectSizeMinusOne = (numBits*4+5)>>3;
	data2.move(rectSizeMinusOne);
	
	const u16 frameRate	 = data2.read<u16>();
	const u16 frameCount = data2.read<u16>();

	std::set<u32>	tagsUsed;
	size_t tagCount = 0;

	while (data2.cur!=data2.end)
	{
		u16 tagHeader = data2.read<u16>();
		u32 tagLength = tagHeader&0x3F;
		u32 tagType = tagHeader>>6;
		tagsUsed.insert(tagType);

		if (tagLength==0x3F)
			tagLength = data2.read<u32>();
		data2.move(tagLength);

		parseTag(tagType);

		++tagCount;
	}

	if (uncompressed) free(uncompressed);

	printf("\nProcessed %d tags\n\n", tagCount);

	printf("        Tags used        \n");
	printf("-------------------------\n");

	std::set<u32>::iterator	it  = tagsUsed.begin(),
							end = tagsUsed.end();

	for (; it!=end; ++it)
	{
		parseTag(*it);
	}

	free(fileData);
}
Example #3
0
UPK_STATUS
NitroPlus::
GetFileData(
    UNPACKER_FILE_INFO         *FileInfo,
    UNPACKER_FILE_ENTRY_BASE   *BaseEntry,
    ULONG                       Flags /* = 0 */
)
{
    PBYTE               Buffer;
    ULONG               Size;
    NTSTATUS            Status;
    NITRO_PLUS_ENTRY   *Entry;

    Entry = (NITRO_PLUS_ENTRY *)BaseEntry;

    if (FLAG_ON(Entry->Attributes, FILE_ATTRIBUTE_DIRECTORY))
        return STATUS_UNSUCCESSFUL;

    Status = m_File.Seek(Entry->Offset, FILE_BEGIN);
    FAIL_RETURN(Status);

    Size   = Entry->CompressedSize.LowPart;
    Buffer = (PBYTE)AllocateMemory(Size);
    if (Buffer == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    FileInfo->FileType                  = UnpackerFileBinary;
    FileInfo->BinaryData.Buffer         = Buffer;
    FileInfo->BinaryData.Size.QuadPart  = Size;

    Status = m_File.Read(Buffer, Size);
    FAIL_RETURN(Status);

    if (FLAG_ON(Flags, UNPACKER_SAVE_RAW_DATA))
        return STATUS_SUCCESS;

    if (FLAG_ON(Entry->Flags, UNPACKER_ENTRY_ENCRYPTED))
    {
        DecryptData(Buffer, Entry->DecryptLength, Entry->Seed);
//        EncryptData(Buffer, Entry->DecryptLength, Entry->Seed);
//        DecryptData(Buffer, Entry->DecryptLength, Entry->Seed);
    }

    if (FLAG_ON(Entry->Flags, UNPACKER_ENTRY_COMPRESSED))
    {
        Size = Entry->Size.LowPart;
        Buffer = (PBYTE)AllocateMemory(Size);
        if (Buffer == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        Status = uncompress(Buffer, &Size, FileInfo->BinaryData.Buffer, FileInfo->BinaryData.Size.LowPart);
        FreeMemory(FileInfo->BinaryData.Buffer);

        FileInfo->BinaryData.Buffer         = Buffer;
        FileInfo->BinaryData.Size.QuadPart  = Size;

        if (Status != Z_OK)
        {
            return STATUS_UNSUCCESSFUL;
        }
    }

    return STATUS_SUCCESS;
}
Example #4
0
/*
 * Function to decompress a compressed message
 */
static int mc_decompress(struct sip_msg* msg)
{
	#define HDRS_TO_SKIP 4

	int i;
	int j;
	int rc;
	int algo=-1;
	int hdrs_algo=-1;
	int b64_required=-1;

	str msg_body;
	str msg_final;

	str b64_decode={NULL, 0};
	str hdr_b64_decode={NULL,0};
	str uncomp_body={NULL,0};
	str uncomp_hdrs={NULL,0};

	char *new_buf;

	unsigned long temp;

	/* hdr_vec allows to sort the headers. This will help skipping
		these headers when building the new message */
	struct hdr_field *hf;
	struct hdr_field *hdr_vec[HDRS_TO_SKIP];
					/*hdr_vec : 	0 Content-Length
							1 Comp-Hdrs
							2 Headers-Algo
							3 Content-Encoding*/

	memset(hdr_vec, 0, HDRS_TO_SKIP * sizeof(struct hdr_field*));

	if (parse_headers(msg, HDR_EOH_F, 0) != 0) {
		LM_ERR("failed to parse SIP message\n");
		return -1;
	}

	/*If compressed with this module there are great chances that Content-Encoding is last*/
	hdr_vec[3] = msg->last_header;

	if (!is_content_encoding(hdr_vec[3])) {
		hdr_vec[3] = NULL;
		for (hf = msg->headers; hf; hf = hf->next) {
			if (is_content_encoding(hf)) {
				hdr_vec[3] = hf;
				continue;
			}
			if (hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) {
				hdr_vec[1] = hf;
				continue;
			}

			if (hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, HDRS_ENCODING,
						sizeof(HDRS_ENCODING)-1)) {
				hdr_vec[2] = hf;
			}

			if (hdr_vec[1] && hdr_vec[2] && hdr_vec[3])
					break;
		}
	} else {
		for (hf = msg->headers; hf; hf = hf->next) {
			if (!hdr_vec[1] && hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) {
				hdr_vec[1] = hf;
				continue;
			}

			if (!hdr_vec[2] && hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, HDRS_ENCODING,
						sizeof(HDRS_ENCODING)-1))
				hdr_vec[2] = hf;

			if (hdr_vec[2] && hdr_vec[3] && hdr_vec[1])
					break;
		}
	}

	/* Only if content-encoding present, Content-Length will be replaced
		with the one in the compressed body or in compressed headers*/

	if (hdr_vec[3]) {
		hdr_vec[0] = msg->content_length;
		parse_algo_hdr(hdr_vec[3], &algo, &b64_required);
	}


	if (b64_required > 0 && hdr_vec[3]) {
		msg_body.s = msg->last_header->name.s + msg->last_header->len + CRLF_LEN;
		msg_body.len = strlen(msg_body.s);

		/* Cutting CRLF'S at the end of the message */
		while (WORD(msg_body.s + msg_body.len-CRLF_LEN) == PARSE_CRLF) {
			msg_body.len -= CRLF_LEN;
		}

		if (wrap_realloc(&body_in, calc_max_base64_decode_len(msg_body.len)))
			return -1;

		b64_decode.s = body_in.s;

		b64_decode.len = base64decode((unsigned char*)b64_decode.s,
						(unsigned char*)msg_body.s,
							msg_body.len);
	} else if (hdr_vec[3]) {
		if (get_body(msg, &msg_body) < 0) {
			LM_ERR("failed to get body\n");
			return -1;
		}

		b64_decode.s = msg_body.s;
		b64_decode.len = msg_body.len;
	}

	b64_required=0;
	if (hdr_vec[2]) {
		parse_algo_hdr(hdr_vec[3], &algo, &b64_required);
	}

	if (b64_required > 0 &&  hdr_vec[1]) {
		if (wrap_realloc(&hdr_in, calc_max_base64_decode_len(hdr_vec[1]->body.len)))
			return -1;

		hdr_b64_decode.s = hdr_in.s;

		hdr_b64_decode.len = base64decode(
					(unsigned char*)hdr_b64_decode.s,
					(unsigned char*)hdr_vec[1]->body.s,
							hdr_vec[1]->body.len
					);
	} else if (hdr_vec[1]) {
		hdr_b64_decode.s = hdr_vec[1]->body.s;
		hdr_b64_decode.len = hdr_vec[1]->body.len;
	}

	switch (hdrs_algo) {
		case 0: /* deflate */
			temp = (unsigned long)BUFLEN;

			rc = uncompress((unsigned char*)hdr_buf,
					&temp,
					(unsigned char*)hdr_b64_decode.s,
					(unsigned long)hdr_b64_decode.len);

			uncomp_hdrs.s = hdr_buf;
			uncomp_hdrs.len = temp;

			if (check_zlib_rc(rc)) {
				LM_ERR("header decompression failed\n");
				return -1;
			}
			break;
		case 1: /* gzip */
			rc = gzip_uncompress(
					(unsigned char*)hdr_b64_decode.s,
					(unsigned long)hdr_b64_decode.len,
					&hdr_out,
					&temp);

			if (check_zlib_rc(rc)) {
				LM_ERR("header decompression failed\n");
				return -1;
			}

			uncomp_hdrs.s = hdr_out.s;
			uncomp_hdrs.len = temp;

			break;
		case -1:
			break;
		default:
			return -1;
	}

	switch (algo) {
		case 0: /* deflate */
			temp = (unsigned long)BUFLEN;

			rc = uncompress((unsigned char*)body_buf,
					&temp,
					(unsigned char*)b64_decode.s,
					(unsigned long)b64_decode.len);

			if (check_zlib_rc(rc)) {
				LM_ERR("body decompression failed\n");
				return -1;
			}

			uncomp_body.s = body_buf;
			uncomp_body.len = temp;

			break;
		case 1: /* gzip */
			rc = gzip_uncompress(
					(unsigned char*)b64_decode.s,
					(unsigned long)b64_decode.len,
					&body_out,
					&temp);

			if (check_zlib_rc(rc)) {
				LM_ERR("body decompression failed\n");
				return -1;
			}

			uncomp_body.s = body_out.s;
			uncomp_body.len = temp;

			break;
		case -1:
			LM_DBG("no body\n");
			break;
		default:
			LM_ERR("invalid algo\n");
			return -1;
	}

	/* Sort to have the headers in order */
	for (i = 0; i < HDRS_TO_SKIP - 1; i++) {
		for (j = i + 1; j < HDRS_TO_SKIP; j++) {
			if (!hdr_vec[j])
				continue;

			if (!hdr_vec[i] && hdr_vec[j]) {
				hdr_vec[i] = hdr_vec[j];
				hdr_vec[j] = NULL;
			}

			if ((hdr_vec[i] && hdr_vec[j]) &&
				(hdr_vec[i]->name.s > hdr_vec[j]->name.s)) {
				hf = hdr_vec[i];
				hdr_vec[i] = hdr_vec[j];
				hdr_vec[j] = hf;
			}
		}
	}

	int msg_final_len = 0;
	int msg_ptr=0;

	for ( i = 0; i < HDRS_TO_SKIP; i++) {
		if (hdr_vec[i]) {
			msg_final_len += hdr_vec[i]->name.s - (msg->buf+msg_ptr);
			msg_ptr += hdr_vec[i]->name.s+hdr_vec[i]->len - (msg->buf+msg_ptr);
		}
	}

	msg_final_len += msg->last_header->name.s + msg->last_header->len -
				(msg->buf + msg_ptr);

	if (hdrs_algo >= 0)
		msg_final_len += uncomp_hdrs.len;

	if (algo >= 0)
		msg_final_len += uncomp_body.len;
	else
		msg_final_len += strlen(msg->eoh);

	if (wrap_realloc(&buf_out, msg_final_len))
		return -1;

	msg_ptr = 0;

	msg_final.len = 0;
	msg_final.s = buf_out.s;

	for ( i = 0; i < HDRS_TO_SKIP; i++) {
		if (hdr_vec[i]) {
			wrap_copy_and_update(&msg_final.s,
					msg->buf+msg_ptr,
					hdr_vec[i]->name.s-(msg->buf+msg_ptr),
					&msg_final.len);

			msg_ptr += (hdr_vec[i]->name.s+hdr_vec[i]->len) -
					(msg->buf+msg_ptr);
		}
	}

	wrap_copy_and_update(
			&msg_final.s,
			msg->buf+msg_ptr,
			(msg->last_header->name.s+msg->last_header->len)-
							(msg->buf+msg_ptr),
			&msg_final.len
		);

	if (hdrs_algo >= 0) {
		wrap_copy_and_update(&msg_final.s, uncomp_hdrs.s,
					uncomp_hdrs.len,&msg_final.len);
	}

	if (algo >= 0) {
		wrap_copy_and_update(&msg_final.s, uncomp_body.s,
					uncomp_body.len, &msg_final.len);
	} else {
		wrap_copy_and_update(&msg_final.s, msg->eoh, strlen(msg->eoh), &msg_final.len);
	}

	/* new buffer because msg_final(out_buf) will
	 * be overwritten at next iteration */
#ifdef DYN_BUF
	new_buf = pkg_malloc(msg_final.len+1);
	if (new_buf == NULL) {
		LM_ERR("no more pkg mem\n");
		return -1;
	}
#else
	new_buf = msg->buf;
#endif

	memcpy(new_buf, msg_final.s, msg_final.len);
	new_buf[msg_final.len] = '\0';

	struct sip_msg tmp;

	memcpy(&tmp, msg, sizeof(struct sip_msg));

	/*reset dst_uri and path_vec to avoid free*/
	if (msg->dst_uri.s != NULL) {
		msg->dst_uri.s = NULL;
		msg->dst_uri.len = 0;
	}
	if (msg->path_vec.s != NULL)
	{
		msg->path_vec.s = NULL;
		msg->path_vec.len = 0;
	}

	free_sip_msg(msg);
	memset(msg, 0, sizeof(struct sip_msg));

	/* restore msg fields */
	msg->id					= tmp.id;
	msg->rcv				= tmp.rcv;
	msg->set_global_address = tmp.set_global_address;
	msg->set_global_port    = tmp.set_global_port;
	msg->flags              = tmp.flags;
	msg->msg_flags          = tmp.msg_flags;
	msg->hash_index         = tmp.hash_index;
	msg->force_send_socket  = tmp.force_send_socket;
	msg->dst_uri            = tmp.dst_uri;
	msg->path_vec           = tmp.path_vec;
	/* set the new ones */
	msg->buf = new_buf;
	msg->len = msg_final.len;

	/* reparse the message */
	if (parse_msg(msg->buf, msg->len, msg) != 0)
		LM_ERR("parse_msg failed\n");

	return 1;
}
Example #5
0
    void TileLayer::ParseBase64(const std::string &innerText) 
    {
    	std::string testText = innerText;
    	Util::Trim( testText );

        const std::string &text = Util::DecodeBase64(testText);

        // Temporary array of gids to be converted to map tiles.
        unsigned *out = 0;

        if (compression == TMX_COMPRESSION_ZLIB) 
        {
            // Use zlib to uncompress the tile layer into the temporary array of tiles.
            uLongf outlen = width * height * 4;
            out = (unsigned *)malloc(outlen);
            uncompress(
                (Bytef*)out, &outlen, 
                (const Bytef*)text.c_str(), text.size());
    
        } 
        else if (compression == TMX_COMPRESSION_GZIP) 
        {
            // Use the utility class for decompressing (which uses zlib)
            out = (unsigned *)Util::DecompressGZIP(
                text.c_str(), 
                text.size(), 
                width * height * 4);
        } 
        else 
        {
            out = (unsigned *)malloc(text.size());
        
            // Copy every gid into the temporary array since
            // the decoded string is an array of 32-bit integers.
            memcpy(out, text.c_str(), text.size());
        }

        // Convert the gids to map tiles.
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                unsigned gid = out[y * width + x];

                // Find the tileset index.
                const int tilesetIndex = map->FindTilesetIndex(gid);
                if (tilesetIndex != -1)
                {
                    // If valid, set up the map tile with the tileset.
                    const Tmx::Tileset* tileset = map->GetTileset(tilesetIndex);
                    tile_map[y * width + x] = MapTile(gid, tileset->GetFirstGid(), tilesetIndex);
                }
                else
                {
                    // Otherwise, make it null.
                    tile_map[y * width + x] = MapTile(gid, 0, -1);
                }
            }
        }

        // Free the temporary array from memory.
        free(out);
    }
Example #6
0
void CFontList::InstallFont(BYTE* pBytes, DWORD dwLen, int index)
{
	if (!pBytes || !dwLen || index < 0 || index >= sizeof(OurFontList)/sizeof(FONTRECORD))
		return;

	FONTRECORD& InstallFontRec = OurFontList[index];
	char szFileName[MAX_PATH];
	lstrcpy(szFileName, InstallFontRec.pFileName);
	szFileName[lstrlen(szFileName) - 1] = 'F'; // Change the .TTZ to .TTF
	CString strPath = CTrueType::GetPathFromFileName(szFileName);
	CString strTempPath = CTrueType::GetTempPathFromFileName(szFileName);
	
	// Uncompress the font data
	DWORD dwUncompressedLen = *((DWORD*)pBytes);
	BYTE* pUncompressedBytes = new BYTE[dwUncompressedLen];
	if (!pUncompressedBytes)
		return;

	int iRet = uncompress(pUncompressedBytes, &dwUncompressedLen, pBytes + 4, dwLen - 4);
	if (iRet != Z_OK)
	{
		delete [] pUncompressedBytes;
		return;
	}

	// See if the font file already exists
	bool bCopy = (dwUncompressedLen != FileSize(strPath));
	if (bCopy)
	{
		int bRemoved = ::RemoveFontResource(strPath);

		// Write the font data to disk
		HANDLE hFile = ::CreateFile(strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile == INVALID_HANDLE_VALUE)
		{
			if (dwUncompressedLen != FileSize(strTempPath))
			{
				hFile = ::CreateFile(strTempPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
				strPath = strTempPath;
			}
		}
		if (hFile != INVALID_HANDLE_VALUE)
		{
			DWORD dwWritten = 0;
			::WriteFile(hFile, pUncompressedBytes, dwUncompressedLen, &dwWritten, NULL);
			::CloseHandle(hFile);
		}		
	}

	delete [] pUncompressedBytes;

	// Make the font installation permanent by adding the font's display name and filename to the registry 
	CTrueType::AddToRegistry(InstallFontRec.pRegistryName, szFileName);
	
	// Make the font available immediately
	int nFontsAdded = ::AddFontResource(strPath);

	// Warn the user if the font doesn't appear to be installed
	if (nFontsAdded <= 0)  
		CMessageBox::Message(String("Error installing font '%s'.", InstallFontRec.pRegistryName));
}
Example #7
0
HttpTask::~HttpTask()
{
    if(!_buffer.empty())
    {
	bool unzip_ok = false;
	int retry_count = 0;
	unsigned int nRecvCmdLen = *((unsigned int *)&_buffer[0]);
	Zebra::logger->debug("HttpTask::~HttpTask %u,%u", _buffer.size(), nRecvCmdLen);
	std::vector<char> _unzip_buffer(_buffer.size()*3);
	uLong nUnzipLen = _unzip_buffer.size();
do_retry:
	switch(uncompress((Bytef *)&_unzip_buffer[0], &nUnzipLen, (const Bytef *)&_buffer[4], nRecvCmdLen))
	{
	    case Z_OK:
		Zebra::logger->debug("Z_OK");
		unzip_ok = true;
		break;
	    case Z_MEM_ERROR:
		Zebra::logger->debug("Z_MEM_ERROR");
		break;
	    case Z_BUF_ERROR:
		Zebra::logger->debug("Z_BUF_ERROR");
		if(++retry_count <= 16)
		{
		    _unzip_buffer.resize(_unzip_buffer.size()*2);
		    nUnzipLen = _unzip_buffer.size();
		    goto do_retry;
		}
		break;
	    case Z_DATA_ERROR:
		Zebra::logger->debug("Z_DATA_ERROR");
		break;
	}

	if(unzip_ok)
	{
	    connHandleID handle = DumpServer::dbConnPool->getHandle();
	    if((connHandleID)-1 == handle)
	    {
		Zebra::logger->error("不能获取数据库句柄");
	    }
	    else
	    {
		const char *sql_template = "";
		char sqlBuf[512];
		memset(sqlBuf, 0, sizeof(sqlBuf));

		char timeBuffer[128];
		memset(timeBuffer, 0, sizeof(timeBuffer));
		time_t  t;
		struct tm *tmp;
		t = time(NULL);
		tmp = localtime(&t);
		strftime(timeBuffer, sizeof(timeBuffer),"%Y%m%d", tmp);

		sprintf(sqlBuf, sql_template, timeBuffer);
		if(DumpServer::dbConnPool->execSql(handle, sqlBuf, strlen(sqlBuf)))
		{
		    Zebra::logger->error("执行建表sql出错");
		}
		else
		{
		    DumpData *pData = (DumpData*)&_unzip_buffer[0];
		    pData->account[MAX_NAMESIZE-1] = '\0';
		    pData->userName[MAX_NAMESIZE-1] = '\0';
		    pData->gameName[MAX_NAMESIZE-1] = '\0';
		    pData->zoneName[MAX_NAMESIZE-1] = '\0';
		    std::vector<char> log(2*pData->logSize+1), desc(2*pData->descSize+1), data(2*pData->dataSize+1);
		    DumpServer::dbConnPool->escapeString(handle, &_unzip_buffer[sizeof(DumpData)], &log[0], pData->logSize);
		    DumpServer::dbConnPool->escapeString(handle, &_unzip_buffer[sizeof(DumpData)+pData->logSize], &desc[0], pData->descSize);
		    DumpServer::dbConnPool->escapeString(handle, &_unzip_buffer[sizeof(DumpData)+pData->logSize+pData->descSize], &data[0], pData->dataSize);

		    std::ostringstream strSql;
		    strSql<<"INSERT INTO 'ErrorDump" <<timeBuffer<<"' VALUES(\'"
			<<pData->account<<"\', \'"
			<<pData->userName<<"\', \'"
			<<pData->gameName<<"\', \'"
			<<pData->zoneName<<"\', \'"
			<<pData->version<<"\', \'"
			<<(char *)&log[0]<<"\', \'"
			<<(char *)&desc[0]<<"\', \'"
			<<(char *)&data[0]<<"\'";

		    char *tmpversion = strstr((char *)&log[0], "Exception Address");
		    std::string Ver="";
		    if(NULL != tmpversion)
		    {
			char *temp = NULL;
			temp = strtok((char *)&tmpversion[18], "\\r\\n");
			if(NULL != temp)
			{
			    Ver = temp;
			}
		    }
		    strSql <<",\'"<<Ver<<"\'";

		    char *tmpaddress = strstr((char *)&log[0], "Version");
		    std::string Add="";
		    if(NULL != tmpaddress)
		    {
			char *temp = NULL;
			temp = strtok((char *)&tmpaddress[10], "\\r\\n");
			if(NULL != temp)
			{
			    Add = temp;
			}
		    }
		    strSql <<",\'"<<Add<<"\'";

		    memset(timeBuffer, 0, sizeof(timeBuffer));
		    strftime(timeBuffer, sizeof(timeBuffer),"%Y%m%d%H%M%S", tmp);
		    strSql<<",\'"<<timeBuffer<<"\')";
			
		    if(DumpServer::dbConnPool->execSql(handle, strSql.str().c_str(), strSql.str().length()))
		    {
			Zebra::logger->error("执行sql语句出错");
		    }

		}
		DumpServer::dbConnPool->putHandle(handle);
	    }
	}

    }
}
Example #8
0
/* Decompresses data using the compression method
 * Returns 1 on success, 0 on failure or -1 on error
 */
int libvmdk_decompress_data(
     const uint8_t *compressed_data,
     size_t compressed_data_size,
     uint16_t compression_method,
     uint8_t *uncompressed_data,
     size_t *uncompressed_data_size,
     libcerror_error_t **error )
{
	static char *function              = "libvmdk_decompress_data";
	int result                         = 0;

#if defined( HAVE_ZLIB ) || defined( ZLIB_DLL )
	uLongf zlib_uncompressed_data_size = 0;
#endif

	if( compressed_data == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid compressed data buffer.",
		 function );

		return( -1 );
	}
	if( uncompressed_data == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid uncompressed data buffer.",
		 function );

		return( -1 );
	}
	if( uncompressed_data == compressed_data )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid compressed data buffer equals uncompressed data buffer.",
		 function );

		return( -1 );
	}
	if( uncompressed_data_size == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid uncompressed data size.",
		 function );

		return( -1 );
	}
	if( compression_method == LIBVMDK_COMPRESSION_METHOD_DEFLATE )
	{
#if defined( HAVE_ZLIB ) || defined( ZLIB_DLL )
		if( compressed_data_size > (size_t) ULONG_MAX )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
			 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
			 "%s: invalid compressed data size value exceeds maximum.",
			 function );

			return( -1 );
		}
		if( *uncompressed_data_size > (size_t) ULONG_MAX )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
			 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
			 "%s: invalid uncompressed data size value exceeds maximum.",
			 function );

			return( -1 );
		}
		zlib_uncompressed_data_size = (uLongf) *uncompressed_data_size;

		result = uncompress(
			  (Bytef *) uncompressed_data,
			  &zlib_uncompressed_data_size,
			  (Bytef *) compressed_data,
			  (uLong) compressed_data_size );

		if( result == Z_OK )
		{
			*uncompressed_data_size = (size_t) zlib_uncompressed_data_size;

			result = 1;
		}
		else if( result == Z_DATA_ERROR )
		{
#if defined( HAVE_DEBUG_OUTPUT )
			if( libcnotify_verbose != 0 )
			{
				libcnotify_printf(
				 "%s: unable to read compressed data: data error.\n",
				 function );
			}
#endif
			*uncompressed_data_size = 0;

			result = -1;
		}
		else if( result == Z_BUF_ERROR )
		{
#if defined( HAVE_DEBUG_OUTPUT )
			if( libcnotify_verbose != 0 )
			{
				libcnotify_printf(
				"%s: unable to read compressed data: target buffer too small.\n",
				 function );
			}
#endif
			/* Estimate that a factor 2 enlargement should suffice
			 */
			*uncompressed_data_size *= 2;

			result = 0;
		}
		else if( result == Z_MEM_ERROR )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_MEMORY,
			 LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
			 "%s: unable to read compressed data: insufficient memory.",
			 function );

			*uncompressed_data_size = 0;

			result = -1;
		}
		else
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_COMPRESSION,
			 LIBCERROR_COMPRESSION_ERROR_DECOMPRESS_FAILED,
			 "%s: zlib returned undefined error: %d.",
			 function,
			 result );

			*uncompressed_data_size = 0;

			result = -1;
		}
#else
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE,
		 "%s: missing support for deflate compression.",
		 function );

		return( -1 );
#endif /* defined( HAVE_ZLIB ) || defined( ZLIB_DLL ) */
	}
	else
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE,
		 "%s: unsupported compression method.",
		 function );

		return( -1 );
	}
	return( result );
}
Example #9
0
/*
 * Decode the specified CTF buffer and optional symbol table and create a new
 * CTF container representing the symbolic debugging information.  This code
 * can be used directly by the debugger, or it can be used as the engine for
 * ctf_fdopen() or ctf_open(), below.
 */
ctf_file_t *
ctf_bufopen(const ctf_sect_t *ctfsect, const ctf_sect_t *symsect,
    const ctf_sect_t *strsect, int *errp)
{
	const ctf_preamble_t *pp;
	ctf_header_t hp;
	ctf_file_t *fp;
	void *buf, *base;
	size_t size, hdrsz;
	int err;

	if (ctfsect == NULL || ((symsect == NULL) != (strsect == NULL)))
		return (ctf_set_open_errno(errp, EINVAL));

	if (symsect != NULL && symsect->cts_entsize != sizeof (Elf32_Sym) &&
	    symsect->cts_entsize != sizeof (Elf64_Sym))
		return (ctf_set_open_errno(errp, ECTF_SYMTAB));

	if (symsect != NULL && symsect->cts_data == NULL)
		return (ctf_set_open_errno(errp, ECTF_SYMBAD));

	if (strsect != NULL && strsect->cts_data == NULL)
		return (ctf_set_open_errno(errp, ECTF_STRBAD));

	if (ctfsect->cts_size < sizeof (ctf_preamble_t))
		return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));

	pp = (const ctf_preamble_t *)ctfsect->cts_data;

	ctf_dprintf("ctf_bufopen: magic=0x%x version=%u\n",
	    pp->ctp_magic, pp->ctp_version);

	/*
	 * Validate each part of the CTF header (either V1 or V2).
	 * First, we validate the preamble (common to all versions).  At that
	 * point, we know specific header version, and can validate the
	 * version-specific parts including section offsets and alignments.
	 */
	if (pp->ctp_magic != CTF_MAGIC)
		return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));

	if (pp->ctp_version != CTF_VERSION_1)
		return (ctf_set_open_errno(errp, ECTF_CTFVERS));

	if (ctfsect->cts_size < sizeof (ctf_header_t))
		return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));

	bcopy(ctfsect->cts_data, &hp, sizeof (hp));
	hdrsz = sizeof (ctf_header_t);

	size = hp.cth_stroff + hp.cth_strlen;

	ctf_dprintf("ctf_bufopen: uncompressed size=%lu\n", (ulong_t)size);

	if (hp.cth_lbloff > size || hp.cth_objtoff > size ||
	    hp.cth_funcoff > size || hp.cth_typeoff > size ||
	    hp.cth_stroff > size)
		return (ctf_set_open_errno(errp, ECTF_CORRUPT));

	if (hp.cth_lbloff > hp.cth_objtoff ||
	    hp.cth_objtoff > hp.cth_funcoff ||
	    hp.cth_funcoff > hp.cth_typeoff ||
	    hp.cth_funcoff > hp.cth_varoff ||
	    hp.cth_varoff > hp.cth_typeoff ||
	    hp.cth_typeoff > hp.cth_stroff)
		return (ctf_set_open_errno(errp, ECTF_CORRUPT));

	if ((hp.cth_lbloff & 3) || (hp.cth_objtoff & 1) ||
	    (hp.cth_funcoff & 1) || (hp.cth_varoff & 3) ||
	    (hp.cth_typeoff & 3))
		return (ctf_set_open_errno(errp, ECTF_CORRUPT));

	/*
	 * Once everything is determined to be valid, attempt to decompress
	 * the CTF data buffer if it is compressed.  Otherwise we just put
	 * the data section's buffer pointer into ctf_buf, below.
	 */
	if (hp.cth_flags & CTF_F_COMPRESS) {
		size_t srclen, dstlen;
		const void *src;
		int rc = Z_OK;

		if ((base = ctf_data_alloc(size + hdrsz)) == MAP_FAILED)
			return (ctf_set_open_errno(errp, ECTF_ZALLOC));

		bcopy(ctfsect->cts_data, base, hdrsz);
		((ctf_preamble_t *)base)->ctp_flags &= ~CTF_F_COMPRESS;
		buf = (uchar_t *)base + hdrsz;

		src = (uchar_t *)ctfsect->cts_data + hdrsz;
		srclen = ctfsect->cts_size - hdrsz;
		dstlen = size;

		if ((rc = uncompress(buf, &dstlen, src, srclen)) != Z_OK) {
			ctf_dprintf("zlib inflate err: %s\n", zError(rc));
			ctf_data_free(base, size + hdrsz);
			return (ctf_set_open_errno(errp, ECTF_DECOMPRESS));
		}

		if (dstlen != size) {
			ctf_dprintf("zlib inflate short -- got %lu of %lu "
			    "bytes\n", (ulong_t)dstlen, (ulong_t)size);
			ctf_data_free(base, size + hdrsz);
			return (ctf_set_open_errno(errp, ECTF_CORRUPT));
		}

		ctf_data_protect(base, size + hdrsz);

	} else {
		base = (void *)ctfsect->cts_data;
		buf = (uchar_t *)base + hdrsz;
	}

	/*
	 * Once we have uncompressed and validated the CTF data buffer, we can
	 * proceed with allocating a ctf_file_t and initializing it.
	 */
	if ((fp = ctf_alloc(sizeof (ctf_file_t))) == NULL)
		return (ctf_set_open_errno(errp, EAGAIN));

	bzero(fp, sizeof (ctf_file_t));
	fp->ctf_version = hp.cth_version;
	fp->ctf_fileops = &ctf_fileops[hp.cth_version];
	bcopy(ctfsect, &fp->ctf_data, sizeof (ctf_sect_t));

	if (symsect != NULL) {
		bcopy(symsect, &fp->ctf_symtab, sizeof (ctf_sect_t));
		bcopy(strsect, &fp->ctf_strtab, sizeof (ctf_sect_t));
	}

	if (fp->ctf_data.cts_name != NULL)
		fp->ctf_data.cts_name = ctf_strdup(fp->ctf_data.cts_name);
	if (fp->ctf_symtab.cts_name != NULL)
		fp->ctf_symtab.cts_name = ctf_strdup(fp->ctf_symtab.cts_name);
	if (fp->ctf_strtab.cts_name != NULL)
		fp->ctf_strtab.cts_name = ctf_strdup(fp->ctf_strtab.cts_name);

	if (fp->ctf_data.cts_name == NULL)
		fp->ctf_data.cts_name = _CTF_NULLSTR;
	if (fp->ctf_symtab.cts_name == NULL)
		fp->ctf_symtab.cts_name = _CTF_NULLSTR;
	if (fp->ctf_strtab.cts_name == NULL)
		fp->ctf_strtab.cts_name = _CTF_NULLSTR;

	fp->ctf_str[CTF_STRTAB_0].cts_strs = (const char *)buf + hp.cth_stroff;
	fp->ctf_str[CTF_STRTAB_0].cts_len = hp.cth_strlen;

	if (strsect != NULL) {
		fp->ctf_str[CTF_STRTAB_1].cts_strs = strsect->cts_data;
		fp->ctf_str[CTF_STRTAB_1].cts_len = strsect->cts_size;
	}

	fp->ctf_base = base;
	fp->ctf_buf = buf;
	fp->ctf_size = size + hdrsz;
	fp->ctf_vars = (ctf_varent_t *)((const char *)buf + hp.cth_varoff);
	fp->ctf_nvars = (hp.cth_typeoff - hp.cth_varoff) / sizeof (ctf_varent_t);

	/*
	 * If we have a parent container name and label, store the relocated
	 * string pointers in the CTF container for easy access later.
	 */
	if (hp.cth_parlabel != 0)
		fp->ctf_parlabel = ctf_strptr(fp, hp.cth_parlabel);
	if (hp.cth_parname != 0)
		fp->ctf_parname = ctf_strptr(fp, hp.cth_parname);

	ctf_dprintf("ctf_bufopen: parent name %s (label %s)\n",
	    fp->ctf_parname ? fp->ctf_parname : "<NULL>",
	    fp->ctf_parlabel ? fp->ctf_parlabel : "<NULL>");

	/*
	 * If we have a symbol table section, allocate and initialize
	 * the symtab translation table, pointed to by ctf_sxlate.
	 */
	if (symsect != NULL) {
		fp->ctf_nsyms = symsect->cts_size / symsect->cts_entsize;
		fp->ctf_sxlate = ctf_alloc(fp->ctf_nsyms * sizeof (uint_t));

		if (fp->ctf_sxlate == NULL) {
			(void) ctf_set_open_errno(errp, EAGAIN);
			goto bad;
		}

		if ((err = init_symtab(fp, &hp, symsect, strsect)) != 0) {
			(void) ctf_set_open_errno(errp, err);
			goto bad;
		}
	}

	if ((err = init_types(fp, &hp)) != 0) {
		(void) ctf_set_open_errno(errp, err);
		goto bad;
	}

	/*
	 * Initialize the ctf_lookup_by_name top-level dictionary.  We keep an
	 * array of type name prefixes and the corresponding ctf_hash to use.
	 * NOTE: This code must be kept in sync with the code in ctf_update().
	 */
	fp->ctf_lookups[0].ctl_prefix = "struct";
	fp->ctf_lookups[0].ctl_len = strlen(fp->ctf_lookups[0].ctl_prefix);
	fp->ctf_lookups[0].ctl_hash = &fp->ctf_structs;
	fp->ctf_lookups[1].ctl_prefix = "union";
	fp->ctf_lookups[1].ctl_len = strlen(fp->ctf_lookups[1].ctl_prefix);
	fp->ctf_lookups[1].ctl_hash = &fp->ctf_unions;
	fp->ctf_lookups[2].ctl_prefix = "enum";
	fp->ctf_lookups[2].ctl_len = strlen(fp->ctf_lookups[2].ctl_prefix);
	fp->ctf_lookups[2].ctl_hash = &fp->ctf_enums;
	fp->ctf_lookups[3].ctl_prefix = _CTF_NULLSTR;
	fp->ctf_lookups[3].ctl_len = strlen(fp->ctf_lookups[3].ctl_prefix);
	fp->ctf_lookups[3].ctl_hash = &fp->ctf_names;
	fp->ctf_lookups[4].ctl_prefix = NULL;
	fp->ctf_lookups[4].ctl_len = 0;
	fp->ctf_lookups[4].ctl_hash = NULL;

	if (symsect != NULL) {
		if (symsect->cts_entsize == sizeof (Elf64_Sym))
			(void) ctf_setmodel(fp, CTF_MODEL_LP64);
		else
			(void) ctf_setmodel(fp, CTF_MODEL_ILP32);
	} else
		(void) ctf_setmodel(fp, CTF_MODEL_NATIVE);

	fp->ctf_refcnt = 1;
	return (fp);

bad:
	ctf_close(fp);
	return (NULL);
}
const u8 * NetReceiver::UncompressData()
{
	if(!filebuffer)
		return NULL;

	//Zip File
	if (filebuffer[0] == 'P' && filebuffer[1] == 'K' && filebuffer[2] == 0x03 && filebuffer[3] == 0x04)
	{
		char temppath[200];
		char tempfilepath[200];
		snprintf(temppath, sizeof(temppath), "%s/WiiXplorerTmp/", Settings.BootDevice);
		snprintf(tempfilepath, sizeof(tempfilepath), "%s/WiiXplorerTmp/tmp.zip", Settings.BootDevice);

		if(!CreateSubfolder(temppath))
		{
			FreeData();
			return NULL;
		}

		FILE * file = fopen(tempfilepath, "wb");
		if(!file)
		{
			FreeData();
			RemoveDirectory(temppath);
			return NULL;
		}

		fwrite(filebuffer, 1, filesize, file);
		fclose(file);

		FreeData();

		ArchiveHandle * Zip = new ArchiveHandle(tempfilepath);
		if(!Zip->ExtractAll(temppath))
		{
			delete Zip;
			RemoveDirectory(temppath);
			return NULL;
		}

		delete Zip;

		DirList Dir(temppath, ".dol,.elf");
		if(Dir.GetFilecount() <= 0)
		{
			RemoveDirectory(temppath);
			ShowError(tr("No homebrew in the zip."));
			return NULL;
		}

		char newfilepath[300];
		snprintf(newfilepath, sizeof(newfilepath), "%s", Dir.GetFilepath(0));
		snprintf(FileName, sizeof(FileName), "%s", Dir.GetFilename(0));

		u8 * buffer = NULL;
		u32 newfilesize = 0;

		if(LoadFileToMem(newfilepath, &buffer, &newfilesize) < 0)
		{
			RemoveDirectory(temppath);
			return NULL;
		}

		RemoveDirectory(temppath);
		filesize = newfilesize;
		filebuffer = buffer;
	}

	//WiiLoad zlib compression
	else if((wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) && uncfilesize != 0)
	{
		u8 * unc = (u8 *) malloc(uncfilesize);
		if(!unc)
		{
			FreeData();
			return NULL;
		}

		uLongf f = uncfilesize;
		if(uncompress(unc, &f, filebuffer, filesize) != Z_OK)
		{
			free(unc);
			FreeData();
			return NULL;
		}

		free(filebuffer);

		filebuffer = unc;
		filesize = f;
	}

	return filebuffer;
}
Example #11
0
// Flip all bits in compressed buffer and bit flip each new uncompressed version
bitsaver_t bs_check_bits_compressed(struct bitsaver* bs, int bits)
{

    struct bitsaver_mask* bm_inflate = bs_mask_init(bits);

    // Check without any flips
    size_t len = bs->inflated_max_size;
    int i,j;

    bs->inflated_size = bs->inflated_max_size;

    printf("Checking the uncompressed version\n");
    int ec;
    while(ec=(uncompress(bs->inflated, &bs->inflated_size, bs->data, bs->data_size)) == Z_BUF_ERROR)
    {
        free(bs->inflated);
        bs->inflated_max_size *= 0x10;
        if (bs->inflated_max_size > MAX_MEM_SIZE)
        {
            errx(1,"decompressing file exceeded %zd bytes.\n",MAX_MEM_SIZE);
        }
        bs->inflated = malloc(bs->inflated_max_size);
        if(bs->inflated == NULL)
        {
            err(1,"malloc");
        }
        bs->inflated_size = bs->inflated_max_size;
    }
    if( ec == Z_OK )
    {
        if (bs_check_bits_inflate(bs, bm_inflate) == BS_SUCCESS)
        {
            return BS_SUCCESS;
        }
    }


    printf("Checking the compressed version\n");
    struct bitsaver_mask* bm = bs_mask_init(bits);
    bs_mask_set_max(bm, bs->data_size*8);
    for(bs_mask_clear(bm); !bm->done; bs_mask_inc(bm))
    {
        BITFLIP(bs->data, bm);

        bs->inflated_size = bs->inflated_max_size;

        if( uncompress(bs->inflated, &bs->inflated_size, bs->data, bs->data_size) == Z_OK )
        {
            if (bs_check_bits_inflate(bs,bm_inflate) == BS_SUCCESS)
            {
                return BS_SUCCESS;
            }

        }

        BITFLIP(bs->data, bm);
    
    }

    bs_mask_destroy(bm);
    bs_mask_destroy(bm_inflate);

    return BS_FAIL;
}
bool AddonHandler::BuildAddonPacket(WorldPacket* Source, WorldPacket* Target)
{
    ByteBuffer AddOnPacked;
    uLongf AddonRealSize;
    uint32 CurrentPosition;
    uint32 TempValue;

    // broken addon packet, can't be received from real client
    if (Source->rpos() + 4 > Source->size())
        return false;

    *Source >> TempValue;                                   // get real size of the packed structure

    // empty addon packet, nothing process, can't be received from real client
    if (!TempValue)
        return false;

    AddonRealSize = TempValue;                              // temp value because ZLIB only excepts uLongf

    CurrentPosition = Source->rpos();                       // get the position of the pointer in the structure

    AddOnPacked.resize(AddonRealSize);                      // resize target for zlib action

    if (uncompress(const_cast<uint8*>(AddOnPacked.contents()), &AddonRealSize, const_cast<uint8*>((*Source).contents() + CurrentPosition), (*Source).size() - CurrentPosition)== Z_OK)
    {
        Target->Initialize(SMSG_ADDON_INFO);

        uint32 addonsCount;
        AddOnPacked >> addonsCount;                         // addons count?

        for (uint32 i = 0; i < addonsCount; ++i)
        {
            std::string addonName;
            uint8 enabled;
            uint32 crc, unk2;

            // check next addon data format correctness
            if (AddOnPacked.rpos()+1 > AddOnPacked.size())
                return false;

            AddOnPacked >> addonName;

            // recheck next addon data format correctness
            if (AddOnPacked.rpos()+1+4+4 > AddOnPacked.size())
                return false;

            AddOnPacked >> enabled >> crc >> unk2;

#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
            sLog->outDebug(LOG_FILTER_NETWORKIO, "ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk2);
#endif

            uint8 state = (enabled ? 2 : 1);
            *Target << uint8(state);

            uint8 unk1 = (enabled ? 1 : 0);
            *Target << uint8(unk1);
            if (unk1)
            {
                uint8 unk = (crc != 0x4c1c776d);           // If addon is Standard addon CRC
                *Target << uint8(unk);
                if (unk)
                {
                    unsigned char tdata[256] =
                    {
                        0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
                        0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
                        0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
                        0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
                        0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
                        0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
                        0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
                        0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
                        0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
                        0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
                        0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
                        0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
                        0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
                        0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
                        0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
                        0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
                    };
                    Target->append(tdata, sizeof(tdata));
                }

                *Target << uint32(0);
            }

            uint8 unk3 = (enabled ? 0 : 1);
            *Target << uint8(unk3);
            if (unk3)
            {
                // String, 256 (null terminated?)
                *Target << uint8(0);
            }
        }

        uint32 unk4;
        AddOnPacked >> unk4;

        uint32 count = 0;
        *Target << uint32(count);

#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
        if (AddOnPacked.rpos() != AddOnPacked.size())
            sLog->outDebug(LOG_FILTER_NETWORKIO, "packet under read!");
#endif
    }
Example #13
0
void _comprimir(int encode, char *fichero) {

	unsigned long size,size2;
	byte *ptr,*ptr_dest;
	FILE *f;

	if ((f=fopen(fichero,"rb"))!=NULL) {
		fseek(f,0,SEEK_END); 
		size=ftell(f);
	
		if ((ptr=(byte *)malloc(size))!=NULL) {
			fseek(f,0,SEEK_SET);
		
			if(fread(ptr,1,size,f) == size) {
				fclose(f);
			} else { 
				fclose(f); 
				e_free(ptr); 
				return; 
			}
		} else { 
			fclose(f);
			return; 
		}
	} else 
		return;

	if (encode) {
		if (!strcmp(ptr,"zx!\x1a\x0d\x0a\xff")) 
			return;
		size2=size+size/100+256;
		
		if ((ptr_dest=(byte *)malloc(size2))==NULL) {
			e_free(ptr);
			return;
		}
		
		if (compress(ptr_dest, &size2, ptr, size)) {
			e_free(ptr_dest);
			e_free(ptr);
			return;
		}

		/* Si no se gana espacio, se deja el fichero sin comprimir */
		if (size2>=size-12) { 
			e_free(ptr_dest); 
			e_free(ptr); 
			return; 
		}
	} else {
		if (strcmp(ptr,"zx!\x1a\x0d\x0a\xff")) 
			return;
		
		size2=*(int*)(ptr+8);
		
		if ((ptr_dest=(byte *)malloc(size2))==NULL) {
			e_free(ptr);
			return;
		}
		
		if (uncompress(ptr_dest, &size2, ptr+12, size-12)) {
			e_free(ptr_dest);
			e_free(ptr);
			return;
		}
		
		size2=*(int*)(ptr+8);
	}

	e_free(ptr);

	if (rename(fichero,"temp.ZX!")) {
		e_free(ptr_dest);
		return;
	}

	if ((f=fopen(fichero,"wb"))==NULL) {
		rename("temp.ZX!",fichero); 
		e_free(ptr_dest); 
		return;
  }

  
	if (encode) {
	  if(fwrite("zx!\x1a\x0d\x0a\xff",1,8,f)!=8) {
		  fclose(f);
		  remove(fichero);
		  rename("temp.ZX!",fichero);
		  e_free(ptr_dest); 
		  return;
	  }
	  
	  if(fwrite(&size,1,4,f)!=4) {
		  fclose(f);
		  remove(fichero);
		  rename("temp.ZX!",fichero);
		  e_free(ptr_dest);
		  return;
	  }
	}

	if(fwrite(ptr_dest,1,size2,f)!=size2) {
		fclose(f);
		remove(fichero);
		rename("temp.ZX!",fichero);
		e_free(ptr_dest);
		return;
	}

  /* Si todo ha ido bien ... */
	fclose(f);
	e_free(ptr_dest);
	remove("temp.ZX!");
}
Example #14
0
void POVMS_Object::Read(InputStream& stream, bool continued, bool headeronly)
{
    POVMSStream headerstream[16];
    POVMSStream *objectstream = NULL;
    POVMSStream *compressedstream = NULL;
    int err = pov_base::kNoErr;
    int maxheadersize = 0;
    int datasize = 0;

    try
    {
        err = POVMSObject_Delete(&data);
        if(err != pov_base::kNoErr)
            throw POV_EXCEPTION_CODE(err);

        if(continued == false)
        {
            char header[8];
            POVMSInt version = 0;

            if(!stream.read((void *)headerstream, 12))
                throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

            datasize = 0;
            maxheadersize = 12; // header

            datasize += POVMSStream_ReadString(header, headerstream + datasize, 8, &maxheadersize);                // header       8 byte
            if(!((header[0] == 'P') && (header[1] == 'O') && (header[2] == 'V') && (header[3] == 'R') &&
                 (header[4] == 'A') && (header[5] == 'Y') && (header[6] == 'M') && (header[7] == 'S')))
                throw POV_EXCEPTION_CODE(pov_base::kVersionErr);

            datasize += POVMSStream_ReadInt(&version, headerstream + datasize, &maxheadersize);                    // version      4 byte
            if(version != 0x0370)
                throw POV_EXCEPTION_CODE(pov_base::kVersionErr);
        }

        if(headeronly == false)
        {
            POVMSInt objectsize = 0;
            POVMSType encoding = kPOVMSRawStreamEncoding;

            if(!stream.read((void *)headerstream, 8))
                throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

            datasize = 0;
            maxheadersize = 8; // header

            datasize += POVMSStream_ReadInt(&objectsize, headerstream + datasize, &maxheadersize);                 // data size    4 byte
            if(objectsize == 0)
                throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

            datasize += POVMSStream_ReadType(&encoding, headerstream + datasize, &maxheadersize);                  // encoding     4 byte
            if(encoding == kPOVMSRawStreamEncoding)
            {
                objectstream = new POVMSStream[objectsize];

                if(!stream.read((void *)objectstream, objectsize))                                                 // object       x byte
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

                if(POVMSStream_Read(&data, objectstream, &objectsize) == 0)
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);
            }
            else if(encoding == kPOVMSGZipStreamEncoding)
            {
                int compressedsize = objectsize;

                datasize = 0;
                maxheadersize = 4; // header

                if(!stream.read((void *)headerstream, 4))
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

                datasize += POVMSStream_ReadInt(&objectsize, headerstream + datasize, &maxheadersize);             // object size  4 byte
                if(objectsize == 0)
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

                compressedstream = new POVMSStream[compressedsize];
                objectstream = new POVMSStream[objectsize];

                if(!stream.read((void *)compressedstream, compressedsize))                                         // data         x byte
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);

                // uncompress stream data
                uLongf destlen = (uLongf)objectsize;
                if(uncompress((Bytef *)(objectstream), &destlen, (Bytef *)(compressedstream), (uLongf)(compressedsize)) != Z_OK)
                    throw POV_EXCEPTION_CODE(pov_base::kCannotHandleDataErr);

                if(POVMSStream_Read(&data, objectstream, &objectsize) == 0)
                    throw POV_EXCEPTION_CODE(pov_base::kFileDataErr);
            }
            else
                throw POV_EXCEPTION_CODE(pov_base::kCannotHandleDataErr);
        }

        if(objectstream != NULL)
            delete[] objectstream;
        objectstream = NULL;

        if(compressedstream != NULL)
            delete[] compressedstream;
        compressedstream = NULL;
    }
    catch(...)
    {
        if(objectstream != NULL)
            delete[] objectstream;

        if(compressedstream != NULL)
            delete[] compressedstream;

        throw;
    }
}
Example #15
0
void
db_putprop(FILE * f, const char *dir, PropPtr p)
{
    char buf[BUFFER_LEN * 2];
    char fbuf[BUFFER_LEN];
    char num[16];
    char *ptr;
    const char *ptr2;


    if (PropType(p) == PROP_DIRTYP)
        return;

    for (ptr = buf, ptr2 = dir + 1; *ptr2;)
        *ptr++ = *ptr2++;
    for (ptr2 = PropName(p); *ptr2;)
        *ptr++ = *ptr2++;
    *ptr++ = PROP_DELIMITER;

    ptr2 = intostr(num, PropFlagsRaw(p) & ~(PROP_TOUCHED | PROP_ISUNLOADED));
    while (*ptr2)
        *ptr++ = *ptr2++;
    *ptr++ = PROP_DELIMITER;

    ptr2 = "";
    switch (PropType(p)) {
        case PROP_INTTYP:
            if (!PropDataVal(p))
                return;
            ptr2 = intostr(num, PropDataVal(p));
            break;
        case PROP_FLTTYP:
            if (!PropDataFVal(p))
                return;
            ptr2 = fltostr(fbuf, PropDataFVal(p));
            break;
        case PROP_REFTYP:
            if (PropDataRef(p) == NOTHING)
                return;
            ptr2 = intostr(num, (int) PropDataRef(p));
            break;
        case PROP_STRTYP:
            if (!*PropDataStr(p))
                return;
            if (db_decompression_flag) {
#ifdef COMPRESS
                ptr2 = uncompress(PropDataStr(p));
#else
                ptr2 = PropDataStr(p);
#endif
            } else {
                ptr2 = PropDataStr(p);
            }
            break;
        case PROP_LOKTYP:
            if (PropFlags(p) & PROP_ISUNLOADED)
                return;
            if (PropDataLok(p) == TRUE_BOOLEXP)
                return;
            ptr2 = unparse_boolexp((dbref) 1, PropDataLok(p), 0);
            break;
    }
    while (*ptr2)
        if (*ptr2 != '\n')
            *ptr++ = *ptr2++;
        else {
            *ptr++ = '\\';
            *ptr++ = 'n';
            ptr2++;
        }
    *ptr++ = '\n';
    *ptr++ = '\0';
    if (fputs(buf, f) == EOF) {
        fprintf(stderr, "PANIC: Unable to write to db to write prop.\n");
        abort();
    }
}
Example #16
0
/** \fn DSMCCCacheModuleData::AddModuleData(DsmccDb*,const unsigned char*)
 *  \brief Add block to the module and create the module if it's now complete.
 *  \return data for the module if it is complete, NULL otherwise.
 */
unsigned char *DSMCCCacheModuleData::AddModuleData(DsmccDb *ddb,
                                                   const unsigned char *data)
{
    if (m_version != ddb->module_version)
        return NULL; // Wrong version

    if (m_completed)
        return NULL; // Already got it.

    // Check if we have this block already or not. If not append to list
    LOG(VB_DSMCC, LOG_INFO,
        QString("[dsmcc] Module %1 block number %2 length %3")
            .arg(ddb->module_id).arg(ddb->block_number).arg(ddb->len));

    if (ddb->block_number >= m_blocks.size())
    {
        LOG(VB_DSMCC, LOG_ERR,
            QString("[dsmcc] Module %1 block number %2 is larger than %3")
                .arg(ddb->module_id).arg(ddb->block_number)
                .arg(m_blocks.size()));

        return NULL;
    }

    if (m_blocks[ddb->block_number] == NULL)
    {   // We haven't seen this block before.
        QByteArray *block = new QByteArray((char*) data, ddb->len);
        // Add this to our set of blocks.
        m_blocks[ddb->block_number] = block;
        m_receivedData += ddb->len;
    }

    LOG(VB_DSMCC, LOG_INFO,
        QString("[dsmcc] Module %1 Current Size %2 Total Size %3")
            .arg(m_module_id).arg(m_receivedData).arg(m_moduleSize));

    if (m_receivedData < m_moduleSize)
        return NULL; // Not yet complete

    LOG(VB_DSMCC, LOG_INFO,
        QString("[dsmcc] Reconstructing module %1 from blocks")
            .arg(m_module_id));

    // Re-assemble the blocks into the complete module.
    unsigned char *tmp_data = (unsigned char*) malloc(m_receivedData);
    if (tmp_data == NULL)
        return NULL;

    uint curp = 0;
    for (uint i = 0; i < m_blocks.size(); i++)
    {
        QByteArray *block = m_blocks[i];
        uint size = block->size();
        memcpy(tmp_data + curp, block->data(), size);
        curp += size;
        delete block;
    }
    m_blocks.clear(); // No longer required: free the space.

    /* Uncompress....  */
    if (m_descriptorData.isCompressed)
    {
        unsigned long dataLen = m_descriptorData.originalSize + 1;
        LOG(VB_DSMCC, LOG_INFO,
            QString("[dsmcc] uncompressing: compressed size %1, final size %2")
                .arg(m_moduleSize).arg(dataLen));

        unsigned char *uncompressed = (unsigned char*) malloc(dataLen + 1);
        int ret = uncompress(uncompressed, &dataLen, tmp_data, m_moduleSize);
        if (ret != Z_OK)
        {
            LOG(VB_DSMCC, LOG_ERR, "[dsmcc] compression error, skipping");
            free(tmp_data);
            free(uncompressed);
            return NULL;
        }

        free(tmp_data);
        m_completed = true;
        return uncompressed;
    }
    else
    {
        m_completed = true;
        return tmp_data;
    }
}
Example #17
0
void
reflist_del(dbref obj, const char *propname, dbref todel)
{
    PropPtr ptr;
    const char *temp;
    const char *list;
    int count = 0;
    int charcount = 0;
    char buf[BUFFER_LEN];
    char outbuf[BUFFER_LEN];

    ptr = get_property(obj, propname);
    if (ptr) {
        const char *pat = NULL;

#ifdef DISKBASE
        propfetch(obj, ptr);
#endif
        switch (PropType(ptr)) {
            case PROP_STRTYP:
                *outbuf = '\0';
                list = temp = uncompress(PropDataStr(ptr));
                sprintf(buf, "%d", todel);
                while (*temp) {
                    if (*temp == '#') {
                        pat = buf;
                        count++;
                        charcount = temp - list;
                    } else if (pat) {
                        if (!*pat) {
                            if (!*temp || *temp == ' ') {
                                break;
                            }
                            pat = NULL;
                        } else if (*pat != *temp) {
                            pat = NULL;
                        } else {
                            pat++;
                        }
                    }
                    temp++;
                }
                if (pat && !*pat) {
                    if (charcount > 0) {
                        strncpy(outbuf, list, charcount - 1);
                        outbuf[charcount - 1] = '\0';
                    }
                    strcat(outbuf, temp);
                    for (temp = outbuf; isspace(*temp); temp++) ;
                    add_property(obj, propname, temp, 0);
                }
                break;
            case PROP_REFTYP:
                if (PropDataRef(ptr) == todel) {
                    add_property(obj, propname, "", 0);
                }
                break;
            default:
                break;
        }
    }
}
int 
carmen_navigator_get_map(carmen_navigator_map_t map_type, 
			 carmen_map_t *map) 
{
  IPC_RETURN_TYPE err;
  carmen_navigator_map_request_message msg;
  carmen_navigator_map_message *response = NULL;
  int index;

#ifndef NO_ZLIB
  int uncompress_return;
  int uncompress_size;
  uLongf uncompress_size_result;
  unsigned char *uncompressed_data;
#endif

  static int initialized = 0;

  if (!initialized) 
    {
      err = IPC_defineMsg(CARMEN_NAVIGATOR_MAP_REQUEST_NAME, 
			  IPC_VARIABLE_LENGTH, 
			  CARMEN_NAVIGATOR_MAP_REQUEST_FMT);
      carmen_test_ipc_exit(err, "Could not define message", 
			   CARMEN_NAVIGATOR_MAP_REQUEST_NAME);
      initialized = 1;
    }

  msg.map_type = map_type;
  msg.timestamp = carmen_get_time();
  msg.host = carmen_get_host();

  err = IPC_queryResponseData(CARMEN_NAVIGATOR_MAP_REQUEST_NAME, &msg, 
			      (void **)&response, timeout);
  carmen_test_ipc(err, "Could not get map", CARMEN_NAVIGATOR_MAP_REQUEST_NAME);

#ifndef NO_ZLIB
  if (response && response->compressed) 
    {
      uncompress_size = response->config.x_size*
	response->config.y_size;
      uncompressed_data = (unsigned char *)
	calloc(uncompress_size, sizeof(float));
      carmen_test_alloc(uncompressed_data);
      uncompress_size_result = uncompress_size*sizeof(float);
      uncompress_return = uncompress((void *)uncompressed_data,   
				     &uncompress_size_result,
				     (void *)response->data, 
				     response->size);
      response->data = uncompressed_data;
      response->size = uncompress_size_result;
    }
#else
  if (response && response->compressed) 
    {
      carmen_warn("Received compressed map from server. This program was\n"
		  "compiled without zlib support, so this map cannot be\n"
		  "used. Sorry.\n");
      free(response->data);
      free(response);
      response = NULL;
    }
#endif

  if (response)
    {
      if (map)
	{
	  map->config = response->config;
	  map->complete_map = (float *)response->data;
	  map->map = (float **)calloc(map->config.x_size, sizeof(float*));
	  carmen_test_alloc(map->map);
	  
	  for (index = 0; index < map->config.x_size; index++)
	    map->map[index] = map->complete_map+index*map->config.y_size;
	}
      else
	free(response->data);
      free(response);
    } 

  return 0;
}
Example #19
0
int main(void)
{
	REQUEST_HD hd;
	RESPONSE_HD rd;
	REQUEST_CCTV hdc;

	int i, rlen, wlen, len;
	struct sockaddr_in serv_addr;
	int ret, ret_size = 0;

	char *info = NULL;
	char *data = NULL;

	char filename[256];

	FILE *fp;

	char *fdata = NULL;
	short fnum = 0;
	short fclass = 0;
	int fsize = 0;
	long uncompsize = 0;
	char data_time[12+1];
	char f_h;


	memset(&hd, 0x00, sizeof(hd));
	memset(&hdc, 0x00, sizeof(hdc));
	memset(&rd, 0x00, sizeof(rd));

	hd.version = htonl(100);
	hd.serviceid = htonl(1000);
	printf("--------IN------\n");
	InputChar("D or E", &hdc.sourceFlag, 'D');
	InputInt("Camera(CCTV) ID", &hdc.cameraID, 99);
	hdc.cameraID = htonl(hdc.cameraID);
	InputShort("¸îÀå?", &hdc.photoNum, 5);
	hdc.photoNum = htons(hdc.photoNum);

	memset((char *) &serv_addr, 0, sizeof(serv_addr)) ;
	serv_addr.sin_family = AF_INET ;
	serv_addr.sin_addr.s_addr = inet_addr(SM_SERVER_IP) ;
	serv_addr.sin_port = htons(SM_SERVER_PORT) ;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("clientsoc: can't open stream socket") ;
		close(sockfd), exit(0);
	}

	if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		printf("clientsoc: can't connect to server") ;
		close(sockfd), exit(0);
	}

	if ((wlen = write(sockfd, &hd, sizeof(hd))) <= 0) {
		printf("ERR: IN(wlen:%d)\n", wlen);
		close(sockfd), exit(1);
	}
	printf("SEND: IN[wlen:%d]\n", wlen);
	if ((wlen = write(sockfd, &hdc, sizeof(hdc))) <= 0) {
		printf("ERR: IN(wlen:%d)\n", wlen);
		close(sockfd), exit(1);
	}
	printf("SEND: IN[wlen:%d]\n", wlen);

	if ((rlen = read(sockfd, &rd, sizeof(rd))) <= 0) {
		printf("ERR: OUT(rlen:%d)\n", rlen);
		close(sockfd), exit(1);
	}
	printf("RECEIVE: OUT[rlen:%d]\n", rlen);

	rd.error_code = ntohl(rd.error_code);
	rd.version = ntohl(rd.version);
	rd.serviceid = ntohl(rd.serviceid);
	rd.file_num = ntohl(rd.file_num);
	rd.comp_flag = ntohl(rd.comp_flag);
	rd.uncomp_size = ntohl(rd.uncomp_size);
	rd.comp_size = ntohl(rd.comp_size);

	printf("ECODE[%d] VER[%d] SID[%d] FNUM[%d] CFLAG[%d] UNC_SIZE[%d] C_SIZE[%d]\n", rd.error_code, rd.version, rd.serviceid, rd.file_num, rd.comp_flag, rd.uncomp_size, rd.comp_size);

	if (rd.error_code == 0) {
		if (rd.comp_flag == 0) ret_size = rd.uncomp_size;
		else ret_size = rd.comp_size;

		if ((info = (char *)malloc(rd.uncomp_size)) == NULL) {
			printf("ERR: Memory Alloc Fail\n");
			close(sockfd), exit(1);
		}
		memset(info, 0, rd.uncomp_size);

		if ((rlen = readn(sockfd, info, ret_size)) <= 0) {
			printf("ERR: read info[rlen:%d/%d]\n", rlen, ret_size);
			close(sockfd), exit(1);
		}
		printf("READ: DATA[rlen:%d]\n", rlen);

		if (rd.comp_flag == 1) {
			if ((data = (char *) malloc(rd.uncomp_size)) == NULL) {
				printf("........Fail\n");
				close(sockfd), exit(1);
			}
			memset(data, 0, rd.uncomp_size);
			memcpy(data, info, rd.uncomp_size);
			memset(info, 0, rd.uncomp_size);
			
			uncompsize = rd.uncomp_size;
			ret = uncompress(info, &(uncompsize), data, rd.comp_size);

			rd.uncomp_size = uncompsize;

			printf("uncompress() ret[%d], un[%d], c[%d]\n", ret, rd.uncomp_size, rd.comp_size);
		}

		memset(data_time, 0x00, sizeof(data_time));
		len = 0;
		memcpy(&fnum, info+len, sizeof(short));
		len += sizeof(short);
		memcpy(&fclass, info+len, sizeof(short));
		len += sizeof(short);
		memcpy(data_time, info+len, 12);
		len += 12;

		fnum = ntohs(fnum);
		fclass = ntohs(fclass);

		printf("---- FILE_COUNT(%d) FCLASS(%d) TIME(%s)\n", fnum, fclass, data_time);

		for (i = 0; i < fnum; i++) {
			memcpy(&f_h, info+len, sizeof(char));
			len += sizeof(char);
			if (f_h != 'T') {
				printf("-------------ERROR!!!(%c)\n", f_h);
				exit(-1);
			}
			memcpy(&f_h, info+len, sizeof(char));
			len += sizeof(char);
			if (f_h != 'W') {
				printf("-------------ERROR!!!(%c)\n", f_h);
				exit(-1);
			}
			
			memset(filename, 0x00, sizeof(filename));
			memcpy(&fsize, info+len, sizeof(int));
			len += sizeof(int);
			fsize = ntohl(fsize);

			fdata = (char *)malloc(fsize);
			memset(fdata, 0x00, fsize);
			memcpy(fdata, info+len, fsize);
			len += fsize;

			sprintf(filename, "cctv%d.jpg", i+1);
			fp = fopen(filename, "wb");
			fwrite(fdata, fsize, 1, fp);
			fclose(fp);
			printf("Write Complete! ---- [%s](%d) (len:%d)\n", filename, fsize, len);
			free(fdata);
		}

		if (info != NULL) free(info);
		info = NULL;
		if (data != NULL) free(data);
		data = NULL;
	}
	exit_handler();
}
bool convertWOFFToSfnt(SharedBuffer* woff, Vector<char>& sfnt)
{
    ASSERT_ARG(sfnt, sfnt.isEmpty());

    size_t offset = 0;

    // Read the WOFF header.
    uint32_t signature;
    if (!readUInt32(woff, offset, signature) || signature != woffSignature) {
        ASSERT_NOT_REACHED();
        return false;
    }

    uint32_t flavor;
    if (!readUInt32(woff, offset, flavor))
        return false;

    uint32_t length;
    if (!readUInt32(woff, offset, length) || length != woff->size())
        return false;

    uint16_t numTables;
    if (!readUInt16(woff, offset, numTables))
        return false;

    if (!numTables || numTables > 0x0fff)
        return false;

    uint16_t reserved;
    if (!readUInt16(woff, offset, reserved) || reserved)
        return false;

    uint32_t totalSfntSize;
    if (!readUInt32(woff, offset, totalSfntSize))
        return false;

    if (woff->size() - offset < sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t))
        return false;

    offset += sizeof(uint16_t); // majorVersion
    offset += sizeof(uint16_t); // minorVersion
    offset += sizeof(uint32_t); // metaOffset
    offset += sizeof(uint32_t); // metaLength
    offset += sizeof(uint32_t); // metaOrigLength
    offset += sizeof(uint32_t); // privOffset
    offset += sizeof(uint32_t); // privLength

    // Check if the WOFF can supply as many tables as it claims it has.
    if (woff->size() - offset < numTables * 5 * sizeof(uint32_t))
        return false;

    // Write the sfnt offset subtable.
    uint16_t entrySelector = 0;
    uint16_t searchRange = 1;
    while (searchRange < numTables >> 1) {
        entrySelector++;
        searchRange <<= 1;
    }
    searchRange <<= 4;
    uint16_t rangeShift = (numTables << 4) - searchRange;

    if (!writeUInt32(sfnt, flavor)
        || !writeUInt16(sfnt, numTables)
        || !writeUInt16(sfnt, searchRange)
        || !writeUInt16(sfnt, entrySelector)
        || !writeUInt16(sfnt, rangeShift))
        return false;

    if (sfnt.size() > totalSfntSize)
        return false;

    if (totalSfntSize - sfnt.size() < numTables * 4 * sizeof(uint32_t))
        return false;

    size_t sfntTableDirectoryCursor = sfnt.size();
    sfnt.grow(sfnt.size() + numTables * 4 * sizeof(uint32_t));

    // Process tables.
    for (uint16_t i = 0; i < numTables; ++i) {
        // Read a WOFF table directory entry.
        uint32_t tableTag;
        if (!readUInt32(woff, offset, tableTag))
            return false;

        uint32_t tableOffset;
        if (!readUInt32(woff, offset, tableOffset))
            return false;

        uint32_t tableCompLength;
        if (!readUInt32(woff, offset, tableCompLength))
            return false;

        if (tableOffset > woff->size() || tableCompLength > woff->size() - tableOffset)
            return false;

        uint32_t tableOrigLength;
        if (!readUInt32(woff, offset, tableOrigLength) || tableCompLength > tableOrigLength)
            return false;

        if (tableOrigLength > totalSfntSize || sfnt.size() > totalSfntSize - tableOrigLength)
            return false;

        uint32_t tableOrigChecksum;
        if (!readUInt32(woff, offset, tableOrigChecksum))
            return false;

        // Write an sfnt table directory entry.
        uint32_t* sfntTableDirectoryPtr = reinterpret_cast<uint32_t*>(sfnt.data() + sfntTableDirectoryCursor);
        *sfntTableDirectoryPtr++ = htonl(tableTag);
        *sfntTableDirectoryPtr++ = htonl(tableOrigChecksum);
        *sfntTableDirectoryPtr++ = htonl(sfnt.size());
        *sfntTableDirectoryPtr++ = htonl(tableOrigLength);
        sfntTableDirectoryCursor += 4 * sizeof(uint32_t);

        if (tableCompLength == tableOrigLength) {
            // The table is not compressed.
            if (!sfnt.tryAppend(woff->data() + tableOffset, tableCompLength))
                return false;
        } else {
            uLongf destLen = tableOrigLength;
            if (!sfnt.tryReserveCapacity(sfnt.size() + tableOrigLength))
                return false;
            Bytef* dest = reinterpret_cast<Bytef*>(sfnt.end());
            sfnt.grow(sfnt.size() + tableOrigLength);
            if (uncompress(dest, &destLen, reinterpret_cast<const Bytef*>(woff->data() + tableOffset), tableCompLength) != Z_OK)
                return false;
            if (destLen != tableOrigLength)
                return false;
        }

        // Pad to a multiple of 4 bytes.
        while (sfnt.size() % 4)
            sfnt.append(0);
    }

    return sfnt.size() == totalSfntSize;
}
Example #21
0
gboolean
id3demux_id3v2_parse_frame (ID3TagsWorking * work)
{
  const gchar *tag_name;
  gboolean result = FALSE;
  gint i;
  guint8 *frame_data = work->hdr.frame_data;
  guint frame_data_size = work->cur_frame_size;
  gchar *tag_str = NULL;
  GArray *tag_fields = NULL;
  guint8 *uu_data = NULL;

#ifdef HAVE_ZLIB
  guint8 *uncompressed_data = NULL;
#endif

  /* Check that the frame id is valid */
  for (i = 0; i < 5 && work->frame_id[i] != '\0'; i++) {
    if (!g_ascii_isalnum (work->frame_id[i])) {
      GST_DEBUG ("Encountered invalid frame_id");
      return FALSE;
    }
  }

  /* Can't handle encrypted frames right now (in case we ever do, we'll have
   * to do the decryption after the un-unsynchronisation and decompression,
   * not here) */
  if (work->frame_flags & ID3V2_FRAME_FORMAT_ENCRYPTION) {
    GST_WARNING ("Encrypted frames are not supported");
    return FALSE;
  }

  tag_name = gst_tag_from_id3_tag (work->frame_id);
  if (tag_name == NULL &&
      strncmp (work->frame_id, "RVA2", 4) != 0 &&
      strncmp (work->frame_id, "TXXX", 4) != 0 &&
      strncmp (work->frame_id, "TDAT", 4) != 0 &&
      strncmp (work->frame_id, "UFID", 4) != 0) {
    return FALSE;
  }

  if (work->frame_flags & (ID3V2_FRAME_FORMAT_COMPRESSION |
          ID3V2_FRAME_FORMAT_DATA_LENGTH_INDICATOR)) {
    if (work->hdr.frame_data_size <= 4)
      return FALSE;
    if (ID3V2_VER_MAJOR (work->hdr.version) == 3) {
      work->parse_size = GST_READ_UINT32_BE (frame_data);
    } else {
      work->parse_size = read_synch_uint (frame_data, 4);
    }
    frame_data += 4;
    frame_data_size -= 4;
    GST_LOG ("Un-unsynced data size %d (of %d)", work->parse_size,
        frame_data_size);
    if (work->parse_size > frame_data_size) {
      GST_WARNING ("ID3v2 frame %s data has invalid size %d (>%d)",
          work->frame_id, work->parse_size, frame_data_size);
      return FALSE;
    }
  }

  /* in v2.3 the frame sizes are not syncsafe, so the entire tag had to be
   * unsynced. In v2.4 the frame sizes are syncsafe so it's just the frame
   * data that needs un-unsyncing, but not the frame headers. */
  if (ID3V2_VER_MAJOR (work->hdr.version) == 4) {
    if ((work->hdr.flags & ID3V2_HDR_FLAG_UNSYNC) != 0 ||
        ((work->frame_flags & ID3V2_FRAME_FORMAT_UNSYNCHRONISATION) != 0)) {
      GST_DEBUG ("Un-unsyncing frame %s", work->frame_id);
      uu_data = id3demux_ununsync_data (frame_data, &frame_data_size);
      frame_data = uu_data;
      GST_MEMDUMP ("ID3v2 frame (un-unsyced)", frame_data, frame_data_size);
    }
  }

  work->parse_size = frame_data_size;

  if (work->frame_flags & ID3V2_FRAME_FORMAT_COMPRESSION) {
#ifdef HAVE_ZLIB
    uLongf destSize = work->parse_size;
    Bytef *dest, *src;

    uncompressed_data = g_malloc (work->parse_size);

    dest = (Bytef *) uncompressed_data;
    src = (Bytef *) frame_data;

    if (uncompress (dest, &destSize, src, frame_data_size) != Z_OK) {
      g_free (uncompressed_data);
      g_free (uu_data);
      return FALSE;
    }
    if (destSize != work->parse_size) {
      GST_WARNING
          ("Decompressing ID3v2 frame %s did not produce expected size %d bytes (got %lu)",
          tag_name, work->parse_size, destSize);
      g_free (uncompressed_data);
      g_free (uu_data);
      return FALSE;
    }
    work->parse_data = uncompressed_data;
#else
    GST_WARNING ("Compressed ID3v2 tag frame could not be decompressed"
        " because gstid3demux was compiled without zlib support");
    g_free (uu_data);
    return FALSE;
#endif
  } else {
    work->parse_data = frame_data;
  }

  if (work->frame_id[0] == 'T') {
    if (strcmp (work->frame_id, "TDAT") == 0) {
      parse_obsolete_tdat_frame (work);
      result = TRUE;
    } else if (strcmp (work->frame_id, "TXXX") == 0) {
      /* Handle user text frame */
      tag_str = parse_user_text_identification_frame (work, &tag_name);
    } else {
      /* Text identification frame */
      tag_fields = parse_text_identification_frame (work);
    }
  } else if (work->frame_id[0] == 'W' && strcmp (work->frame_id, "WXXX") != 0) {
    /* URL link frame: ISO-8859-1 encoded, one frame per tag */
    tag_str = parse_url_link_frame (work, &tag_name);
  } else if (!strcmp (work->frame_id, "COMM")) {
    /* Comment */
    result = parse_comment_frame (work);
  } else if (!strcmp (work->frame_id, "APIC")) {
    /* Attached picture */
    result = parse_picture_frame (work);
  } else if (!strcmp (work->frame_id, "RVA2")) {
    /* Relative volume */
    result = parse_relative_volume_adjustment_two (work);
  } else if (!strcmp (work->frame_id, "UFID")) {
    /* Unique file identifier */
    tag_str = parse_unique_file_identifier (work, &tag_name);
  }
#ifdef HAVE_ZLIB
  if (work->frame_flags & ID3V2_FRAME_FORMAT_COMPRESSION) {
    g_free (uncompressed_data);
    uncompressed_data = NULL;
    work->parse_data = frame_data;
  }
#endif

  if (tag_str != NULL) {
    /* g_print ("Tag %s value %s\n", tag_name, tag_str); */
    result = id3v2_tag_to_taglist (work, tag_name, tag_str);
    g_free (tag_str);
  }
  if (tag_fields != NULL) {
    if (strcmp (work->frame_id, "TCON") == 0) {
      /* Genre strings need special treatment */
      result |= id3v2_genre_fields_to_taglist (work, tag_name, tag_fields);
    } else {
      gint t;

      for (t = 0; t < tag_fields->len; t++) {
        tag_str = g_array_index (tag_fields, gchar *, t);
        if (tag_str != NULL && tag_str[0] != '\0')
          result |= id3v2_tag_to_taglist (work, tag_name, tag_str);
      }
    }
    free_tag_strings (tag_fields);
  }

  g_free (uu_data);

  return result;
}
Example #22
0
/**************************************************************************
presult indicates if there is more packets in the cache. We return result
instead of just testing if the returning package is NULL as we sometimes
return a NULL packet even if everything is OK (receive_packet_goto_route).
**************************************************************************/
void *get_packet_from_connection(struct connection *pc,
				 enum packet_type *ptype, bool *presult)
{
  int len_read;
  int whole_packet_len;
  struct {
    enum packet_type type;
    int itype;
  } utype;
  int typeb1, typeb2;
  struct data_in din;
#ifdef USE_COMPRESSION
  bool compressed_packet = FALSE;
#endif
  int header_size = 4;

  *presult = FALSE;

  if (!pc->used) {
    return NULL;		/* connection was closed, stop reading */
  }
  
  if (pc->buffer->ndata < 2+2) {
    /* length and type not read */
    return NULL;
  }

  dio_input_init(&din, pc->buffer->data, pc->buffer->ndata);
  dio_get_uint16(&din, &len_read);

  /* The non-compressed case */
  whole_packet_len = len_read;

#ifdef USE_COMPRESSION
  if (len_read == JUMBO_SIZE) {
    compressed_packet = TRUE;
    header_size = 6;
    if (dio_input_remaining(&din) >= 4) {
      dio_get_uint32(&din, &whole_packet_len);
      log_compress("COMPRESS: got a jumbo packet of size %d",
                   whole_packet_len);
    } else {
      /* to return NULL below */
      whole_packet_len = 6;
    }
  } else if (len_read >= COMPRESSION_BORDER) {
    compressed_packet = TRUE;
    header_size = 2;
    whole_packet_len = len_read - COMPRESSION_BORDER;
    log_compress("COMPRESS: got a normal packet of size %d",
                 whole_packet_len);
  }
#endif /* USE_COMPRESSION */

  if ((unsigned)whole_packet_len > pc->buffer->ndata) {
    return NULL;		/* not all data has been read */
  }

  if (whole_packet_len < header_size) {
    log_verbose("The packet size is reported to be less than header alone. "
                "The connection will be closed now.");
    connection_close(pc, _("illegal packet size"));

    return NULL;
  }

#ifdef USE_COMPRESSION
  if (compressed_packet) {
    uLong compressed_size = whole_packet_len - header_size;
    /* 
     * We don't know the decompressed size. We assume a bad case
     * here: an expansion by an factor of 100. 
     */
    unsigned long int decompressed_size = 100 * compressed_size;
    void *decompressed = fc_malloc(decompressed_size);
    int error;
    struct socket_packet_buffer *buffer = pc->buffer;
    
    error =
	uncompress(decompressed, &decompressed_size,
		   ADD_TO_POINTER(buffer->data, header_size), 
		   compressed_size);
    if (error != Z_OK) {
      log_verbose("Uncompressing of the packet stream failed. "
                  "The connection will be closed now.");
      connection_close(pc, _("decoding error"));
      return NULL;
    }

    buffer->ndata -= whole_packet_len;
    /* 
     * Remove the packet with the compressed data and shift all the
     * remaining data to the front. 
     */
    memmove(buffer->data, buffer->data + whole_packet_len, buffer->ndata);

    if (buffer->ndata + decompressed_size > buffer->nsize) {
      buffer->nsize += decompressed_size;
      buffer->data = fc_realloc(buffer->data, buffer->nsize);
    }

    /*
     * Make place for the uncompressed data by moving the remaining
     * data.
     */
    memmove(buffer->data + decompressed_size, buffer->data, buffer->ndata);

    /* 
     * Copy the uncompressed data.
     */
    memcpy(buffer->data, decompressed, decompressed_size);

    free(decompressed);

    buffer->ndata += decompressed_size;
    
    log_compress("COMPRESS: decompressed %ld into %ld",
                 compressed_size, decompressed_size);

    return get_packet_from_connection(pc, ptype, presult);
  }
#endif /* USE_COMPRESSION */

  /*
   * At this point the packet is a plain uncompressed one. These have
   * to have to be at least 4 bytes in size.
   */
  if (whole_packet_len < 2+2) {
    log_verbose("The packet stream is corrupt. The connection "
                "will be closed now.");
    connection_close(pc, _("decoding error"));
    return NULL;
  }

  /* Instead of one dio_get_uint16() we do twice dio_get_uint8().
   * Older (<= 2.4) versions had 8bit type field, and we detect
   * here if this is initial PACKET_SERVER_JOIN_REQ from such a client. */
  dio_get_uint8(&din, &typeb1);

  if (typeb1 == PACKET_SERVER_JOIN_REQ) {
    utype.itype = typeb1;
  } else {
    dio_get_uint8(&din, &typeb2);
    utype.itype = ntohs((typeb2 << 8) + typeb1);
  }

  utype.type = utype.itype;

  log_packet("got packet type=(%s)%d len=%d from %s",
             packet_name(utype.type), utype.itype, whole_packet_len,
             is_server() ? pc->username : "******");

  *ptype = utype.type;
  *presult = TRUE;

  if (pc->incoming_packet_notify) {
    pc->incoming_packet_notify(pc, utype.type, whole_packet_len);
  }

#if PACKET_SIZE_STATISTICS 
  {
    static struct {
      int counter;
      int size;
    } packets_stats[PACKET_LAST];
    static int packet_counter = 0;

    int packet_type = utype.itype;
    int size = whole_packet_len;

    if (!packet_counter) {
      int i;

      for (i = 0; i < PACKET_LAST; i++) {
	packets_stats[i].counter = 0;
	packets_stats[i].size = 0;
      }
    }

    packets_stats[packet_type].counter++;
    packets_stats[packet_type].size += size;

    packet_counter++;
    if (packet_counter % 100 == 0) {
      int i, sum = 0;

      log_test("Received packets:");
      for (i = 0; i < PACKET_LAST; i++) {
	if (packets_stats[i].counter == 0)
	  continue;
	sum += packets_stats[i].size;
        log_test("  [%-25.25s %3d]: %6d packets; %8d bytes total; "
                 "%5d bytes/packet average",
                 packet_name(i), i, packets_stats[i].counter,
                 packets_stats[i].size,
                 packets_stats[i].size / packets_stats[i].counter);
      }
      log_test("received %d bytes in %d packets;average size "
               "per packet %d bytes",
               sum, packet_counter, sum / packet_counter);
    }
  }
#endif /* PACKET_SIZE_STATISTICS */
  return get_packet_from_connection_helper(pc, utype.type);
}
Example #23
0
void LevelParser::parseTileLayer(TiXmlElement * pTileElement, std::vector<Layer*>* pLayers, const std::vector<Tileset>* pTilesets, std::vector<TileLayer*>* pCollisionLayers)
{
	bool collidable = false;
	//crar un nuevo tileLayer
	TileLayer* pTileLayer = new TileLayer(m_tileSize, *pTilesets);
	// tile data
	std::vector<std::vector<int>> data;
	std::string decodedIDs;
	TiXmlElement* pDataNode = NULL;
	////////

	for (TiXmlElement* e = pTileElement->FirstChildElement(); e !=
		NULL; e = e->NextSiblingElement())
	{
		if (e->Value() == std::string("properties"))
		{
			for (TiXmlElement* property = e->FirstChildElement(); property
				!= NULL; property = property->NextSiblingElement())
			{
				if (property->Value() == std::string("property"))
				{
					if (property->Attribute("name") == std::string("coli") && property->Attribute("value") == std::string("True"))
					{
						collidable = true;
					}
				}
			}
		}
		if (e->Value() == std::string("data"))
		{
			pDataNode = e;
		}
	}

	/////////
	for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e =
		e->NextSibling())
	{
		TiXmlText* text = e->ToText();
		std::string t = text->Value();
		decodedIDs = base64_decode(t);
	}
	// uncompress zlib compression
	uLongf numGids = m_width * m_height * sizeof(int);
	std::vector<unsigned> gids(numGids);
	uncompress((Bytef*)&gids[0], &numGids, (const
		Bytef*)decodedIDs.c_str(), decodedIDs.size());
	std::vector<int> layerRow(m_width);
	for (int j = 0; j < m_height; j++)
	{
		data.push_back(layerRow);
	}
	for (int rows = 0; rows < m_height; rows++) {
		for (int cols = 0; cols < m_width; cols++)
		{
			data[rows][cols] = gids[rows * m_width + cols];
		}
	}
	pTileLayer->setTileIDs(data);

	if (collidable)
	{
		pCollisionLayers->push_back(pTileLayer);
	}
	
		pLayers->push_back(pTileLayer);
	

	
}
Example #24
0
bool MxoProp::Parse(){

    if(b.loadData(path)){
        b.seekToStr("DIMS");

        // Skip length
        b.seek(8);

        // Get Bounding Box
        for(int i = 0;i<6;i++){
            dims.push_back(b.getFloat());
        }

        // Skip to texture info
        b.seek(12);

        unsigned int textureCount = b.getInt32();
        for(unsigned int i = 0;i<textureCount;i++){
            textures.push_back(b.getBlob(4));
        }

        // Skip MESH+pointer
        b.seek(8);


        model = new IndexedModel();
        
        //LOCALS
        float minX = 0;
        float minZ = 0;
        float maxX = 0;
        float maxZ = 0;
        

        unsigned int meshCount = b.getInt32();

        for(unsigned int i = 0;i<meshCount;i++){

            model->addMesh();

            b.seek(4); // Skip SMSH
            unsigned int meshWHOLEDATASize = b.getInt32();
            b.seek(4); // Skip data

            // We will ignore this blob for now
            string meshBlob = b.getBlob(0x20);

            // Prepare to do zlib.uncompress(MESHCHUNK)
            unsigned long zlibBufferSize = (unsigned long) b.getInt32();
            unsigned char* zlibBuffer = new unsigned char[zlibBufferSize];

            unsigned int meshZlibSize = b.getInt32();
            string meshZlibBlob = b.getBlob(meshZlibSize);


            uncompress((Bytef *)zlibBuffer, &zlibBufferSize,  (Bytef *)meshZlibBlob.c_str(), meshZlibSize);

            // Gather meshData
            string meshData;

            for(unsigned int j = 0;j<zlibBufferSize;j++){
                meshData+=zlibBuffer[j];
            }

            delete zlibBuffer;

            // Prepare another binaryWalker
            bm.setData(meshData);

            unsigned int meshChunkLength = bm.getInt32();
            unsigned int meshVerticesCount = bm.getInt32();
            bm.seek(8); // say...say my name... little little love....


            for(unsigned int j = 0;j<meshVerticesCount;j++){

                // Mesh creation
                ModelVertex* vert = new ModelVertex();

                vert->coords.x = -1 * bm.getFloat() / 100.0;
                vert->coords.y = bm.getFloat() / 100.0;
                vert->coords.z = bm.getFloat() /100.0;

                vert->normal.x = bm.getFloat(); // NORMALS
                vert->normal.y = bm.getFloat();
                vert->normal.z = bm.getFloat();

                vert->color.x = 1.0f;
                vert->color.y = 0.0f;
                vert->color.z = 0.0f;

                vert->uvCoords.x = bm.getFloat();
                vert->uvCoords.y = (1.0f - bm.getFloat()); // Reverse DDS V from directX to openGL

                // ADD vertex to current mesh
                (model->getCurrentMesh())->addVertex(vert);

                
                // Force bounding limit checks
                if (vert->coords.x>maxX){
                    maxX = vert->coords.x;
                }
                
                if (vert->coords.z>maxZ){
                    maxZ = vert->coords.z;
                }
                
                if (vert->coords.x<minX){
                    minX = vert->coords.x;
                }
                
                if (vert->coords.z<minZ){
                    minZ = vert->coords.z;
                }
   
                
            }

            while(bm.getOffset()!=meshChunkLength+4){
                unsigned short index = bm.getInt16();
                 (model->getCurrentMesh())->addIndex(index);
            }

        }

        // INIT THE MODEL
        model->initVao();

        cout<<"MXO PROP DEBUG: "<<minX<<" "<<minZ<<" "<<maxX<<" "<<maxZ<<" "<<endl;
        
        return true;
    }else{
        cout<<"[ERROR] Could not load MXO Prop: "<<path<<endl;
        return false;
    }
}
Example #25
0
triArchiveFile* triArchiveRead(triChar *file, triArchive* archive)
{
	if(strlen(file) >= TRI_ARCHIVE_MAX_FNLEN || archive == NULL)
		return NULL;
	
	triArchiveEntry *entry = archive->entries;
	int i;
	int found=0;
	for(i=0; i<archive->numfiles; i++,entry++)
	{
		if(!strncmp(entry->filename,file,TRI_ARCHIVE_MAX_FNLEN))
		{
			found = 1;
			break;
		}
	}
	
	if(!found)
		return NULL;
	
	unsigned char flags = (unsigned char)entry->filesize>>24;
	int size = entry->filesize&0x00FFFFFF;
	char *buffer = (char*)malloc(size);
	if(!buffer)
		return NULL;
	//open archive and read in file;
	FILE *fd = fopen(archive->archivename,"r+b");
	if(!fd)
	{
		free(buffer);
		return NULL;
	}
	fseek(fd,archive->off_file_table + entry->off_file_table,SEEK_SET);
	if(fread(buffer,size,1,fd) != size)
	{
		free(buffer);
		fclose(fd);
		return NULL;
	}
	fclose(fd);
	
	triArchiveFile *arfile = (triArchiveFile*)malloc(sizeof(triArchiveFile));
	if(!arfile)
		return NULL;
	
	arfile->data = buffer;
	arfile->size = size;
	
	if(flags & TRI_ARCHIVE_ENC == TRI_ARCHIVE_ENC)
	{
		int i,y=0;
		for(i=0; i<size; i++)
		{
			buffer[i]^=archive->key[y++];
			if(y == TRI_ARCHIVE_KEYLEN)
				y=0;
		}
	}
	
	if(flags & TRI_ARCHIVE_COMP == TRI_ARCHIVE_COMP)
	{
		triUChar comptype = (triUChar)entry->uncomp_filesize>>24;
		if(comptype & TRI_ARCHIVE_ZLIB == TRI_ARCHIVE_ZLIB)
		{
			triU32 uncompsize = entry->uncomp_filesize&0x00FFFFFF;
			char *buffer2 = (char*)malloc(uncompsize);
			if(!buffer2)
			{
				free(arfile);
				return NULL;
			}
	
			if(uncompress ((triUChar*)buffer2, &uncompsize, (triUChar*)buffer, size) != Z_OK)
			{
				free(arfile);
				free(buffer2);
				return NULL;
			}
			free(buffer);
			arfile->data = buffer2;
			arfile->size = uncompsize;
		}
	}
Example #26
0
//---------------------------------------------------------------------------
long PacketFile::readPacket (long packet, unsigned char *buffer)
{
    long result = 0;

    if ((packet==-1) || (packet == currentPacket) || (seekPacket(packet) == NO_ERR))
    {
        if ((getStorageType() == STORAGE_TYPE_RAW) || (getStorageType() == STORAGE_TYPE_FWF))
        {
            seek(packetBase);
            result = read(buffer, packetSize);
        }
        else
        {
            switch (getStorageType())
            {
            case STORAGE_TYPE_LZD:
            {
                seek(packetBase+sizeof(long));

                if (!LZPacketBuffer)
                {
                    LZPacketBuffer = (MemoryPtr)malloc(LZPacketBufferSize);
                    gosASSERT(LZPacketBuffer);
                }

                if ((long)LZPacketBufferSize < packetSize)
                {
                    LZPacketBufferSize = packetSize;

                    free(LZPacketBuffer);
                    LZPacketBuffer = (MemoryPtr)malloc(LZPacketBufferSize);
                    gosASSERT(LZPacketBuffer);
                }

                if (LZPacketBuffer)
                {
                    read(LZPacketBuffer,(packetSize-sizeof(long)));
                    long decompLength = LZDecomp(buffer,LZPacketBuffer,packetSize-sizeof(long));
                    if (decompLength != packetUnpackedSize)
                        result = 0;
                    else
                        result = decompLength;
                }
            }
            break;

            case STORAGE_TYPE_ZLIB:
            {
                seek(packetBase+sizeof(long));

                if (!LZPacketBuffer)
                {
                    LZPacketBuffer = (MemoryPtr)malloc(LZPacketBufferSize);
                    gosASSERT(LZPacketBuffer);
                }

                if ((long)LZPacketBufferSize < packetSize)
                {
                    LZPacketBufferSize = packetSize;

                    free(LZPacketBuffer);
                    LZPacketBuffer = (MemoryPtr)malloc(LZPacketBufferSize);
                    gosASSERT(LZPacketBuffer);
                }

                if (LZPacketBuffer)
                {
                    read(LZPacketBuffer,(packetSize-sizeof(long)));
                    unsigned long decompLength = LZPacketBufferSize;
                    long decompResult = uncompress(buffer,&decompLength,LZPacketBuffer,packetSize-sizeof(long));
                    if ((decompResult != Z_OK) || ((long)decompLength != packetUnpackedSize))
                        result = 0;
                    else
                        result = decompLength;
                }
            }
            break;

            case STORAGE_TYPE_HF:
                STOP(("Tried to read a Huffman Compressed Packet.  No Longer Supported!!"));
                break;
            }
        }
    }

    return result;
}
Example #27
0
/*****
* Name:			_XmHTMLReadFLG
* Return Type:	XmImage*
* Description:	reads a Fast Loadable Graphic directly into an XmImage.
* In:
*	ib:			raw image data;
* Returns:
*	an allocated XmImage or NULL on failure.
*****/
XmImageInfo*
_XmHTMLReadFLG(XmHTMLWidget html, ImageBuffer *ib)
{
    XmImageInfo *image = NULL;
    Byte *buffer = NULL, c = 0;
    Boolean err = False;
    ImageBuffer *dp;

#if defined(HAVE_LIBPNG) || defined(HAVE_LIBZ)
    ImageBuffer data;
    int zlib_err;
#endif

    image = NULL;

    /* sanity */
    RewindImageBuffer(ib);

    /* skip magic & version number */
    ib->curr_pos += 7;
    ib->next += 7;

    /* check if data is compressed */
    _readByte(c);

    if(c == 1)
    {
#if !defined(HAVE_LIBPNG) && !defined(HAVE_LIBZ)
        /* compressed FLG requires zlib support to be present */
        _XmHTMLWarning(__WFUNC__(html, "_XmHTMLReadFLG"),
                       XMHTML_MSG_103, ib->file, "zlib support not compiled in");
        return(image);
#else
        Cardinal tmp = 0;
        unsigned long dsize, csize;

        /* get size of uncompressed data */
        _readCardinal(tmp);
        dsize = (unsigned long)tmp;

        /* size of compressed data */
        csize = (unsigned long)(ib->size - ib->next);

        /* allocate uncompress buffer */
        buffer = (Byte*)malloc(dsize+1);

        if((zlib_err = uncompress(buffer, &dsize, ib->curr_pos, csize)) != Z_OK)
        {
            _XmHTMLWarning(__WFUNC__(html, "_XmHTMLReadFLG"),
                           XMHTML_MSG_103, ib->file,
                           zlib_err == Z_MEM_ERROR ? "out of memory" :
                           zlib_err == Z_BUF_ERROR ? "not enough output room" :
                           "data corrupted");
            err = True;
        }
        else if(dsize != (unsigned long)tmp)
        {
            _XmHTMLWarning(__WFUNC__(html, "_XmHTMLReadFLG"),
                           XMHTML_MSG_104, ib->file, dsize, tmp);
            err = True;
        }
        /* compose local image buffer */
        data.buffer = buffer;
        data.curr_pos = data.buffer;
        data.size   = (size_t)dsize;
        data.next   = 0;
        data.may_free = False;
        dp = &data;
#endif
    }
    else
        dp = ib;

    if(err)
    {
        /* free up compressed buffer */
        if(c == 1)
            free(buffer);
        return(image);
    }

    /* now go and process the actual image */
    RewindImageBuffer(dp);

    image = readFLG(dp);

    /* store name of image */
    image->url = strdup(ib->file);	/* image location */

    /* free up compressed buffer */
    if(c == 1)
        free(buffer);

    return(image);
}
Example #28
0
//---------------------------------------------------------------------------
long PacketFile::writePacket (long packet, MemoryPtr buffer, long nbytes, unsigned char pType)
{
    //--------------------------------------------------------
    // This function writes the packet to the current end
    // of file and stores the packet address in the seek
    // table.  NOTE that this cannot be used to replace
    // a packet.  That function is writePacket which takes
    // a packet number and a buffer.  The size cannot change
    // and, as such, is irrelevant.  You must write the
    // same sized packet each time, if the packet already
    // exists.  In theory, it could be smaller but the check
    // right now doesn't allow anything but same size.
    long result = 0;

    MemoryPtr workBuffer = NULL;

    if (pType == ANY_PACKET_TYPE || pType == STORAGE_TYPE_LZD || pType == STORAGE_TYPE_ZLIB)
    {
        if ((nbytes<<1) < 4096)
            workBuffer = (MemoryPtr)malloc(4096);
        else
            workBuffer = (MemoryPtr)malloc(nbytes<<1);

        gosASSERT(workBuffer != NULL);
    }

    gosASSERT((packet > 0) || (packet < numPackets));

    packetBase = getLength();
    currentPacket = packet;
    packetSize = packetUnpackedSize = nbytes;

    //-----------------------------------------------
    // Code goes in here to pick the best compressed
    // version of the packet.  Otherwise, default
    // to RAW.
    if ((pType == ANY_PACKET_TYPE) || (pType == STORAGE_TYPE_LZD) || (pType == STORAGE_TYPE_ZLIB))
    {
        if (pType == ANY_PACKET_TYPE)
            pType = STORAGE_TYPE_RAW;

        //-----------------------------
        // Find best compression here.
        // This USED to use LZ.  Use ZLib from now on.
        // Game will ALWAYS be able to READ LZ Packets!!
        unsigned long actualSize = nbytes << 1;
        if (actualSize < 4096)
            actualSize = 4096;

        unsigned long workBufferSize = actualSize;
        unsigned long oldBufferSize = nbytes;
        long compressedResult = compress2(workBuffer,&workBufferSize,buffer,nbytes,Z_DEFAULT_COMPRESSION);
        if (compressedResult != Z_OK)
            STOP(("Unable to write packet %d to file %s.  Error %d",packet,fileName,compressedResult));

        compressedResult = uncompress(buffer,&oldBufferSize,workBuffer,nbytes);
        if ((long)oldBufferSize != nbytes)
            STOP(("Packet size changed after compression.  Was %d is now %d",nbytes,oldBufferSize));

        if ((pType == STORAGE_TYPE_LZD) || (pType == STORAGE_TYPE_ZLIB) || ((long)workBufferSize < nbytes))
        {
            pType = STORAGE_TYPE_ZLIB;
            packetSize = workBufferSize;
        }
    }

    packetType = pType;
    seek(packetBase);

    if (packetType == STORAGE_TYPE_ZLIB)
    {
        writeLong(packetUnpackedSize);
        result = write(workBuffer, packetSize);
    }
    else
    {
        result = write(buffer, packetSize);
    }

    if (!seekTable)
    {
        seek(TABLE_ENTRY(packet));
        writeLong(SetPacketType(packetBase,packetType));
    }
    else
    {
        seekTable[packet] = SetPacketType(packetBase,packetType);
    }

    long *currentEntry = NULL;
    if (seekTable)
    {
        packet++;
        currentEntry = &(seekTable[packet]);
    }

    long tableData = SetPacketType(getLength(),STORAGE_TYPE_NUL);
    while (packet < (numPackets - 1))
    {
        if (!seekTable)
        {
            writeLong(tableData);
        }
        else
        {
            *currentEntry = tableData;
            currentEntry++;
        }
        packet++;
    }

    if (workBuffer)
        free(workBuffer);

    return result;
}
Example #29
0
////////////////////////////////////////////////////////////////////////////////
// 
// FUNCTION:	CIOCPServer::OnClientReading
// 
// DESCRIPTION:	Called when client is reading 
// 
// INPUTS:		
// 
// NOTES:	
// 
// MODIFICATIONS:
// 
// Name                  Date       Version    Comments
// N T ALMOND            06042001	1.0        Origin
// Ulf Hedlund           09062001		       Changes for OVERLAPPEDPLUS
////////////////////////////////////////////////////////////////////////////////
bool CIOCPServer::OnClientReading(ClientContext* pContext, DWORD dwIoSize)
{
	CLock cs(CIOCPServer::m_cs, "OnClientReading");
	try
	{
		//////////////////////////////////////////////////////////////////////////
		static DWORD nLastTick = GetTickCount();
		static DWORD nBytes = 0;
		nBytes += dwIoSize;
		
		if (GetTickCount() - nLastTick >= 1000)
		{
			nLastTick = GetTickCount();
			InterlockedExchange((LPLONG)&(m_nRecvKbps), nBytes);
			nBytes = 0;
		}

		//////////////////////////////////////////////////////////////////////////

		if (dwIoSize == 0)
		{
			RemoveStaleClient(pContext, FALSE);
			return false;
		}

		if (dwIoSize == FLAG_SIZE && memcmp(pContext->m_byInBuffer, m_bPacketFlag, FLAG_SIZE) == 0)
		{
			// 重新发送
			Send(pContext, pContext->m_ResendWriteBuffer.GetBuffer(), pContext->m_ResendWriteBuffer.GetBufferLen());
			// 必须再投递一个接收请求
			PostRecv(pContext);
			return true;
		}

		// Add the message to out message
		// Dont forget there could be a partial, 1, 1 or more + partial mesages
		pContext->m_CompressionBuffer.Write(pContext->m_byInBuffer,dwIoSize);
			
		m_pNotifyProc((LPVOID) m_pFrame, pContext, NC_RECEIVE);


		// Check real Data
		while (pContext->m_CompressionBuffer.GetBufferLen() > HDR_SIZE)
		{
			BYTE bPacketFlag[FLAG_SIZE];
			CopyMemory(bPacketFlag, pContext->m_CompressionBuffer.GetBuffer(), sizeof(bPacketFlag));

			if (memcmp(m_bPacketFlag, bPacketFlag, sizeof(m_bPacketFlag)) != 0)
				throw "bad buffer";

			int nSize = 0;
			CopyMemory(&nSize, pContext->m_CompressionBuffer.GetBuffer(FLAG_SIZE), sizeof(int));
			
			// Update Process Variable
			pContext->m_nTransferProgress = pContext->m_CompressionBuffer.GetBufferLen() * 100 / nSize;

			if (nSize && (pContext->m_CompressionBuffer.GetBufferLen()) >= nSize)
			{
				int nUnCompressLength = 0;
				// Read off header
				pContext->m_CompressionBuffer.Read((PBYTE) bPacketFlag, sizeof(bPacketFlag));

				pContext->m_CompressionBuffer.Read((PBYTE) &nSize, sizeof(int));
				pContext->m_CompressionBuffer.Read((PBYTE) &nUnCompressLength, sizeof(int));
				
				////////////////////////////////////////////////////////
				////////////////////////////////////////////////////////
				// SO you would process your data here
				// 
				// I'm just going to post message so we can see the data
				int	nCompressLength = nSize - HDR_SIZE;
				PBYTE pData = new BYTE[nCompressLength];
				PBYTE pDeCompressionData = new BYTE[nUnCompressLength];
				
				if (pData == NULL || pDeCompressionData == NULL)
					throw "bad Allocate";

				pContext->m_CompressionBuffer.Read(pData, nCompressLength);

				//////////////////////////////////////////////////////////////////////////
				unsigned long	destLen = nUnCompressLength;
				int	nRet = uncompress(pDeCompressionData, &destLen, pData, nCompressLength);
				//////////////////////////////////////////////////////////////////////////
				if (nRet == Z_OK)
				{
					pContext->m_DeCompressionBuffer.ClearBuffer();
					pContext->m_DeCompressionBuffer.Write(pDeCompressionData, destLen);
					m_pNotifyProc((LPVOID) m_pFrame, pContext, NC_RECEIVE_COMPLETE);
				}
				else
				{
					throw "bad buffer";
				}

				delete [] pData;
				delete [] pDeCompressionData;
				pContext->m_nMsgIn++;
			}
			else
				break;
		}
		// Post to WSARecv Next
		PostRecv(pContext);
	}catch(...)
	{
		pContext->m_CompressionBuffer.ClearBuffer();
		// 要求重发,就发送0, 内核自动添加数包标志
		Send(pContext, NULL, 0);
		PostRecv(pContext);
	}

	return true;
}
Example #30
0
void LevelParser::parseTileLayer
(TiXmlElement *pTileElement, vector<ILayer *> *pLayers,
 vector<TileLayer*>* pCollisionLayers,vector<Tileset> *pTilesets){
    
    TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, *pTilesets);
    
    
    //Check for layer properties
    bool collidable(false);
    
    for (TiXmlElement* e = pTileElement->FirstChildElement();
         e != NULL; e = e->NextSiblingElement()){
        //cout << "Checking " << e->Value() << "\n";
        if (e->Value() == string("properties")){
            for (TiXmlElement* p = e->FirstChildElement();
                 p != NULL; p = p->NextSiblingElement()){
                if (p->Value() == string("property")){
                    cout << "Now checking " << p->Value() << "\n";
                    string currentProperty = p->Attribute("name");
                    
                    if (currentProperty == string("collidable")){
                        if (p->Attribute("value") == string("true")){
                            collidable = true;
                        } else {
                            collidable = false;
                        }
                        if (collidable){
                            cout << "Found collidable layer\n";
                        }
                    }
                }
            }
        }
    }
    
    
    //Find data node then store it
    //pDataNode = findElement("data", pTileElement->FirstChildElement());
    bool isBase64  = false ;
    bool isZlibCompressed = false;
    
    TiXmlElement* pDataNode= 0;
    
    for (TiXmlElement* e = pTileElement->FirstChildElement();
         e != NULL; e = e->NextSiblingElement()){
        if (e->Value() == string("data")){
            pDataNode = e;
            
            //Check if encoded/compressed
            if (e->Attribute("encoding")){
                if (e->Attribute("encoding") == string("base64")){
                    isBase64 = true;
                }
            }
            
            if (e->Attribute("compression")){
                if (e->Attribute("compression") == string("zlib")){
                    isZlibCompressed = true;
                }
            }
        }
    }
    
    
    //Decode data and store
    string decodedIDs;
    
    if (pDataNode && isBase64){
        for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()){
            TiXmlText* text = e ->ToText();
            string t = text->Value();
            decodedIDs = base64_decode(t);
        }
    }
    
    //Placeholder for data
    vector<vector<int>> data;
    
    //Calculate number of GIDS present
    uLongf numGids = m_width * m_height * sizeof(int);
    vector<unsigned> gids(numGids);
    
    
    //Horizontal register for vector
    vector<int> layerRow(m_width);
    
    //Build empty data vector to fill
    for(int j = 0 ; j < m_height; j++){
        data.push_back(layerRow);
    }
    
    //Compressed data assignment
    if (isZlibCompressed){
        uncompress
        ((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size());
        
        
        for (int rows = 0 ; rows <m_height; rows++){
            for (int cols = 0; cols < m_width; cols++){
                data[rows][cols] = gids[rows * m_width + cols];
            }
        }
    } else {
        //Uncompressed data assignment
        int index = 0;
        int tileID = 0;
        
        //Find all tiles, assign GID to proper data vector place
        for (TiXmlElement* e = pDataNode->FirstChildElement();
             e != NULL; e = e->NextSiblingElement()){
            
            e->Attribute("gid",&tileID);
            data[index / m_width][index % m_width] = tileID;
            index++;
        }
    }
    
    
    //Set Tile Layer properties
    pTileLayer->setTileIDs(data);
    pTileLayer->setNumColumns(m_width);
    pTileLayer->setNumRows(m_height);
    
    //Save new tile layer to Level
    cout << "Added new layer\n";
    pLayers->push_back(pTileLayer);
    
    //Add collision tiles to collision layer
    if (collidable){
        pCollisionLayers->push_back(pTileLayer);
        cout << "Added new collision layer\n";
    }
    
}