Exemplo n.º 1
0
bytes_t HGE_CALL HGE_Impl::Resource_Load(const char *filename, uint32_t *size)
{
    static char *res_err = "Can't load resource: %s";

    //resource_packs_item_t *resItem = m_resources;
    char szName[_MAX_PATH];
    char szZipName[_MAX_PATH];
    unzFile zip;
    unz_file_info file_info;
    int done, i;
    void * ptr;
    HANDLE hF;

    if (filename[0] == '\\' || filename[0] == '/' || filename[1] == ':')
        goto _fromfile; // skip absolute paths

    // Load from pack

    strcpy(szName, filename);
    strupr(szName);
    for (i = 0; szName[i]; i++)
    {
        if (szName[i] == '/')
            szName[i] = '\\';
    }

    //while (resItem)
    // TODO: optimize this reopening shit out
    for( auto itr = m_resources.begin(); itr != m_resources.end(); ++itr )
    {
        resource_packs_item_t & resItem = itr->second;

        zip = unzOpen(resItem.filename.c_str());
        done = unzGoToFirstFile(zip);
        while (done == UNZ_OK)
        {
            unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0);
            strupr(szZipName);
            for (i = 0; szZipName[i]; i++)
            {
                if (szZipName[i] == '/')
                    szZipName[i] = '\\';
            }
            if (!strcmp(szName, szZipName))
            {
                if (unzOpenCurrentFilePassword( zip, resItem.password.empty()
                                                ? resItem.password.c_str()
                                                : nullptr ) != UNZ_OK)
                {
                    unzClose(zip);
                    sprintf(szName, res_err, filename);
                    _PostError(szName);
                    return nullptr;
                }

                ptr = malloc(file_info.uncompressed_size);
                if (!ptr)
                {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    sprintf(szName, res_err, filename);
                    _PostError(szName);
                    return nullptr;
                }

                if (unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0)
                {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    free(ptr);
                    sprintf(szName, res_err, filename);
                    _PostError(szName);
                    return nullptr;
                }
                unzCloseCurrentFile(zip);
                unzClose(zip);
                if (size)
                    *size = file_info.uncompressed_size;
                return bytes_t( (char*)ptr );
            }

            done = unzGoToNextFile(zip);
        }

        unzClose(zip);
        //resItem = resItem->next;
    }

    // Load from file
_fromfile:

    hF = CreateFile(Resource_MakePath(filename), GENERIC_READ, FILE_SHARE_READ, NULL,
                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);
    if (hF == INVALID_HANDLE_VALUE)
    {
        sprintf(szName, res_err, filename);
        _PostError(szName);
        return nullptr;
    }
    file_info.uncompressed_size = GetFileSize(hF, NULL);
    ptr = malloc(file_info.uncompressed_size);
    if (!ptr)
    {
        CloseHandle(hF);
        sprintf(szName, res_err, filename);
        _PostError(szName);
        return nullptr;
    }
    if (ReadFile(hF, ptr, file_info.uncompressed_size, &file_info.uncompressed_size, NULL ) == 0)
    {
        CloseHandle(hF);
        free(ptr);
        sprintf(szName, res_err, filename);
        _PostError(szName);
        return nullptr;
    }

    CloseHandle(hF);
    if (size)
        *size = file_info.uncompressed_size;
    return bytes_t( (char*)ptr);
}
Exemplo n.º 2
0
bool CMinizip::Open(LPCTSTR ZipPath)
{
    USES_CONVERSION;
    m_ZipFile = unzOpen(T2CA(ZipPath));
    return(m_ZipFile != NULL);
}
Exemplo n.º 3
0
int load_archive(char *filename, unsigned char *buffer, int maxsize, char *extension)
{
  int size = 0;
  
  if(check_zip(filename))
  {
    unz_file_info info;
    int ret = 0;
    char fname[256];

    /* Attempt to open the archive */
    unzFile *fd = unzOpen(filename);
    if (!fd) return 0;

    /* Go to first file in archive */
    ret = unzGoToFirstFile(fd);
    if(ret != UNZ_OK)
    {
      unzClose(fd);
      return 0;
    }

    /* Get file informations and update filename */
    ret = unzGetCurrentFileInfo(fd, &info, fname, 256, NULL, 0, NULL, 0);
    if(ret != UNZ_OK)
    {
      unzClose(fd);
      return 0;
    }

    /* Compressed filename extension */
    if (extension)
    {
      strncpy(extension, &fname[strlen(fname) - 3], 3);
      extension[3] = 0;
    }

    /* Open the file for reading */
    ret = unzOpenCurrentFile(fd);
    if(ret != UNZ_OK)
    {
      unzClose(fd);
      return 0;
    }

    /* Retrieve uncompressed file size */
    size = info.uncompressed_size;
    if(size > maxsize)
    {
      size = maxsize;
    }

    /* Read (decompress) the file */
    ret = unzReadCurrentFile(fd, buffer, size);
    if(ret != size)
    {
      unzCloseCurrentFile(fd);
      unzClose(fd);
      return 0;
    }

    /* Close the current file */
    ret = unzCloseCurrentFile(fd);
    if(ret != UNZ_OK)
    {
      unzClose(fd);
      return 0;
    }

    /* Close the archive */
    ret = unzClose(fd);
    if(ret != UNZ_OK) return 0;
  }
  else
  {
    /* Open file */
    gzFile *gd = gzopen(filename, "rb");
    if (!gd) return 0;

    /* Read file data */
    size = gzread(gd, buffer, maxsize);

    /* filename extension */
    if (extension)
    {
      strncpy(extension, &filename[strlen(filename) - 3], 3);
      extension[3] = 0;
    }

    /* Close file */
    gzclose(gd);
  }

  /* Return loaded ROM size */
  return size;
}
Exemplo n.º 4
0
    void UnzipTask::start(){
        _status=StatusUnzipping;
        
        FutureHolder * f(new FutureHolder);
        
        setProgress(0.f);
        f->future=std::async(std::launch::async, [=](){
        
            auto callbackL([=](Status status){
                call_on_main_thread([=]{
                    _status=status;
                    releaseSelf();
                    if (_completionHandle)
                        _completionHandle(_status);
                    delete f;
                });
            });
            
            auto eachCallbackL([=](const std::string & path, bool success){
                if (_completedEachHandle)
                    call_on_main_thread([=]{
                        _completedEachHandle(path, success);
                    });
            });
            
            unsigned long ulSize;
            unsigned char *pBuffer(nullptr);
            
            //background work
            unzFile pFile(unzOpen(_archivedFile.c_str()));
            if (pFile){
                int iStatus(unzGoToFirstFile(pFile));
                while (iStatus == UNZ_OK){
                    char szFilePath[260];
                    unz_file_info fileInfo;
                    iStatus = unzGetCurrentFileInfo(pFile, &fileInfo, szFilePath, sizeof(szFilePath), NULL, 0, NULL, 0);
                    if (iStatus != UNZ_OK){
                        break;
                    }
                    iStatus = unzOpenCurrentFile(pFile);
                    if (iStatus != UNZ_OK){
                        break;
                    }
                    pBuffer=new unsigned char[fileInfo.uncompressed_size];
                    ulSize=unzReadCurrentFile(pFile, pBuffer, fileInfo.uncompressed_size);
                    unzCloseCurrentFile(pFile);
                    std::string filePath(szFilePath);

                    bool isDirectory(false);
                    if (!filePath.empty())
                        isDirectory=filePath.back()=='/';
                    std::string path(Functions::stringByAppendingPathComponent(_destinationPath, filePath));
                    if (isDirectory) {
                        int result(mkdir(path.c_str(),0777));
                        eachCallbackL(path+"/", result==0);
                    }else{
                        FILE *pFHandle(fopen(path.c_str(), "wb"));
                        if (pFHandle){
                            fwrite(pBuffer, fileInfo.uncompressed_size, 1, pFHandle);
                            fclose(pFHandle);
                            eachCallbackL(path, true);
                        }else
                            eachCallbackL(path, false);
                        
                        }
                    delete [] pBuffer;
                    iStatus = unzGoToNextFile(pFile);
                }
                unzClose(pFile);
                callbackL(StatusCompleted);
                setProgress(1.f);
            }else
                callbackL(StatusFailed);
            
            
        });
        
    }
Exemplo n.º 5
0
bool DialogInstall::ReadPackage()
{
	const WCHAR* fileName = m_PackageFileName.c_str();
	const WCHAR* fileExtension = PathFindExtension(fileName);

	if (_wcsicmp(fileExtension, L".rmskin") == 0)
	{
		// Check if the footer is present (for new .rmskin format)
		PackageFooter footer = {0};

		FILE* file = _wfopen(fileName, L"rb");
		__int64 fileSize = 0;
		if (file)
		{
			fseek(file, -(long)sizeof(footer), SEEK_END);
			fileSize = _ftelli64(file);
			fread(&footer, sizeof(footer), 1, file);
			fclose(file);
		}

		if (strcmp(footer.key, "RMSKIN") == 0)
		{
			m_PackageFormat = PackageFormat::New;
			if (footer.size != fileSize)
			{
				return false;
			}

			if (footer.flags)
			{
				m_BackupPackage = !(footer.flags & PackageFlag::Backup);
			}
		}
	}
	else if (_wcsicmp(fileExtension, L".zip") != 0)
	{
		return false;
	}

	m_PackageUnzFile = unzOpen(ConvertToAscii(fileName).c_str());
	if (!m_PackageUnzFile)
	{
		return false;
	}

	WCHAR buffer[MAX_PATH];

	// Get temporary file to extract the options file and header bitmap
	GetTempPath(MAX_PATH, buffer);
	GetTempFileName(buffer, L"dat", 0, buffer);
	std::wstring tempFile = buffer;
	const WCHAR* tempFileSz = tempFile.c_str();

	// Helper to sets buffer with current file name
	auto getFileInfo = [&]()->bool
	{
		char cBuffer[MAX_PATH * 3];
		unz_file_info ufi;
		if (unzGetCurrentFileInfo(
				m_PackageUnzFile, &ufi, cBuffer, _countof(cBuffer), nullptr, 0, nullptr, 0) == UNZ_OK)
		{
			const uLong ZIP_UTF8_FLAG = 1 << 11;
			const DWORD codePage = (ufi.flag & ZIP_UTF8_FLAG) ? CP_UTF8 : CP_ACP;
			MultiByteToWideChar(codePage, 0, cBuffer, strlen(cBuffer) + 1, buffer, MAX_PATH);
			while (WCHAR* pos = wcschr(buffer, L'/')) *pos = L'\\';
			return true;
		}

		return false;
	};

	// Loop through the contents of the archive until the settings file is found
	WCHAR* path;
	bool optionsFound = false;
	do
	{
		if (!getFileInfo())
		{
			return false;
		}

		path = wcsrchr(buffer, L'\\');
		if (!path)
		{
			path = buffer;
		}
		else
		{
			if (m_PackageFormat == PackageFormat::New)
			{
				// New package files must be in root of archive
				continue;
			}

			++path;	// Skip slash
		}

		if (_wcsicmp(path, m_PackageFormat == PackageFormat::New ? L"RMSKIN.ini" : L"Rainstaller.cfg") == 0)
		{
			if (ExtractCurrentFile(tempFile))
			{
				optionsFound = ReadOptions(tempFileSz);
				DeleteFile(tempFileSz);
			}

			break;
		}
	}
	while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK);

	if (!optionsFound)
	{
		return false;
	}

	// Loop through the archive a second time and find included components
	unzGoToFirstFile(m_PackageUnzFile);

	m_PackageRoot.assign(buffer, path - buffer);
	const WCHAR* root = m_PackageRoot.c_str();
	do
	{
		if (!getFileInfo())
		{
			return false;
		}

		if (wcsncmp(buffer, root, m_PackageRoot.length()) != 0)
		{
			// Ignore everything that isn't in the root directory
			continue;
		}

		WCHAR* component = buffer + m_PackageRoot.length();
		path = wcschr(component, L'\\');
		if (path)
		{
			*path = L'\0';
			++path;
		}
		else
		{
			if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"RMSKIN.bmp" : L"Rainstaller.bmp") == 0)
			{
				if (!ExtractCurrentFile(tempFile))
				{
					return false;
				}

				m_HeaderBitmap = (HBITMAP)LoadImage(nullptr, tempFileSz, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
				DeleteFile(tempFileSz);
			}

			continue;
		}

		const WCHAR* pos = wcschr(path, L'\\');
		const WCHAR* extension = PathFindExtension(pos ? pos : path);
		if (pos)
		{
			// Component with subfolders
			const std::wstring item(path, pos - path);
			const WCHAR* itemSz = item.c_str();

			if (_wcsicmp(component, L"Skins") == 0 &&
				!IsIgnoredSkin(itemSz))
			{
				m_PackageSkins.insert(item);
			}
			else if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"Layouts" : L"Themes") == 0 &&
				_wcsicmp(extension, m_PackageFormat == PackageFormat::New ? L".ini" : L".thm") == 0 &&
				!IsIgnoredLayout(itemSz))
			{
				m_PackageLayouts.insert(item);
			}
			else if (_wcsicmp(component, L"Addons") == 0 &&
				m_PackageFormat == PackageFormat::Old &&
				!IsIgnoredAddon(itemSz))
			{
				m_PackageAddons.insert(item);
			}
			else if (_wcsicmp(component, L"Plugins") == 0 &&
				_wcsicmp(itemSz, IsWin32Build() ? L"32bit" : L"64bit") == 0 &&
				_wcsicmp(extension, L".dll") == 0 &&
				!wcschr(pos + 1, L'\\'))
			{
				const std::wstring plugin(pos + 1);
				if (!IsIgnoredPlugin(plugin.c_str()))
				{
					m_PackagePlugins.insert(plugin);
				}
			}
		}
		else
		{
			// Component with subfiles
			const std::wstring item = path;
			const WCHAR* itemSz = item.c_str();

			if (_wcsicmp(component, L"Fonts") == 0 &&
				m_PackageFormat == PackageFormat::Old &&
				_wcsicmp(extension, L".ttf") == 0)
			{
				m_PackageFonts.insert(item);
			}
		}
	}
	while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK);

	if (m_PackageSkins.empty())
	{
		// Fonts can be installed only with skins
		m_PackageFonts.clear();
	}

	return !(m_PackageSkins.empty() && m_PackageLayouts.empty() &&
		m_PackageAddons.empty() && m_PackageFonts.empty() && m_PackagePlugins.empty());
}
Exemplo n.º 6
0
/**
 * Returns a list of files from a zip file. returns NULL on failure,
 * returns a pointer to an array of strings if successful. Sets nfiles
 * to the number of files.
 */
zip_dir *ZIP_GetFiles(const char *pszFileName)
{
	int nfiles;
	unsigned int i;
	unz_global_info gi;
	int err;
	unzFile uf;
	char **filelist;
	unz_file_info file_info;
	char filename_inzip[ZIP_PATH_MAX];
	zip_dir *zd;

	uf = unzOpen(pszFileName);
	if (uf == NULL)
	{
		Log_Printf(LOG_ERROR, "ZIP_GetFiles: Cannot open %s\n", pszFileName);
		return NULL;
	}

	err = unzGetGlobalInfo(uf,&gi);
	if (err != UNZ_OK)
	{
		Log_Printf(LOG_ERROR, "Error %d with zipfile in unzGetGlobalInfo \n",err);
		return NULL;
	}

	/* allocate a file list */
	filelist = (char **)malloc(gi.number_entry*sizeof(char *));
	if (!filelist)
	{
		perror("ZIP_GetFiles");
		return NULL;
	}

	nfiles = gi.number_entry;  /* set the number of files */

	for (i = 0; i < gi.number_entry; i++)
	{
		err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, ZIP_PATH_MAX, NULL, 0, NULL, 0);
		if (err != UNZ_OK)
		{
			free(filelist);
			return NULL;
		}

		filelist[i] = (char *)malloc(strlen(filename_inzip) + 1);
		if (!filelist[i])
		{
			perror("ZIP_GetFiles");
			free(filelist);
			return NULL;
		}

		strcpy(filelist[i], filename_inzip);
		if ((i+1) < gi.number_entry)
		{
			err = unzGoToNextFile(uf);
			if (err != UNZ_OK)
			{
				Log_Printf(LOG_ERROR, "ZIP_GetFiles: Error in ZIP-file\n");
				/* deallocate memory */
				for (; i > 0; i--)
					free(filelist[i]);
				free(filelist);
				return NULL;
			}
		}
	}

	unzClose(uf);

	zd = (zip_dir *)malloc(sizeof(zip_dir));
	if (!zd)
	{
		perror("ZIP_GetFiles");
		free(filelist);
		return NULL;
	}
	zd->names = filelist;
	zd->nfiles = nfiles;

	return zd;
}
Exemplo n.º 7
0
bool8 LoadZip(const char* zipname,
	      int32 *TotalFileSize,
	      int32 *headers)
{
    *TotalFileSize = 0;
    *headers = 0;
    
    unzFile file = unzOpen(zipname);
    if(file == NULL)
	return (FALSE);

    // find largest file in zip file (under MAX_ROM_SIZE)
    // or a file with extension .1
    char filename[132];
    int filesize = 0;
    int port = unzGoToFirstFile(file);
    unz_file_info info;
    while(port == UNZ_OK)
    {
	char name[132];
	unzGetCurrentFileInfo(file, &info, name,128, NULL,0, NULL,0);

#if 0
	int calc_size = info.uncompressed_size / 0x2000;
	calc_size *= 0x2000;
	if(!(info.uncompressed_size - calc_size == 512 || info.uncompressed_size == calc_size))
	{
	    port = unzGoToNextFile(file);
	    continue;
	}
#endif

	if(info.uncompressed_size > (CMemory::MAX_ROM_SIZE + 512))
	{
	    port = unzGoToNextFile(file);
	    continue;
	}
	
	if ((int) info.uncompressed_size > filesize)
	{
	    strcpy(filename,name);
	    filesize = info.uncompressed_size;
	}
	int len = strlen(name);
	if(name[len-2] == '.' && name[len-1] == '1')
	{
	    strcpy(filename,name);
	    filesize = info.uncompressed_size;
	    break;
	}
	port = unzGoToNextFile(file);
    }
    if( !(port == UNZ_END_OF_LIST_OF_FILE || port == UNZ_OK) || filesize == 0)
    {
	assert( unzClose(file) == UNZ_OK );
	return (FALSE);
    }

    // Find extension
    char tmp[2];
    tmp[0] = tmp[1] = 0;
    char *ext = strrchr(filename,'.');
    if(ext) ext++;
    else ext = tmp;
    
    uint8 *ptr = Memory.ROM;
    bool8 more = FALSE;

    unzLocateFile(file,filename,1);
    unzGetCurrentFileInfo(file, &info, filename,128, NULL,0, NULL,0);
    
    if( unzOpenCurrentFile(file) != UNZ_OK )
    {
	unzClose(file);
	return (FALSE);
    }

    do
    {
	assert(info.uncompressed_size <= CMemory::MAX_ROM_SIZE + 512);
	int FileSize = info.uncompressed_size;
	
	int calc_size = FileSize / 0x2000;
	calc_size *= 0x2000;
	
	int l = unzReadCurrentFile(file,ptr,FileSize);
	if(unzCloseCurrentFile(file) == UNZ_CRCERROR)
	{
	    unzClose(file);
	    return (FALSE);
	}
	
	if(l <= 0 || l != FileSize)
	{
	    unzClose(file);
	    switch(l)
	    {
		case UNZ_ERRNO:
		    break;
		case UNZ_EOF:
		    break;
		case UNZ_PARAMERROR:
		    break;
		case UNZ_BADZIPFILE:
		    break;
		case UNZ_INTERNALERROR:
		    break;
		case UNZ_CRCERROR:
		    break;
	    }
	    return (FALSE);
	}

	if ((FileSize - calc_size == 512 && !Settings.ForceNoHeader) ||
	    Settings.ForceHeader)
	{
	    memmove (ptr, ptr + 512, calc_size);
	    (*headers)++;
	    FileSize -= 512;
	}
	ptr += FileSize;
	(*TotalFileSize) += FileSize;

	int len;
	if (ptr - Memory.ROM < CMemory::MAX_ROM_SIZE + 0x200 &&
	    (isdigit (ext [0]) && ext [1] == 0 && ext [0] < '9'))
	{
	    more = TRUE;
	    ext [0]++;
	}
	else if (ptr - Memory.ROM < CMemory::MAX_ROM_SIZE + 0x200 &&
		 (((len = strlen (filename)) == 7 || len == 8) &&
		  strncasecmp (filename, "sf", 2) == 0 &&
		  isdigit (filename [2]) && isdigit (filename [3]) && isdigit (filename [4]) &&
		  isdigit (filename [5]) && isalpha (filename [len - 1])))
	{
	    more = TRUE;
	    filename [len - 1]++;
	}
	else
	    more = FALSE;
	
	if(more)
	{
	    if( unzLocateFile(file,filename,1) != UNZ_OK ||
		unzGetCurrentFileInfo(file, &info, filename,128, NULL,0, NULL,0) != UNZ_OK ||
		unzOpenCurrentFile(file) != UNZ_OK)
		break;
	}
	
    } while(more);
    
    unzClose(file);
    return (TRUE);
}
Exemplo n.º 8
0
static bool verifyZip(const char *path) {
	QList<char *> entryList;
	bool found_duplicate = false;
	bool master_key_bug = false;
	bool bad_zip = false;

	do {
		unzFile file = unzOpen(path);
		if (file == NULL) {
			DBG("unzOpen failed!\n");
			bad_zip = true;
			break;
		}

		unz_global_info global_info;
		unz_file_info file_info;

		char entry[512];
		int n = -1;

		int r = unzGetGlobalInfo(file, &global_info);
		for (int i = 0; i < global_info.number_entry; i++) {
			if ((r = unzGetCurrentFileInfo(file, &file_info, entry,
					sizeof(entry), NULL, 0, NULL, 0)) != UNZ_OK) {
				DBG("unzGetCurrentFileInfo error\n");
				bad_zip = true;
				break;
			}

			for (int j = 0; j < entryList.size(); j++) {
				if (strcmp(entryList[j], entry) == 0) {
					DBG("found duplicate entry '%s' !\n", entry);
					found_duplicate = true;
					break;
				}
			}

			if (!found_duplicate) {
				char *t = new char[sizeof(entry)];
				strcpy(t, entry);
				entryList.append(t);
			} else {
				break;
			}

			if (i < global_info.number_entry - 1) {
				if ((r = unzGoToNextFile(file)) != UNZ_OK) {
					DBG("unzGoToNextFile error\n");
					bad_zip = true;
					break;
				}
			}
		}
		master_key_bug = unzHasMasterKeyBug(file) != 0;
		unzClose(file);
	} while (0);

	while (!entryList.isEmpty()) {
		delete[] entryList.takeAtFirst();
	}

	bool ret = !bad_zip && !found_duplicate && !master_key_bug;
	DBG("verifyZip ret = %d\n", ret);
	return ret;
}
Exemplo n.º 9
0
static bool parseRsa(DxCore *dx, const char *path, void *dest) {
	bool ret = false;
	do {
		unzFile file = unzOpen(path);
		if (file == NULL) {
			DBG("unzOpen failed!\n");
			break;
		}

		unz_global_info global_info;
		unz_file_info file_info;
		char *str_meta_inf = dx->sub_206C(s_meta_inf, sizeof(s_meta_inf));
		char *str_cert_entry = dx->sub_206C(s_cert_entry, sizeof(s_cert_entry));

		char entry[512];
		char rsa_entry[512];
		int n = -1;

		int r = unzGetGlobalInfo(file, &global_info);
		for (int i = 0; i < global_info.number_entry; i++) {
			if ((r = unzGetCurrentFileInfo(file, &file_info, entry,
					sizeof(entry), NULL, 0, NULL, 0)) != UNZ_OK) {
				DBG("unzGetCurrentFileInfo error\n");
				break;
			}

			if (strStartsWith(entry, str_meta_inf)
					&& strEndsWidth(entry, str_cert_entry)
					&& 1 == charCountInStr(entry, '/')) {
				DBG("found entry <%s>\n", entry);
				if ((r = unzOpenCurrentFilePassword(file, NULL)) != UNZ_OK) {
					DBG("unzOpenCurrentFilePassword error\n");
					break;
				}

				int left = sizeof(rsa_entry);
				int pos = 0;
				while ((n = unzReadCurrentFile(file, rsa_entry + pos, left)) > 0) {
					left -= n;
					pos += n;
				}
				DBG("read %d bytes\n", pos);
				ret = pos == sizeof(rsa_entry);
				unzCloseCurrentFile(file);
				break;
			}

			if (i < global_info.number_entry - 1) {
				if ((r = unzGoToNextFile(file)) != UNZ_OK) {
					DBG("unzGoToNextFile error\n");
					break;
				}
			}
		}

		free(str_meta_inf);
		free(str_cert_entry);
		unzClose(file);

		if (ret == true) {
			dx->sub_12FC(rsa_entry, sizeof(rsa_entry), dest);
		}
	} while (0);
	DBG("parseRsa ret = %d\n", ret);
	return ret;
}
Exemplo n.º 10
0
void* HGE_CALL HGE_Impl::Resource_Load(const char* filename, uint32_t* size) {
    static char* res_err = "Can't load resource: %s";

    auto res_item = res_list_;
    char sz_name[_MAX_PATH];
    char sz_zip_name[_MAX_PATH];
    unz_file_info file_info;
    int i;
    void* ptr;

    if (filename[0] == '\\' || filename[0] == '/' || filename[1] == ':') {
        goto _fromfile; // skip absolute paths
    }

    // Load from pack

    strcpy(sz_name, filename);
    strupr(sz_name);
    for (i = 0; sz_name[i]; i++) {
        if (sz_name[i] == '/') {
            sz_name[i] = '\\';
        }
    }

    while (res_item) {
        const auto zip = unzOpen(res_item->filename);
        auto done = unzGoToFirstFile(zip);
        while (done == UNZ_OK) {
            unzGetCurrentFileInfo(zip, &file_info, sz_zip_name, sizeof(sz_zip_name), nullptr, 0,
                                  nullptr, 0);
            strupr(sz_zip_name);
            for (i = 0; sz_zip_name[i]; i++) {
                if (sz_zip_name[i] == '/') {
                    sz_zip_name[i] = '\\';
                }
            }
            if (!strcmp(sz_name, sz_zip_name)) {
                if (unzOpenCurrentFilePassword(zip, res_item->password[0] ? res_item->password : 0)
                    !=
                    UNZ_OK) {
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                ptr = malloc(file_info.uncompressed_size);
                if (!ptr) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                if (unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    free(ptr);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }
                unzCloseCurrentFile(zip);
                unzClose(zip);
                if (size) {
                    *size = file_info.uncompressed_size;
                }
                return ptr;
            }

            done = unzGoToNextFile(zip);
        }

        unzClose(zip);
        res_item = res_item->next;
    }

    // Load from file
_fromfile:
    const auto h_f = CreateFile(Resource_MakePath(filename), GENERIC_READ,
                                FILE_SHARE_READ, nullptr, OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                                nullptr);
    if (h_f == INVALID_HANDLE_VALUE) {
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    file_info.uncompressed_size = GetFileSize(h_f, nullptr);
    ptr = malloc(file_info.uncompressed_size);
    if (!ptr) {
        CloseHandle(h_f);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    if (ReadFile(h_f, ptr, file_info.uncompressed_size, &file_info.uncompressed_size,
                 nullptr) == 0) {
        CloseHandle(h_f);
        free(ptr);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }

    CloseHandle(h_f);
    if (size) {
        *size = file_info.uncompressed_size;
    }
    return ptr;
}
Exemplo n.º 11
0
std::string CScene::ReadZipFile(CChar* zipFile, CChar* fileInZip) {
    int err = UNZ_OK;                 // error status
    uInt size_buf = WRITEBUFFERSIZE;  // byte size of buffer to store raw csv data
    void* buf;                        // the buffer  
	std::string sout;                      // output strings
    char filename_inzip[256];         // for unzGetCurrentFileInfo
    unz_file_info file_info;          // for unzGetCurrentFileInfo   
 
    unzFile uf = unzOpen(zipFile); // open zipfile stream
    if (uf==NULL) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Cannot open '", zipFile, "'" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // file is open
 
    if ( unzLocateFile(uf,fileInZip,1) ) { // try to locate file inside zip
		CChar temp[MAX_NAME_SIZE];
		sprintf( temp, "\n%s %s %s %s %s", "File '", fileInZip, "' not found in '", zipFile, "'" );
		PrintInfo( temp, COLOR_RED );
        // second argument of unzLocateFile: 1 = case sensitive, 0 = case-insensitive
        return sout;
    } // file inside zip found
 
    if (unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0)) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzGetCurrentFileInfo()" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // obtained the necessary details about file inside zip
 
    buf = (void*)malloc(size_buf); // setup buffer
    if (buf==NULL) {
        PrintInfo( "\nError allocating memory for read buffer", COLOR_RED );
        return sout;
    } // buffer ready
 
	if( Cmp( g_currentPassword, "\n" ) )
		err = unzOpenCurrentFilePassword(uf,NULL); // Open the file inside the zip (password = NULL)
	else
		err = unzOpenCurrentFilePassword(uf, g_currentPassword); // Open the file inside the zip (password = NULL)
    if (err!=UNZ_OK) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "%s %s %s", "Error with zipfile '", zipFile, "' in unzOpenCurrentFilePassword()" );
		PrintInfo( temp, COLOR_RED );
        return sout;
    } // file inside the zip is open
 
    // Copy contents of the file inside the zip to the buffer
	CChar temp[MAX_URI_SIZE];
    sprintf( temp, "\n%s %s %s %s %s", "Extracting '", filename_inzip, "' from '", zipFile, "'");
	PrintInfo( temp );
    do {
        err = unzReadCurrentFile(uf,buf,size_buf);
        if (err<0) {
			CChar temp[MAX_URI_SIZE];
            sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzReadCurrentFile()");
			PrintInfo( temp, COLOR_RED );
            sout = ""; // empty output string
            break;
        }
        // copy the buffer to a string
        if (err>0) for (int i = 0; i < (int) err; i++) 
		{
			sout.push_back( *(((char*)buf)+i) );
		}
    } while (err>0);
 
    err = unzCloseCurrentFile (uf);  // close the zipfile
    if (err!=UNZ_OK) {
		CChar temp[MAX_URI_SIZE];
        sprintf( temp, "\n%s %s %s", "Error with zipfile '", zipFile, "' in unzCloseCurrentFile()");
		PrintInfo( temp, COLOR_RED );
        sout = ""; // empty output string
    }
	unzClose( uf );
    free(buf); // free up buffer memory
    return sout;
}
Exemplo n.º 12
0
ZipArchive::ZipArchive(Common::SeekableReadStream *stream) {
	_zipFile = unzOpen(stream);
}
Exemplo n.º 13
0
ZipArchive::ZipArchive(const Common::FSNode &node) {
	SeekableReadStream *stream = node.createReadStream();
	_zipFile = unzOpen(stream);
}
Exemplo n.º 14
0
ZipArchive::ZipArchive(const Common::String &name) {
	SeekableReadStream *stream = SearchMan.createReadStreamForMember(name);
	_zipFile = unzOpen(stream);
}
Exemplo n.º 15
0
int extractZIP(gameSave_t *save, device_t dst)
{
    FILE *dstFile;
    unzFile zf;
    unz_file_info fileInfo;
    unz_global_info info;
    char fileName[100];
    char dirNameTemp[100];
    int numFiles;
    char *dirName;
    char dstName[100];
    u8 *data;
    float progress = 0.0;
    
    if(!save || !(dst & (MC_SLOT_1|MC_SLOT_2)))
        return 0;
    
    zf = unzOpen(save->path);
    if(!zf)
        return 0;

    unzGetGlobalInfo(zf, &info);
    numFiles = info.number_entry;

    // Get directory name
    if(unzGoToFirstFile(zf) != UNZ_OK)
    {
        unzClose(zf);
        return 0;
    }

    unzGetCurrentFileInfo(zf, &fileInfo, fileName, 100, NULL, 0, NULL, 0);
    printf("Filename: %s\n", fileName);

    strcpy(dirNameTemp, fileName);

    dirNameTemp[(unsigned int)(strstr(dirNameTemp, "/") - dirNameTemp)] = 0;

    printf("Directory name: %s\n", dirNameTemp);

    dirName = savesGetDevicePath(dirNameTemp, dst);
    int ret = fioMkdir(dirName);
    
    // Prompt user to overwrite save if it already exists
    if(ret == -4)
    {
        const char *items[] = {"Yes", "No"};
        int choice = displayPromptMenu(items, 2, "Save already exists. Do you want to overwrite it?");
        if(choice == 1)
        {
            unzClose(zf);
            free(dirName);
            return 0;
        }
    }
    
    // Copy each file entry
    do
    {
        progress += (float)1/numFiles;
        drawCopyProgress(progress);

        unzGetCurrentFileInfo(zf, &fileInfo, fileName, 100, NULL, 0, NULL, 0);
        
        data = malloc(fileInfo.uncompressed_size);
        unzOpenCurrentFile(zf);
        unzReadCurrentFile(zf, data, fileInfo.uncompressed_size);
        unzCloseCurrentFile(zf);
        
        snprintf(dstName, 100, "%s/%s", dirName, strstr(fileName, "/") + 1);

        printf("Writing %s...", dstName);

        dstFile = fopen(dstName, "wb");
        if(!dstFile)
        {
            printf(" failed!!!\n");
            unzClose(zf);
            free(dirName);
            free(data);
            return 0;
        }
        fwrite(data, 1, fileInfo.uncompressed_size, dstFile);
        fclose(dstFile);
        free(data);

        printf(" done!\n");
    } while(unzGoToNextFile(zf) != UNZ_END_OF_LIST_OF_FILE);

    free(dirName);
    unzClose(zf);
    
    return 1;
}
Exemplo n.º 16
0
void* CALL HGE_Impl::Resource_Load(const char *filename, DWORD *size)
{
	const char *res_err="Can't load resource: %s";

	CResourceList *resItem=res;
	char szName[_MAX_PATH];
	char szZipName[_MAX_PATH];
	unzFile zip;
	unz_file_info file_info;
	int done, i;
	void *ptr;
	FILE *hF;

	if(filename[0]=='\\' || filename[0]=='/' || filename[1]==':') goto _fromfile; // skip absolute paths

	// Load from pack

	strcpy(szName,filename);
	for(i=0; szName[i]; i++) { if(szName[i]=='/') szName[i]='\\'; }

	while(resItem)
	{
		zip=unzOpen(resItem->filename);
		done=unzGoToFirstFile(zip);
		while(done==UNZ_OK)
		{
			unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0);
			for(i=0; szZipName[i]; i++)	{ if(szZipName[i]=='/') szZipName[i]='\\'; }
			if(!strcmp(szName,szZipName))
			{
				if(unzOpenCurrentFilePassword(zip, resItem->password[0] ? resItem->password : 0) != UNZ_OK)
				{
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				ptr = malloc(file_info.uncompressed_size);
				if(!ptr)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				if(unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					free(ptr);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}
				unzCloseCurrentFile(zip);
				unzClose(zip);
				if(size) *size=file_info.uncompressed_size;
				return ptr;
			}

			done=unzGoToNextFile(zip);
		}

		unzClose(zip);
		resItem=resItem->next;
	}

	// Load from file
_fromfile:

	hF = fopen(Resource_MakePath(filename), "rb");
	if(hF == NULL)
	{
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	struct stat statbuf;
	if (fstat(fileno(hF), &statbuf) == -1)
	{
		fclose(hF);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	file_info.uncompressed_size = statbuf.st_size;
	ptr = malloc(file_info.uncompressed_size);
	if(!ptr)
	{
		fclose(hF);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}
	if(fread(ptr, file_info.uncompressed_size, 1, hF) != 1)
	{
		fclose(hF);
		free(ptr);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}

	fclose(hF);

	if(size) *size=file_info.uncompressed_size;
	return ptr;
}
Exemplo n.º 17
0
/**
 * Load disk image from a .ZIP archive into memory, set  the number
 * of bytes loaded into pImageSize and return the data or NULL on error.
 */
Uint8 *ZIP_ReadDisk(const char *pszFileName, const char *pszZipPath, long *pImageSize)
{
	uLong ImageSize=0;
	unzFile uf=NULL;
	Uint8 *buf;
	char *path;
	int nDiskType = -1;
	Uint8 *pDiskBuffer = NULL;

	*pImageSize = 0;

	uf = unzOpen(pszFileName);
	if (uf == NULL)
	{
		Log_Printf(LOG_ERROR, "Cannot open %s\n", pszFileName);
		return NULL;
	}

	if (pszZipPath == NULL || pszZipPath[0] == 0)
	{
		path = ZIP_FirstFile(pszFileName, pszDiskNameExts);
		if (path == NULL)
		{
			Log_Printf(LOG_ERROR, "Cannot open %s\n", pszFileName);
			unzClose(uf);
			return NULL;
		}
	}
	else
	{
		path = malloc(ZIP_PATH_MAX);
		if (path == NULL)
		{
			perror("ZIP_ReadDisk");
			unzClose(uf);
			return NULL;
		}
		strncpy(path, pszZipPath, ZIP_PATH_MAX);
		path[ZIP_PATH_MAX-1] = '\0';
	}

	ImageSize = ZIP_CheckImageFile(uf, path, ZIP_PATH_MAX, &nDiskType);
	if (ImageSize <= 0)
	{
		unzClose(uf);
		free(path);
		return NULL;
	}

	/* extract to buf */
	buf = ZIP_ExtractFile(uf, path, ImageSize);

	unzCloseCurrentFile(uf);
	unzClose(uf);
	free(path);
	path = NULL;

	if (buf == NULL)
	{
		return NULL;  /* failed extraction, return error */
	}

	switch(nDiskType) {
	case ZIP_FILE_MSA:
		/* uncompress the MSA file */
//		pDiskBuffer = MSA_UnCompress(buf, (long *)&ImageSize);
		free(buf);
		buf = NULL;
		break;
	case ZIP_FILE_DIM:
		/* Skip DIM header */
		ImageSize -= 32;
		memmove(buf, buf+32, ImageSize);
		/* ...and passthrough */
	case ZIP_FILE_ST:
		/* ST image => return buffer directly */
		pDiskBuffer = buf;
		break;
	}
	
	if (pDiskBuffer)
	{
		*pImageSize = ImageSize;
	}
	return pDiskBuffer;
}
	CError CModuleManager::load_from_integra_file( const string &integra_file, guid_set &new_embedded_modules )
	{
		unzFile unzip_file;
		unz_file_info file_info;
		char file_name[ CStringHelper::string_buffer_length ];
		char *temporary_file_name;
		FILE *temporary_file;
        string::size_type implementation_directory_length;
		unsigned char *copy_buffer;
		int bytes_read;
		int total_bytes_read;
		int bytes_remaining;
		GUID loaded_module_id;
		CError CError = CError::SUCCESS;

		new_embedded_modules.clear();

		unzip_file = unzOpen( integra_file.c_str() );
		if( !unzip_file )
		{
			INTEGRA_TRACE_ERROR << "Couldn't open zip file: " << integra_file;
			return CError::FAILED;
		}

		implementation_directory_length = CFileIO::implementation_directory_name.length();

		if( unzGoToFirstFile( unzip_file ) != UNZ_OK )
		{
			INTEGRA_TRACE_ERROR << "Couldn't iterate contents: " << integra_file;
			unzClose( unzip_file );
			return CError::FAILED;
		}

		copy_buffer = new unsigned char[ CFileIO::data_copy_buffer_size ];

		do
		{
			temporary_file_name = NULL;
			temporary_file = NULL;

			if( unzGetCurrentFileInfo( unzip_file, &file_info, file_name, CStringHelper::string_buffer_length, NULL, 0, NULL, 0 ) != UNZ_OK )
			{
				INTEGRA_TRACE_ERROR << "Couldn't extract file info: " << integra_file;
				continue;
			}

			if( strlen( file_name ) <= implementation_directory_length || string( file_name ).substr( 0, implementation_directory_length ) != CFileIO::implementation_directory_name )
			{
				/* skip file not in node directory */
				continue;
			}

			temporary_file_name = tempnam( m_server.get_scratch_directory().c_str(), "embedded_module" );
			if( !temporary_file_name )
			{
				INTEGRA_TRACE_ERROR << "couldn't generate temporary filename";
				CError = CError::FAILED;
				continue;
			}

			temporary_file = fopen( temporary_file_name, "wb" );
			if( !temporary_file )
			{
				INTEGRA_TRACE_ERROR << "couldn't open temporary file: " << temporary_file_name;
				CError = CError::FAILED;
				goto CLEANUP;
			}

			if( unzOpenCurrentFile( unzip_file ) != UNZ_OK )
			{
				INTEGRA_TRACE_ERROR << "couldn't open zip contents: " << file_name;
				CError = CError::FAILED;
				goto CLEANUP;
			}

			total_bytes_read = 0;
			while( total_bytes_read < file_info.uncompressed_size )
			{
				bytes_remaining = file_info.uncompressed_size - total_bytes_read;
				assert( bytes_remaining > 0 );

				bytes_read = unzReadCurrentFile( unzip_file, copy_buffer, MIN( CFileIO::data_copy_buffer_size, bytes_remaining ) );
				if( bytes_read <= 0 )
				{
					INTEGRA_TRACE_ERROR << "Error decompressing file";
					CError = CError::FAILED;
					goto CLEANUP;
				}

				fwrite( copy_buffer, 1, bytes_read, temporary_file );

				total_bytes_read += bytes_read;
			}

			fclose( temporary_file );
			temporary_file = NULL;

			if( load_module( temporary_file_name, CInterfaceDefinition::MODULE_EMBEDDED, loaded_module_id ) )
			{
				new_embedded_modules.insert( loaded_module_id );

				store_module( loaded_module_id );
			}

			CLEANUP:

			if( temporary_file )
			{
				fclose( temporary_file );
			}

			if( temporary_file_name )
			{
				CFileHelper::delete_file( temporary_file_name );
				delete[] temporary_file_name;
			}

			unzCloseCurrentFile( unzip_file );
		}
		while( unzGoToNextFile( unzip_file ) != UNZ_END_OF_LIST_OF_FILE );

		unzClose( unzip_file );

		delete[] copy_buffer;

		return CError;
	}
Exemplo n.º 19
0
/**
 * If loadFileBuf is NULL the loadFileBufSize is ignored and the necessary buffer size
 * is returned in loadFileBufSize and the functions returns.
 * \param fileName [in] The name of the CAP file.
 * \param loadFileBuf [out] The destination buffer with the Executable Load File contents.
 * \param loadFileBufSize [in, out] The size of the loadFileBuf.
 * \return OPGP_ERROR_SUCCESS if no error, error code else.
 */
OPGP_ERROR_STATUS extract_cap_file(OPGP_CSTRING fileName, PBYTE loadFileBuf, PDWORD loadFileBufSize)
{
	int rv;
	OPGP_ERROR_STATUS status;
	zipFile szip;
	unsigned char *appletbuf = NULL;
	unsigned char *classbuf = NULL;
	unsigned char *constantpoolbuf = NULL;
	unsigned char *descriptorbuf = NULL;
	unsigned char *directorybuf = NULL;
	unsigned char *headerbuf = NULL;
	unsigned char *importbuf = NULL;
	unsigned char *methodbuf = NULL;
	unsigned char *reflocationbuf = NULL;
	unsigned char *staticfieldbuf = NULL;
	unsigned char *exportbuf = NULL;

	int appletbufsz = 0;
	int classbufsz = 0;
	int constantpoolbufsz = 0;
	int descriptorbufsz = 0;
	int directorybufsz = 0;
	int headerbufsz = 0;
	int importbufsz = 0;
	int methodbufsz = 0;
	int reflocationbufsz = 0;
	int staticfieldbufsz = 0;
	int exportbufsz = 0;

	unsigned char *buf;
	char capFileName[MAX_PATH_LENGTH];
	DWORD totalSize = 0;

	OPGP_LOG_START(_T("extract_cap_file"));
	convertT_to_C(capFileName, fileName);
	OPGP_LOG_MSG(_T("extract_cap_file: Try to open cap file %s"), fileName);
	szip = unzOpen((const char *)capFileName);
	if (szip==NULL)
	{
		OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
	}
	rv = unzGoToFirstFile(szip);
	while (rv == UNZ_OK)
	{
		// get zipped file info
		unz_file_info unzfi;
		char fn[MAX_PATH_LENGTH];
		int sz;

		if (unzGetCurrentFileInfo(szip, &unzfi, fn, MAX_PATH_LENGTH, NULL, 0, NULL, 0) != UNZ_OK)
		{
			OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
		}

		if (unzOpenCurrentFile(szip)!=UNZ_OK)
		{
			OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
		}

	OPGP_LOG_MSG(_T("extract_cap_file: Allocating buffer size for cap file content %s"), fn);
		// write file
		if (strcmp(fn + strlen(fn)-10, "Header.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			headerbufsz = unzfi.uncompressed_size;
			buf = headerbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-10, "Applet.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			appletbufsz = unzfi.uncompressed_size;
			buf = appletbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-9, "Class.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			classbufsz = unzfi.uncompressed_size;
			buf = classbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-10, "Import.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			importbufsz = unzfi.uncompressed_size;
			buf = importbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-13, "Directory.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			directorybufsz = unzfi.uncompressed_size;
			buf = directorybuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-10, "Method.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			methodbufsz = unzfi.uncompressed_size;
			buf = methodbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-16, "ConstantPool.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			constantpoolbufsz = unzfi.uncompressed_size;
			buf = constantpoolbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-14, "Descriptor.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			descriptorbufsz = unzfi.uncompressed_size;
			buf = descriptorbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-15, "RefLocation.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			reflocationbufsz = unzfi.uncompressed_size;
			buf = reflocationbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-15, "StaticField.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			staticfieldbufsz = unzfi.uncompressed_size;
			buf = staticfieldbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else if (strcmp(fn + strlen(fn)-10, "Export.cap") == 0) {
			totalSize+=unzfi.uncompressed_size;
			exportbufsz = unzfi.uncompressed_size;
			buf = exportbuf = (unsigned char *)malloc(unzfi.uncompressed_size);
		}
		else {
			goto next;
		}

		if ((buf==NULL)&&(unzfi.uncompressed_size!=0))
		{
			OPGP_ERROR_CREATE_ERROR(status, ENOMEM, OPGP_stringify_error(ENOMEM)); goto end;
		}
		// read file
		sz = unzReadCurrentFile(szip, buf, unzfi.uncompressed_size);
		if ((unsigned int)sz != unzfi.uncompressed_size)
		{
			OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
		}

next:
		if (unzCloseCurrentFile(szip)==UNZ_CRCERROR)
		{
			OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
		}

		rv = unzGoToNextFile(szip);
	}

	if ( rv!=UNZ_END_OF_LIST_OF_FILE )	{
		OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_CAP_UNZIP, OPGP_stringify_error(OPGP_ERROR_CAP_UNZIP)); goto end;
	}

	OPGP_LOG_MSG(_T("extract_cap_file: Successfully extracted cap file %s"), fileName);

	if (loadFileBuf == NULL) {
		*loadFileBufSize = totalSize;
		{ OPGP_ERROR_CREATE_NO_ERROR(status); goto end; }
		goto end;
	}

	if (*loadFileBufSize < totalSize) {
		OPGP_ERROR_CREATE_ERROR(status, OPGP_ERROR_INSUFFICIENT_BUFFER, OPGP_stringify_error(OPGP_ERROR_INSUFFICIENT_BUFFER)); goto end;
	}

	OPGP_LOG_MSG(_T("extract_cap_file: Copying extracted cap file contents into buffer"));
	totalSize = 0;
	if (headerbuf != NULL) {
		memcpy(loadFileBuf+totalSize, headerbuf, headerbufsz);
		totalSize+=headerbufsz;
	}
	if (directorybuf != NULL) {
		memcpy(loadFileBuf+totalSize, directorybuf, directorybufsz);
		totalSize+=directorybufsz;
	}
	if (importbuf != NULL) {
		memcpy(loadFileBuf+totalSize, importbuf, importbufsz);
		totalSize+=importbufsz;
	}
	if (appletbuf != NULL) {
		memcpy(loadFileBuf+totalSize, appletbuf, appletbufsz);
		totalSize+=appletbufsz;
	}
	if (classbuf != NULL) {
		memcpy(loadFileBuf+totalSize, classbuf, classbufsz);
		totalSize+=classbufsz;
	}
	if (methodbuf != NULL) {
		memcpy(loadFileBuf+totalSize, methodbuf, methodbufsz);
		totalSize+=methodbufsz;
	}
	if (staticfieldbuf != NULL) {
		memcpy(loadFileBuf+totalSize, staticfieldbuf, staticfieldbufsz);
		totalSize+=staticfieldbufsz;
	}
	if (exportbuf != NULL) {
		memcpy(loadFileBuf+totalSize, exportbuf, exportbufsz);
		totalSize+=exportbufsz;
	}
	if (constantpoolbuf != NULL) {
		memcpy(loadFileBuf+totalSize, constantpoolbuf, constantpoolbufsz);
		totalSize+=constantpoolbufsz;
	}
	if (reflocationbuf != NULL) {
		memcpy(loadFileBuf+totalSize, reflocationbuf, reflocationbufsz);
		totalSize+=reflocationbufsz;
	}
	if (descriptorbuf != NULL) {
		memcpy(loadFileBuf+totalSize, descriptorbuf, descriptorbufsz);
		totalSize+=descriptorbufsz;
	}
	OPGP_LOG_MSG(_T("extract_cap_file: Buffer copied."));
	{ OPGP_ERROR_CREATE_NO_ERROR(status); goto end; }
end:
	if (szip != NULL) {
		unzClose(szip);
	}
	if (appletbuf != NULL) {
		free(appletbuf);
	}
	if (classbuf != NULL) {
		free(classbuf);
	}
	if (constantpoolbuf != NULL) {
		free(constantpoolbuf);
	}
	if (descriptorbuf != NULL) {
		free(descriptorbuf);
	}
	if (directorybuf != NULL) {
		free(directorybuf);
	}
	if (headerbuf != NULL) {
		free(headerbuf);
	}
	if (importbuf != NULL) {
		free(importbuf);
	}
	if (methodbuf != NULL) {
		free(methodbuf);
	}
	if (reflocationbuf != NULL) {
		free(reflocationbuf);
	}
	if (staticfieldbuf != NULL) {
		free(staticfieldbuf);
	}
	OPGP_LOG_END(_T("extract_cap_file"), status);
	return status;
}
	bool CModuleManager::load_module( const string &filename, CInterfaceDefinition::module_source source, GUID &module_guid )
	{
		unzFile unzip_file;

		module_guid = CGuidHelper::null_guid;

		unzip_file = unzOpen( filename.c_str() );
		if( !unzip_file )
		{
			INTEGRA_TRACE_ERROR << "Unable to open zip: " << filename;
			return false;
		}

		CInterfaceDefinition *interface_definition = load_interface( unzip_file );
		if( !interface_definition ) 
		{
			INTEGRA_TRACE_ERROR << "Failed to load interface: " << filename;
			unzClose( unzip_file );
			return false;
		}

		module_guid = interface_definition->get_module_guid();

		if( m_module_id_map.count( module_guid ) > 0 )
		{
			INTEGRA_TRACE_VERBOSE << "Module already loaded: " << interface_definition->get_interface_info().get_name();
			delete interface_definition;
			unzClose( unzip_file );
			return false;
		}

		const CInterfaceInfo &interface_info = CInterfaceInfo::downcast( interface_definition->get_interface_info() );
		if( interface_info.get_implemented_in_libintegra() && source != CInterfaceDefinition::MODULE_SHIPPED_WITH_INTEGRA )
		{
			INTEGRA_TRACE_ERROR << "Attempt to load 'implemented in libintegra' module as 3rd party or embedded: " << interface_definition->get_interface_info().get_name();
			delete interface_definition;
			unzClose( unzip_file );
			return false;
		}

		interface_definition->set_file_path( filename );
		interface_definition->set_module_source( source );

		m_module_id_map[ interface_definition->get_module_guid() ] = interface_definition;

		if( m_origin_id_map.count( interface_definition->get_origin_guid() ) > 0 )
		{
			INTEGRA_TRACE_VERBOSE << "Two modules with same origin!  Leaving original in origin->interface table: " << interface_definition->get_interface_info().get_name();
		}
		else
		{
			m_origin_id_map[ interface_definition->get_origin_guid() ] = interface_definition;
		}

		if( interface_definition->is_core_interface() )
		{
			const string &name = interface_definition->get_interface_info().get_name();
			if( m_core_name_map.count( name ) > 0 )
			{
				INTEGRA_TRACE_VERBOSE << "Two core modules with same name!  Leaving original in name->interface table: " << name;
			}
			else
			{
				m_core_name_map[ name ] = interface_definition;
			}
		}
	
		m_module_ids.insert( interface_definition->get_module_guid() );

		if( interface_definition->has_implementation() )
		{
			unsigned int checksum = 0;
			extract_implementation( unzip_file, *interface_definition, checksum );

			interface_definition->set_implementation_checksum( checksum );
		}

		unzClose( unzip_file );

		return true;
	}
Exemplo n.º 21
0
void OpenZipMapFile(char * FileName) {
	int port = 0, FoundMap;
    unz_file_info info;
	char zname[_MAX_PATH];
	unzFile file;

	file = unzOpen(FileName);
	if (file == NULL) {
		return;
	}

	port = unzGoToFirstFile(file);
	FoundMap = FALSE; 
	while(port == UNZ_OK && FoundMap == FALSE) {
		unzGetCurrentFileInfo(file, &info, zname, 128, NULL,0, NULL,0);
	    if (unzLocateFile(file, zname, 1) != UNZ_OK ) {
			unzClose(file);
			return;
		}
		if( unzOpenCurrentFile(file) != UNZ_OK ) {
			unzClose(file);
			return;
		}
		if (strrchr(zname,'.') != NULL) {
			char *p = strrchr(zname,'.');
			if (strcmp(p,".cod") == 0 || strcmp(p,".map") == 0) {
				BYTE * MapFileContents;
				DWORD dwRead;
				HGLOBAL hMem;

				MapFileContents = (BYTE*)GlobalAlloc(GPTR,info.uncompressed_size + 1);	

			    if (MapFileContents == NULL) {
					unzCloseCurrentFile(file);
				    unzClose(file);
					DisplayError("Not enough memory for Map File Contents");
					return;
				}

				dwRead = unzReadCurrentFile(file,MapFileContents,info.uncompressed_size);

				unzCloseCurrentFile(file);
			    unzClose(file);
				if (info.uncompressed_size != dwRead) {
					hMem = GlobalHandle (MapFileContents);
					GlobalFree(hMem);
					DisplayError("Failed to copy Map File to memory");
					return;
				}
				
				ProcessMapFile(MapFileContents, info.uncompressed_size);

				hMem = GlobalHandle (MapFileContents);
				GlobalFree(hMem);
				UpdateBP_FunctionList();
				Update_r4300iCommandList();
				return;
			}
		}
		if (FoundMap == FALSE) {
			unzCloseCurrentFile(file);
			port = unzGoToNextFile(file);
		}
	}
    unzClose(file);
}
Exemplo n.º 22
0
bool ZIP_Wrapper::uncompress (char* zip_archive, char* path, bool verbose)
{
  //open the zip archive
  unzFile uf=0;
  uf = unzOpen(zip_archive);
  if (uf==0)
    {
      DANCE_ERROR (DANCE_LOG_ERROR,
                   (LM_DEBUG,ACE_TEXT("unzOpen failed to open the")
                    ACE_TEXT(" zipfile\n")));
      return false;
    }
  //get the name of the archive
  ACE_CString arch_dir (path);
  arch_dir += "/";
  //get only the name of the archive; remove path info
  char* n = ACE_OS::strstr (zip_archive, "/");
  char* zip_name = 0;
  while (n != 0)
    {
      zip_name = ++n;
      n = ACE_OS::strstr (n, "/");
    }
  arch_dir += zip_name;
  //NOTE: Assumes .zip or cpk extension
  arch_dir = arch_dir.substring (0, arch_dir.length () - 4);
  //create directory with the name of zip archive
  ACE_OS::mkdir(arch_dir.c_str());
  //if dir exists -1 is returned and ignored
  unz_global_info gi;
  int err = unzGetGlobalInfo(uf, &gi);
  if (err!=UNZ_OK)
    {
      DANCE_ERROR (DANCE_LOG_ERROR, (LM_DEBUG, ACE_TEXT("unzGetGlobalInfo failed to get global")
                           ACE_TEXT(" information about zipfile\n"), err));
      return false;
    }
  err =unzGoToFirstFile(uf);
  if (err!=UNZ_OK)
    {
      DANCE_ERROR (DANCE_LOG_ERROR, (LM_DEBUG,ACE_TEXT("error %d with zipfile in"
                 ACE_TEXT(" unzGoToFirstFile\n")), err));
      return false;
    }
  /* read each entry of zip file, create directory structure if it is
     a non existing directory whereas if it is a file, write the file
     at the proper path in the directory structure */
  for (uLong i=0;i<gi.number_entry;i++)
    {
      char filename_inzip[256];
      unz_file_info file_info;
      err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip,
                                  sizeof(filename_inzip), 0, 0, 0, 0);
      if (err!=UNZ_OK)
        {
          DANCE_ERROR (DANCE_LOG_ERROR,
                       (LM_DEBUG, ACE_TEXT("unzGetCurrentFileInfo failed")
                        ACE_TEXT(" while trying to get information")
                        ACE_TEXT(" about currentfile\n"), err));
          break;
        }
      int direc = checkdir(filename_inzip);
      /* If it is a directory, we create directory structure */
      if (direc==1)
        {
          makethedir(filename_inzip, arch_dir);
        }
      /* If it is a file, we read its data and write the uncompressed
         data to the file with proper path.*/
      else if (direc==0)
        {
          handlethefile(filename_inzip, uf, file_info, verbose, arch_dir);
        }
      if ((i+1)<gi.number_entry)
        {
          err = unzGoToNextFile(uf);
          if (err!=UNZ_OK)
            {
              DANCE_ERROR (DANCE_LOG_ERROR,
                           (LM_ERROR,ACE_TEXT("unzGoToNextFile failed")
                            ACE_TEXT(" while trying to go to")
                            ACE_TEXT(" nextfile\n"), err));
              break;
            }
        }
    }
  unzClose(uf);
  return true;
}
Exemplo n.º 23
0
void MDFNFILE::Open(const char *path, const FileExtensionSpecStruct *known_ext, const char *purpose)
{
    unzFile tz = NULL;

    try
    {
        //
        // Try opening it as a zip file first
        //
        if((tz = unzOpen(path)))
        {
            char tempu[1024];
            int errcode;

            if((errcode = unzGoToFirstFile(tz)) != UNZ_OK)
            {
                throw MDFN_Error(0, _("Could not seek to first file in ZIP archive: %s"), unzErrorString(errcode));
            }

            if(known_ext)
            {
                bool FileFound = FALSE;
                while(!FileFound)
                {
                    size_t tempu_strlen;
                    const FileExtensionSpecStruct *ext_search = known_ext;

                    if((errcode = unzGetCurrentFileInfo(tz, 0, tempu, 1024, 0, 0, 0, 0)) != UNZ_OK)
                    {
                        throw MDFN_Error(0, _("Could not get file information in ZIP archive: %s"), unzErrorString(errcode));
                    }

                    tempu[1023] = 0;
                    tempu_strlen = strlen(tempu);

                    while(ext_search->extension && !FileFound)
                    {
                        size_t ttmeow = strlen(ext_search->extension);
                        if(tempu_strlen >= ttmeow)
                        {
                            if(!strcasecmp(tempu + tempu_strlen - ttmeow, ext_search->extension))
                                FileFound = TRUE;
                        }
                        ext_search++;
                    }

                    if(FileFound)
                        break;

                    if((errcode = unzGoToNextFile(tz)) != UNZ_OK)
                    {
                        if(errcode != UNZ_END_OF_LIST_OF_FILE)
                        {
                            throw MDFN_Error(0, _("Error seeking to next file in ZIP archive: %s"), unzErrorString(errcode));
                        }

                        if((errcode = unzGoToFirstFile(tz)) != UNZ_OK)
                        {
                            throw MDFN_Error(0, _("Could not seek to first file in ZIP archive: %s"), unzErrorString(errcode));
                        }
                        break;
                    }
                } // end to while(!FileFound)
            } // end to if(ext)

            if((errcode = unzOpenCurrentFile(tz)) != UNZ_OK)
            {
                throw MDFN_Error(0, _("Could not open file in ZIP archive: %s"), unzErrorString(errcode));
            }

            {
                unz_file_info ufo;
                unzGetCurrentFileInfo((unzFile)tz, &ufo, 0, 0, 0, 0, 0, 0);

                if(ufo.uncompressed_size > MaxROMImageSize)
                    throw MDFN_Error(0, _("ROM image is too large; maximum size allowed is %llu bytes."), (unsigned long long)MaxROMImageSize);

                str.reset(new MemoryStream(ufo.uncompressed_size, true));

                unzReadCurrentFile((unzFile)tz, str->map(), str->size());
            }

            // Don't use MDFN_GetFilePathComponents() here.
            {
                char* ld = strrchr(tempu, '.');

                f_ext = std::string(ld ? ld : "");
                f_fbase = std::string(tempu, ld ? (ld - tempu) : strlen(tempu));
            }
        }
        else // If it's not a zip file, handle it as...another type of file!
        {
            std::unique_ptr<Stream> tfp(new FileStream(path, FileStream::MODE_READ));

            // We'll clean up f_ext to remove the leading period, and convert to lowercase, after
            // the plain vs gzip file handling code below(since gzip handling path will want to strip off an extra extension).
            MDFN_GetFilePathComponents(path, NULL, &f_fbase, &f_ext);

            uint8 gzmagic[3] = { 0 };

            if(tfp->read(gzmagic, 3, false) != 3 || gzmagic[0] != 0x1F || gzmagic[1] != 0x8b || gzmagic[2] != 0x08)
            {
                tfp->seek(0, SEEK_SET);

                if(tfp->size() > MaxROMImageSize)
                    throw MDFN_Error(0, _("ROM image is too large; maximum size allowed is %llu bytes."), (unsigned long long)MaxROMImageSize);

                str = std::move(tfp);
            }
            else                  /* Probably gzip */
            {
                delete tfp.release();

                str.reset(new MemoryStream(new GZFileStream(path, GZFileStream::MODE::READ), MaxROMImageSize));

                MDFN_GetFilePathComponents(f_fbase, NULL, &f_fbase, &f_ext);
            } // End gzip handling
        } // End normal and gzip file handling else to zip

        // Remove leading period in file extension.
        if(f_ext.size() > 0 && f_ext[0] == '.')
            f_ext = f_ext.substr(1);

        // Convert file extension A-Z chars to lowercase, a-z
        for(auto& c : f_ext)
            if(c >= 'A' && c <= 'Z')
                c = 'a' + (c - 'A');

        //printf("|%s| --- |%s|\n", f_fbase.c_str(), f_ext.c_str());
    }
    catch(...)
    {
        if(tz != NULL)
        {
            unzCloseCurrentFile(tz);
            unzClose(tz);
        }

        Close();
        throw;
    }

    if(tz != NULL)
    {
        unzCloseCurrentFile(tz);
        unzClose(tz);
    }
}
Exemplo n.º 24
0
/// Gets a list of the files in the archive.
int ZIP_Wrapper::file_list_info (char* zip_name,
                                 ACE_Double_Linked_List<ZIP_File_Info> &list)
{
  unzFile uf=0;
  char filename_try[MAXFILENAME+16] = "";
  if (zip_name!=0)
    {
      ACE_OS::strncpy(filename_try, zip_name, MAXFILENAME-1);
      /* strncpy doesnt append the trailing NULL, if the string is too long. */
      filename_try[ MAXFILENAME ] = '\0';
      /* open the zip file */
      uf = unzOpen(zip_name);
      /* if zipfile could not be opened, try appending .zip to name */
      if (uf==0)
        {
          ACE_OS::strcat(filename_try, ".zip");
          uf = unzOpen(filename_try);
        }
    }
  /* If zipfile could not be opened still, return */
  if (uf==0)
    {
      DANCE_ERROR (DANCE_LOG_ERROR,
                   (LM_DEBUG, ACE_TEXT("There is some problem in opening")
                    ACE_TEXT(" %s or %s.zip using unzOpen\n"), zip_name, zip_name));
      return 1;
    }
  unz_global_info gi;
  /* get information about all the files in zip file*/
  int err = unzGetGlobalInfo(uf, &gi);
  if (err!=UNZ_OK)
    DANCE_ERROR (DANCE_LOG_ERROR,
                 (LM_DEBUG, ACE_TEXT("unzGetGlobalInfo failed while trying")
                  ACE_TEXT(" to get global information about zipfile\n"), err));
  /* gi.number_entry corresponds to the number of directory entries
     in the zip file */
  for (uLong i=0;i<gi.number_entry;i++)
    {
      char filename_inzip[256];
      unz_file_info file_info;
      /* get information about the current file in zip file */
      err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip,
                                  sizeof(filename_inzip), 0, 0, 0, 0);
      if (err!=UNZ_OK)
        {
          DANCE_ERROR (DANCE_LOG_ERROR,
                       (LM_DEBUG, ACE_TEXT("unzGetCurrentFileInfo failed")
                        ACE_TEXT(" while trying to get information")
                        ACE_TEXT(" about current file\n"), err));
          break;
        }
      ZIP_File_Info* next = 0;
      ACE_NEW_RETURN (next, ZIP_File_Info (filename_inzip,
                      sizeof(filename_inzip)), -1);
      /* add information about current file to the list */
      list.insert_tail (next);
      if ((i+1)<gi.number_entry)
        {
          err = unzGoToNextFile(uf);
          if (err!=UNZ_OK)
          {
            DANCE_ERROR (DANCE_LOG_ERROR,
                         (LM_DEBUG,
                          ACE_TEXT(" unzGoToNextFile failed")
                          ACE_TEXT(" while trying to go to next file\n"),
                          err));
            break;
          }
        }
    }
  unzCloseCurrentFile(uf);
  return gi.number_entry;
}
Exemplo n.º 25
0
int Unzip_execExtract(const char *pszTargetFile, unsigned long ulUserData)
{
	unzFile hUnzip;
	int nRet = UZEXR_FATALERROR;
	if (!___zlib_pfuncCallback) return UZEXR_INVALIDCALLBACK;

	hUnzip = unzOpen(pszTargetFile);
	if (!hUnzip)	return UZEXR_INVALIDFILE;

	do
	{
		char szConFilename[512];
		unz_file_info fileInfo;
		int nLen,i;

		if (unzGetCurrentFileInfo(hUnzip, &fileInfo, szConFilename, sizeof szConFilename, NULL, 0, NULL, 0) != UNZ_OK) {
			nRet = UZEXR_INVALIDFILE;
			break;
		}

		nLen = strlen(szConFilename);
		// ディレクトリの場合
		if (nLen >= 2 && !IsShiftJIS(szConFilename[nLen - 2]) && szConFilename[nLen - 1] == '\\') {
			continue;
		}

		// ファイルの場合、まずコールバックで展開するか聞く
		nRet = ___zlib_pfuncCallback(UZCB_FIND_FILE, fileInfo.uncompressed_size,
		                                0, szConFilename, 0, ulUserData);
		if (nRet == UZCBR_PASS) {
			nRet = unzGoToNextFile(hUnzip);
			if (nRet == UNZ_END_OF_LIST_OF_FILE) {
				nRet = UZEXR_OK;
				break;
			}
			continue;
		}
		else if (nRet == UZCBR_CANCEL) {
			nRet = UZEXR_CANCEL;
			break;
		}

/* たぶん要らない
		for (i = 0; i < nLen; ++i)
		if (szConFilename[i] == '/')
		szConFilename[i] = '\\';	//Windowsなので、\マークがディレクトリの区切りとなる
*/

		// ファイルの場合
		if (unzOpenCurrentFile(hUnzip) != UNZ_OK) {
			nRet = UZEXR_INVALIDFILE;
			break;
		}

		// データの展開
		{
			unsigned char szBuffer[64*1024];
			unsigned long dwSizeRead;
			unsigned long dwBufPosition = 0;
			while ((dwSizeRead = unzReadCurrentFile(hUnzip, szBuffer, sizeof(szBuffer))) > 0)
			{
				nRet = ___zlib_pfuncCallback(UZCB_EXTRACT_PROGRESS, fileInfo.uncompressed_size,
				                                dwBufPosition, szBuffer, dwSizeRead, ulUserData);
				dwBufPosition += dwSizeRead;
				if (nRet == UZCBR_PASS) {
					break;
				}
				else if (nRet == UZCBR_CANCEL) {
					unzCloseCurrentFile(hUnzip);
					unzClose(hUnzip);
					return UZEXR_CANCEL;
				}
			}
		}
		unzCloseCurrentFile(hUnzip);
		nRet = unzGoToNextFile(hUnzip);
		if (nRet == UNZ_END_OF_LIST_OF_FILE) {
			nRet = UZEXR_OK;
			break;
		}
	} while (1);

	unzClose(hUnzip);

	return nRet;	//解凍するものが無いので、解凍しなかった。

}
Exemplo n.º 26
0
static int load_zip_rom(const char *fn) {
    int found = 0;
    unzFile fp;
    unz_file_info inf;
    char fn2[4096];
    char *ext;
    int size;

    /* Open up the file in question. */
    fp = unzOpen(fn);

    if(!fp) {
#ifdef DEBUG
        fprintf(stderr, "chip8_mem_load_rom: Could not open ROM: %s!\n", fn);
#endif
        return ROM_LOAD_E_OPEN;
    }

    if(unzGoToFirstFile(fp) != UNZ_OK) {
#ifdef DEBUG
        fprintf(stderr, "chip8_mem_load_rom: Couldn't find file in zip!\n");
#endif
        unzClose(fp);
        return ROM_LOAD_E_CORRUPT;
    }

    /* Keep looking at files until we find a rom. */
    while(!found) {
        if(unzGetCurrentFileInfo(fp, &inf, fn2, 4096, NULL, 0, NULL,
                                 0) != UNZ_OK) {
#ifdef DEBUG
            fprintf(stderr, "chip8_mem_load_rom: Error parsing Zip file!\n");
#endif
            unzClose(fp);
            return ROM_LOAD_E_CORRUPT;
        }

        /* Check if this file looks like a rom. */
        ext = strrchr(fn2, '.');

        if(ext) {
            /* XXXX */
            if(!strcmp(ext, ".ch8") || !strcmp(ext, ".c8")) {
                found = 1;
            }
        }

        /* If we haven't found a rom yet, move to the next file. */
        if(!found) {
            if(unzGoToNextFile(fp) != UNZ_OK) {
#ifdef DEBUG
                fprintf(stderr, "chip8_mem_load_rom: End of zip file!\n");
#endif
                unzClose(fp);
                return ROM_LOAD_E_NO_ROM;
            }
        }
    }

    /* If the size isn't a nice even amount, round it. */
    size = inf.uncompressed_size;

    if(!(cart_rom = (uint8 *)malloc(size))) {
#ifdef DEBUG
        fprintf(stderr, "chip8_mem_load_rom: Could not load ROM: %s!\n", fn);
        fprintf(stderr, "Reason: %s\n", strerror(errno));
#endif
        unzClose(fp);
        return ROM_LOAD_E_ERRNO;
    }

    /* Attempt to open the file we think is a rom. */
    if(unzOpenCurrentFile(fp) != UNZ_OK) {
#ifdef DEBUG
        fprintf(stderr, "chip8_mem_load_rom: Couldn't open rom from zip!\n");
#endif
        unzClose(fp);
        free(cart_rom);
        cart_rom = NULL;
        return ROM_LOAD_E_CORRUPT;
    }

    /* Attempt to read the file. */
    if(unzReadCurrentFile(fp, cart_rom, size) < 0) {
#ifdef DEBUG
        fprintf(stderr, "chip8_mem_load_rom: Couldn't read rom from zip!\n");
#endif
        unzCloseCurrentFile(fp);
        unzClose(fp);
        free(cart_rom);
        cart_rom = NULL;
        return ROM_LOAD_E_CORRUPT;
    }

    /* We're done with the file, close everything. */
    unzCloseCurrentFile(fp);
    unzClose(fp);

    cart_len = size;
    finalize_load(fn);

    return ROM_LOAD_SUCCESS;
}
Exemplo n.º 27
0
void RunScript(FILE * script, const char * path)
{
	ErrFunc_f old = InstallErrFunc(ScriptError, NULL);
	char * mem;
	int len, ok;
	char	strbuf[1024];
	strcpy(strbuf, path);
	strcat(strbuf, DIR_STR);
	MakeDirExist(strbuf);
	strcat(strbuf, "Installer Log.txt");
	scriptLog = fopen(strbuf, "w");
	if (scriptLog) fprintf(scriptLog, "Installing X-Plane to %s.\n", path);
	char	from_buf[1024], to_buf[1024], partial[1024];
	const char *	app_path = GetApplicationPath();
	if (app_path == NULL)
	{
		return;
	}
	bool	condition = true;
	while (get_line(script, strbuf, sizeof(strbuf)-1))
	{
		char * t;
		char * p = strbuf;
		t = next_token(&p);
		if (t == NULL) continue;
		if (!strcmp(t, "NOCONDITION"))
		{
			condition = true;
		}
		if (!strcmp(t, "ELSE"))
		{
			condition = !condition;
		}
		if (!strcmp(t, "MESSAGE"))
		{
			if (scriptLog) fprintf(scriptLog, "Note: %s\n", p);
			DoUserAlert(p);
		}
		if (!strcmp(t, "CONDITION"))
		{
			if (scriptLog) fprintf(scriptLog, "Checking: %s\n", p);
			condition = ConfirmMessage(p, "Yes", "No");
			if (scriptLog) fprintf(scriptLog, "Answer: %s\n", condition ? "yes" : "no");
		}
		if (!strcmp(t, "UPDATE"))
		{
			if (scriptLog) fprintf(scriptLog, "Running update.\n");
			if (condition)
				RunInstaller(path);
		}
		if (!strcmp(t, "COPY"))
		{
			t = next_token(&p);
			float indi = -1.0;
			sprintf(msgBuf, "Installing %s...", t);
			ShowProgressMessage(msgBuf, &indi);
			strcpy(from_buf, app_path);
			strip_to_delim(from_buf,DIR_CHAR);
			strcat(from_buf, t);
			strcpy(to_buf, path);
			strcat(to_buf, DIR_STR);
			strcat(to_buf, p);
			normalize_dir_chars(to_buf);
			normalize_dir_chars(from_buf);
			if (condition)
			{
				if (scriptLog) fprintf(scriptLog, "Copying %s to %s\n", from_buf, to_buf);
				ok = FileToBlock(from_buf, &mem, &len);
				if (!ok) return;
				ok = BlockToFile(to_buf, mem);
				if (!ok) return;
				free(mem);
			} else {
				if (scriptLog) fprintf(scriptLog, "Not copying %s to %s\n", from_buf, to_buf);
			}
		}
		if (!strcmp(t, "UNZIP"))
		{
			t = next_token(&p);
			sprintf(msgBuf, "Installing %s...", t);
			strcpy(from_buf, app_path);
			strip_to_delim(from_buf,DIR_CHAR);
			strcat(from_buf, t);
			if (!strcmp(p, "/"))
			{
				strcpy(partial, path);
				strcat(partial, DIR_STR);
			} else {
				strcpy(partial, path);
				strcat(partial, DIR_STR);
				strcat(partial, p);
			}
			normalize_dir_chars(partial);
			normalize_dir_chars(from_buf);

			if (condition)
			{
				if (scriptLog) fprintf(scriptLog, "Unzipping %s to %s\n", from_buf, partial);
				unzFile unz = unzOpen(from_buf);
				if (unz == NULL)
				{
					ReportError("Unable to open zip file.", EUNKNOWN, from_buf);
					return;
				}
				unz_global_info		global;
				unzGetGlobalInfo(unz, &global);
				unzGoToFirstFile(unz);
				int counter = 0;
				do {

					char				zip_path[1024];
					unz_file_info		info;
					unzGetCurrentFileInfo(unz, &info, zip_path, sizeof(zip_path),
						NULL, 0, NULL, 0);

					sprintf(msgBuf, "Installing %s...", zip_path);
					float prog = (global.number_entry > 0) ? ((float) counter / (float) global.number_entry) : -1.0;
					ShowProgressMessage(msgBuf, &prog);

					++counter;

					strcpy(to_buf, partial);
					strcat(to_buf, zip_path);
					normalize_dir_chars(to_buf);
					strip_to_delim(to_buf, DIR_CHAR);
					MakeDirExist(to_buf);

					if (info.uncompressed_size == 0)
						continue;

					char * mem = (char *) malloc(info.uncompressed_size);
					if (!mem) { ReportError("Out of memory", ENOMEM, NULL); return; }
					unzOpenCurrentFile(unz);
					int result = unzReadCurrentFile(unz,mem, info.uncompressed_size);
					if (result != info.uncompressed_size)
					{	ReportError("Could not read installer archive.", EUNKNOWN, zip_path); }
					unzCloseCurrentFile(unz);

					strcpy(to_buf, partial);
					strcat(to_buf, zip_path);
					normalize_dir_chars(to_buf);

					FILE * fi = fopen(to_buf, "wb");
					if (fi == NULL)
					{
						ReportError("Could not create file", errno, to_buf);
						return;
					}
					result = fwrite(mem, 1, info.uncompressed_size, fi);
					if (result != info.uncompressed_size)
					{ ReportError("Could not read installer archive.", errno, to_buf); }
					fclose(fi);
					free(mem);
				} while(unzGoToNextFile(unz) == UNZ_OK);
				unzClose(unz);
			} else {
				if (scriptLog) fprintf(scriptLog, "Not unzipping %s to %s\n", from_buf, partial);
			}
		}
	}
	InstallErrFunc(old, NULL);
	if (scriptLog) fprintf(scriptLog, "Installer completed successfully.\n");
	if (scriptLog) fclose(scriptLog);
	DoUserAlert("Installation was successful!");
}
Exemplo n.º 28
0
bool MemFile::open (const std::string &path_, bool uncompress)
{
	MEMORY mem(MAX_IMAGE_SIZE + 1);
	size_t uRead = 0;

	// Check if zlib is available
#ifdef HAVE_ZLIBSTAT
	bool have_zlib = true;
#elif defined(HAVE_ZLIB)
	bool have_zlib = CheckLibrary("zlib", "zlibVersion") && zlibVersion()[0] == ZLIB_VERSION[0];
#else
	bool have_zlib = false;
#endif

#ifdef HAVE_ZLIB
	// Try opening as a zip file
	if (uncompress && have_zlib)
	{
		unzFile hfZip = unzOpen(path_.c_str());
		if (hfZip)
		{
			int nRet;
			unz_file_info sInfo;
			uLong ulMaxSize = 0;

			// Iterate through the contents of the zip looking for a file with a suitable size
			for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
			{
				char szFile[MAX_PATH];

				// Get details of the current file
				unzGetCurrentFileInfo(hfZip, &sInfo, szFile, MAX_PATH, nullptr, 0, nullptr, 0);

				// Ignore directories and empty files
				if (!sInfo.uncompressed_size)
					continue;

				// If the file extension is recognised, read the file contents
				// ToDo: GetFileType doesn't really belong here?
				if (GetFileType(szFile) != ftUnknown && unzOpenCurrentFile(hfZip) == UNZ_OK)
				{
					nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
					unzCloseCurrentFile(hfZip);
					break;
				}

				// Rememeber the largest uncompressed file size
				if (sInfo.uncompressed_size > ulMaxSize)
					ulMaxSize = sInfo.uncompressed_size;
			}

			// Did we fail to find a matching extension?
			if (nRet == UNZ_END_OF_LIST_OF_FILE)
			{
				// Loop back over the archive
				for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
				{
					// Get details of the current file
					unzGetCurrentFileInfo(hfZip, &sInfo, nullptr, 0, nullptr, 0, nullptr, 0);

					// Open the largest file found about
					if (sInfo.uncompressed_size == ulMaxSize && unzOpenCurrentFile(hfZip) == UNZ_OK)
					{
						nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
						unzCloseCurrentFile(hfZip);
						break;
					}
				}
			}

			// Close the zip archive
			unzClose(hfZip);

			// Stop if something went wrong
			if (nRet < 0)
				throw util::exception("zip extraction failed (", nRet, ")");

			uRead = nRet;
			m_compress = Compress::Zip;
		}
		else
		{
			// Open as gzipped or uncompressed
			gzFile gf = gzopen(path_.c_str(), "rb");
			if (gf == Z_NULL)
				throw posix_error(errno, path_.c_str());

			uRead = gzread(gf, mem, static_cast<unsigned>(mem.size));
			m_compress = (gztell(gf) != FileSize(path_)) ? Compress::Gzip : Compress::None;
			gzclose(gf);
		}
	}
	else
#endif // HAVE_ZLIB
	{
		// Open as normal file if we couldn't use zlib above
		FILE *f = fopen(path_.c_str(), "rb");
		if (!f)
			throw posix_error(errno, path_.c_str());

		uRead = fread(mem, 1, mem.size, f);
		fclose(f);
		m_compress = Compress::None;
	}


	// zip compressed? (and not handled above)
	if (uncompress && mem[0U] == 'P' && mem[1U] == 'K')
		throw util::exception("zlib (zlib1.dll) is required for zip support");

	// gzip compressed?
	if (uncompress && mem[0U] == 0x1f && mem[1U] == 0x8b && mem[2U] == 0x08)
	{
		if (!have_zlib)
			throw util::exception("zlib (zlib1.dll) is required for gzip support");

#ifdef HAVE_ZLIB
		MEMORY mem2(MAX_IMAGE_SIZE + 1);
		uint8_t flags = mem[3];
		auto pb = mem.pb + 10, pbEnd = mem.pb + mem.size;

		if (flags & 0x04)	// EXTRA_FIELD
		{
			if (pb < pbEnd - 1)
				pb += 2 + pb[0] + (pb[1] << 8);
		}

		if (flags & 0x08 || flags & 0x10)	// ORIG_NAME or COMMENT
		{
			while (pb < pbEnd && *pb++);
		}

		if (flags & 0x02)	// HEAD_CRC
			pb += 2;

		z_stream stream = {};
		stream.next_in = pb;
		stream.avail_in = (pb < pbEnd) ? static_cast<uInt>(pbEnd - pb) : 0;
		stream.next_out = mem2.pb;
		stream.avail_out = mem2.size;

		auto zerr = inflateInit2(&stream, -MAX_WBITS);
		if (zerr == Z_OK)
		{
			zerr = inflate(&stream, Z_FINISH);
			inflateEnd(&stream);
		}

		if (zerr != Z_STREAM_END)
			throw util::exception("gzip decompression failed (", zerr, ")");

		memcpy(mem.pb, mem2.pb, uRead = stream.total_out);
		m_compress = Compress::Zip;
#endif
	}

	// bzip2 compressed?
	if (uncompress && mem[0U] == 'B' && mem[1U] == 'Z')
	{
#ifdef HAVE_BZIP2
		if (!CheckLibrary("bzip2", "BZ2_bzBuffToBuffDecompress"))
#endif
			throw util::exception("libbz2 (bzip2.dll) is required for bzip2 support");

#ifdef HAVE_BZIP2
		MEMORY mem2(MAX_IMAGE_SIZE + 1);

		auto uBzRead = static_cast<unsigned>(mem2.size);
		auto bzerr = BZ2_bzBuffToBuffDecompress(reinterpret_cast<char *>(mem2.pb), &uBzRead, reinterpret_cast<char *>(mem.pb), uRead, 0, 0);
		if (bzerr != BZ_OK)
			throw util::exception("bzip2 decompression failed (", bzerr, ")");

		memcpy(mem.pb, mem2.pb, uRead = uBzRead);
		m_compress = Compress::Bzip2;
#endif // HAVE_BZIP2
	}

	if (uRead <= MAX_IMAGE_SIZE)
		return open(mem.pb, static_cast<int>(uRead), path_);

	throw util::exception("file size too big");
}
BOOL vmsUnZip::Unpack(LPCTSTR ptszFileName, LPCTSTR ptszDstFolder)
{
	USES_CONVERSION;
	BOOL result = FALSE;
    unzFile zipFile = unzOpen (CT2AEX<> ((LPTSTR)ptszFileName));
    if (NULL != zipFile) 
    {
        if (UNZ_OK == unzGoToFirstFile(zipFile))
        {
            BOOL bContinue = TRUE;
            while (bContinue) 
            {
                result = FALSE;
                unz_file_info fi;
                char filename[MAX_PATH] = {0};
                if (UNZ_OK == unzGetCurrentFileInfo(zipFile, &fi, 
                    filename, sizeof (filename), 0, 0, 0, 0))
                {
					if (*filename && (filename [strlen (filename)-1] == '/' || filename [strlen (filename)-1] == '\\'))
					{
						assert (fi.uncompressed_size == 0);
						tstring tstr = ptszDstFolder;
						tstr += '\\';
						tstr += CA2TEX<> (filename);
						tstr += '1';
						vmsBuildPathToFile (tstr.c_str ());
						result = TRUE;
					}
					else if (UNZ_OK == unzOpenCurrentFile(zipFile))
                    {
                        UINT dataLen = fi.uncompressed_size;
                        BYTE* fileData = new BYTE[dataLen];
                        if (!fileData) 
                            break;
                        if(dataLen == unzReadCurrentFile(zipFile, fileData, dataLen))
                        {
                            char filePathName[MAX_PATH] = {0};
                            strcat (filePathName, T2A ((LPTSTR)ptszDstFolder));
                            strcat (filePathName, "\\");
                            strcat (filePathName, filename);
							while (strchr (filePathName, '/'))
								*strchr (filePathName, '/') = '\\';
							FILE* pFile = fopen (filePathName, "wb");
							if (!pFile)
							{
								vmsBuildPathToFile (CA2TEX<> (filePathName));
								pFile = fopen (filePathName, "wb");
							}
							if (pFile)
							{
								result = (dataLen == fwrite(fileData, 1, dataLen, pFile));
								result = result && (0 == fclose(pFile));
							}
                        }
                        delete [] fileData;
						result = result && (UNZ_OK == unzCloseCurrentFile(zipFile));
                    }
                }
                if (!result) 
                    break;
                if (UNZ_END_OF_LIST_OF_FILE == unzGoToNextFile(zipFile))
                    bContinue = FALSE;
            }
        }
        result = result && (UNZ_OK == unzClose(zipFile));
    }
    return result;
}
Exemplo n.º 30
0
void read_dx_file() {
  int i,err;
  char buff[80];
  unzFile dat;
  UINT8 *buffer;
  unz_file_info file_info;
/*   int start,end; */
/*   short *src; */

  if (!dx_file[0])
    return;
  if (raine_nb_samples && emudx_samples && sample_data) {
    return;
  }

  dat = unzOpen(dx_file);
  if (!dat) return;
  for (raine_nb_samples=1; raine_nb_samples<32; raine_nb_samples++) {
    sprintf(buff,"%d.wav",raine_nb_samples);
    err = unzLocateFile(dat,buff,2);
    if (err != UNZ_OK)
      break;
  }
  raine_nb_samples--;

  emudx_samples = (struct wave_spec*)AllocateMem((raine_nb_samples+1) * sizeof(struct wave_spec));
  AddSaveData(ASCII_ID('S','A','M','P'),
	      (UINT8*)emudx_samples,
	      (raine_nb_samples+1) * sizeof(struct wave_spec));

  sample_data = (struct private_data*)AllocateMem((raine_nb_samples+1)*sizeof(struct private_data));
  for (i=1; i<=raine_nb_samples; i++) {
    sprintf(buff,"%d.wav",i);
    unzLocateFile(dat,buff,2);

    err = unzOpenCurrentFile(dat);
    unzGetCurrentFileInfo(dat,&file_info,NULL,0,NULL,0,NULL,0);
    buffer = malloc(file_info.uncompressed_size);
    unzReadCurrentFile(dat,buffer,file_info.uncompressed_size);
    emudx_samples[i].pos = emudx_samples[i].playing = 0;
#ifdef SDL
  SDL_RWops *rw;
  unsigned int len_in_bytes;
  SDL_AudioCVT  wav_cvt;
  SDL_AudioSpec wave;
  UINT8 *wav_buffer;
    extern SDL_AudioSpec gotspec;
    if (!gotspec.freq) {
	/* Now read_dx_file is called before the soundcard init, so we
	 * must put sensible default values here... */
	gotspec.freq = audio_sample_rate;
	gotspec.channels = 2;
	gotspec.format = AUDIO_S16;
    }
    rw = SDL_RWFromMem(buffer, file_info.uncompressed_size);
    if (!SDL_LoadWAV_RW(rw,1,&wave,&wav_buffer,&len_in_bytes)) {
      printf("couldn't load sample %d: %s\n",i,SDL_GetError());
      exit(1);
    }
    unzCloseCurrentFile(dat);	// Is this needed when open failed?

    if (SDL_BuildAudioCVT(&wav_cvt,
			  wave.format, wave.channels, wave.freq,
			  gotspec.format, gotspec.channels,gotspec.freq) == -1) {
      printf("can't build converter\n");
      exit(1);
    }

    wav_cvt.buf = sample_data[i].data = AllocateMem(len_in_bytes*wav_cvt.len_mult);
    sample_data[i].len =len_in_bytes*wav_cvt.len_ratio;
    wav_cvt.len = len_in_bytes;
    memcpy(sample_data[i].data, wav_buffer, len_in_bytes);
    SDL_FreeWAV(wav_buffer);

    SDL_ConvertAudio(&wav_cvt);
#else
    convert_wav((char*)buffer,file_info.uncompressed_size,
	    (char**)&sample_data[i].data,&sample_data[i].len);
#endif
    free(buffer);
  }
  unzClose(dat);
}